Here are the examples of the csharp api System.IO.TextWriter.WriteLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1281 Examples
19
Source : Program.cs
with MIT License
from 0x0ade
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 : Program.cs
with zlib License
from 0x0ade
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 : Disassembler.cs
with MIT License
from 0xd4d
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 : Program.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static void Disreplacedemble(DisasmJobContext context, DisasmJob job) {
var (writer, disposeWriter) = job.GetTextWriter();
try {
var methods = job.Methods;
Array.Sort(methods, SortMethods);
for (int i = 0; i < methods.Length; i++) {
if (i > 0)
writer.WriteLine();
var method = methods[i];
context.Disreplacedembler.Disreplacedemble(context.Formatter, writer, method);
}
}
finally {
if (disposeWriter)
writer.Dispose();
}
}
19
Source : DebugProgramTemplate.cs
with MIT License
from 71
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 : DellFanCmd.cs
with GNU General Public License v3.0
from AaronKelley
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 : Ecoji.cs
with MIT License
from abock
with MIT License
from abock
public static void Encode(Stream input, TextWriter output, int wrap = 0)
{
if (input is null)
throw new ArgumentNullException(nameof(input));
if (output is null)
throw new ArgumentNullException(nameof(output));
var wrapLineProgress = 0;
var b = new byte[5];
while (true)
{
var read = 0;
while (read < b.Length)
{
var n = input.Read(b, read, b.Length - read);
read += n;
if (n == 0)
break;
}
if (read <= 0) {
if (wrapLineProgress > 0)
output.WriteLine();
break;
}
for (var i = read; i < b.Length; i++)
b[i] = 0;
output.WriteRune(emojis[b[0] << 2 | b[1] >> 6]);
switch (read)
{
case 1:
output.WriteRune(padding);
output.WriteRune(padding);
output.WriteRune(padding);
break;
case 2:
output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
output.WriteRune(padding);
output.WriteRune(padding);
break;
case 3:
output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
output.WriteRune(emojis[(b[2] & 0x0f) << 6 | b[3] >> 2]);
output.WriteRune(padding);
break;
case 4:
output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
output.WriteRune(emojis[(b[2] & 0x0f) << 6 | b[3] >> 2]);
var pad4 = (b[3] & 0x03) switch
{
0 => padding40,
1 => padding41,
2 => padding42,
3 => padding43,
_ => 0
};
if (pad4 > 0)
output.WriteRune(pad4);
break;
case 5:
output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
output.WriteRune(emojis[(b[2] & 0x0f) << 6 | b[3] >> 2]);
output.WriteRune(emojis[(b[3] & 0x03) << 8 | b[4]]);
break;
}
if (wrap > 0)
{
wrapLineProgress += 4;
if (wrapLineProgress >= wrap)
{
output.WriteLine();
wrapLineProgress = 0;
}
}
}
19
Source : Program.cs
with MIT License
from abock
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
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 : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
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 : RecipeSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(uint recipeId, IList<RecipeMod> input, StreamWriter writer)
{
foreach (var value in input)
{
writer.WriteLine();
writer.WriteLine("INSERT INTO `recipe_mod` (`recipe_Id`, `executes_On_Success`, `health`, `stamina`, `mana`, `unknown_7`, `data_Id`, `unknown_9`, `instance_Id`)");
var output = $"VALUES ({recipeId}, {value.ExecutesOnSuccess}, {value.Health}, {value.Stamina}, {value.Mana}, {value.Unknown7}, {(value.DataId > 0 ? $"0x{value.DataId:X8}" : $"{value.DataId}")}, {value.Unknown9}, {value.InstanceId});";
output = FixNullFields(output);
writer.WriteLine(output);
if ((value.RecipeModsInt != null && value.RecipeModsInt.Count > 0) ||
(value.RecipeModsDID != null && value.RecipeModsDID.Count > 0) ||
(value.RecipeModsIID != null && value.RecipeModsIID.Count > 0) ||
(value.RecipeModsFloat != null && value.RecipeModsFloat.Count > 0) ||
(value.RecipeModsString != null && value.RecipeModsString.Count > 0) ||
(value.RecipeModsBool != null && value.RecipeModsBool.Count > 0))
{
writer.WriteLine();
writer.WriteLine("SET @parent_id = LAST_INSERT_ID();");
}
if (value.RecipeModsInt != null && value.RecipeModsInt.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.RecipeModsInt.ToList(), writer);
}
if (value.RecipeModsDID != null && value.RecipeModsDID.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.RecipeModsDID.ToList(), writer);
}
if (value.RecipeModsIID != null && value.RecipeModsIID.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.RecipeModsIID.ToList(), writer);
}
if (value.RecipeModsFloat != null && value.RecipeModsFloat.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.RecipeModsFloat.ToList(), writer);
}
if (value.RecipeModsString != null && value.RecipeModsString.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.RecipeModsString.ToList(), writer);
}
if (value.RecipeModsBool != null && value.RecipeModsBool.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.RecipeModsBool.ToList(), writer);
}
}
}
19
Source : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(uint id, IList<BiotaPropertiesEmote> input, StreamWriter writer)
{
foreach (var value in input)
{
writer.WriteLine();
writer.WriteLine("INSERT INTO `biota_properties_emote` (`object_Id`, `category`, `probability`, `biota_Clreplaced_Id`, `style`, `substyle`, `quest`, `vendor_Type`, `min_Health`, `max_Health`)");
var categoryLabel = Enum.GetName(typeof(EmoteCategory), value.Category);
if (categoryLabel != null)
categoryLabel = $" /* {categoryLabel} */";
string weenieClreplacedIdLabel = null;
if (WeenieNames != null && value.WeenieClreplacedId.HasValue)
{
WeenieNames.TryGetValue(value.WeenieClreplacedId.Value, out weenieClreplacedIdLabel);
if (weenieClreplacedIdLabel != null)
weenieClreplacedIdLabel = $" /* {weenieClreplacedIdLabel} */";
}
string styleLabel = null;
if (value.Style.HasValue)
{
styleLabel = Enum.GetName(typeof(MotionStance), value.Style.Value);
if (styleLabel != null)
styleLabel = $" /* {styleLabel} */";
}
string substyleLabel = null;
if (value.Substyle.HasValue)
{
substyleLabel = Enum.GetName(typeof(MotionCommand), value.Substyle.Value);
if (substyleLabel != null)
substyleLabel = $" /* {substyleLabel} */";
}
string vendorTypeLabel = null;
if (value.VendorType.HasValue)
{
vendorTypeLabel = Enum.GetName(typeof(VendorType), value.VendorType.Value);
if (vendorTypeLabel != null)
vendorTypeLabel = $" /* {vendorTypeLabel} */";
}
var output = "VALUES (" +
$"{id}, " +
$"{value.Category.ToString().PadLeft(2)}{categoryLabel}, " +
$"{value.Probability.ToString(CultureInfo.InvariantCulture).PadLeft(6)}, " +
$"{value.WeenieClreplacedId}{weenieClreplacedIdLabel}, " +
$"{value.Style}{styleLabel}, " +
$"{value.Substyle}{substyleLabel}, " +
$"{GetSQLString(value.Quest)}, " +
$"{value.VendorType}{vendorTypeLabel}, " +
$"{value.MinHealth}, " +
$"{value.MaxHealth}" +
");";
output = FixNullFields(output);
writer.WriteLine(output);
if (value.BiotaPropertiesEmoteAction != null && value.BiotaPropertiesEmoteAction.Count > 0)
{
writer.WriteLine();
writer.WriteLine("SET @parent_id = LAST_INSERT_ID();");
writer.WriteLine();
CreateSQLINSERTStatement(value.BiotaPropertiesEmoteAction.OrderBy(r => r.Order).ToList(), writer);
}
}
}
19
Source : LandblockInstanceWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(IList<LandblockInstance> input, StreamWriter writer)
{
var instanceWcids = input.ToDictionary(i => i.Guid, i => i.WeenieClreplacedId);
input = input.OrderBy(r => r.Guid).ToList();
foreach (var value in input)
{
if (value != input[0])
writer.WriteLine();
writer.WriteLine("INSERT INTO `landblock_instance` (`guid`, `weenie_Clreplaced_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)");
string label = null;
if (WeenieNames != null)
WeenieNames.TryGetValue(value.WeenieClreplacedId, out label);
var output = "VALUES (" +
$"0x{value.Guid.ToString("X8")}, " +
$"{value.WeenieClreplacedId.ToString().PadLeft(5)}, " +
$"0x{value.ObjCellId:X8}, " +
$"{TrimNegativeZero(value.OriginX):0.######}, " +
$"{TrimNegativeZero(value.OriginY):0.######}, " +
$"{TrimNegativeZero(value.OriginZ):0.######}, " +
$"{TrimNegativeZero(value.AnglesW):0.######}, " +
$"{TrimNegativeZero(value.AnglesX):0.######}, " +
$"{TrimNegativeZero(value.AnglesY):0.######}, " +
$"{TrimNegativeZero(value.AnglesZ):0.######}, " +
$"{value.IsLinkChild.ToString().PadLeft(5)}, " +
$"'{value.LastModified:yyyy-MM-dd HH:mm:ss}'" +
$"); /* {label} */" +
Environment.NewLine + $"/* @teleloc 0x{value.ObjCellId:X8} [{TrimNegativeZero(value.OriginX):F6} {TrimNegativeZero(value.OriginY):F6} {TrimNegativeZero(value.OriginZ):F6}] {TrimNegativeZero(value.AnglesW):F6} {TrimNegativeZero(value.AnglesX):F6} {TrimNegativeZero(value.AnglesY):F6} {TrimNegativeZero(value.AnglesZ):F6} */";
output = FixNullFields(output);
writer.WriteLine(output);
if (value.LandblockInstanceLink != null && value.LandblockInstanceLink.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.LandblockInstanceLink.OrderBy(r => r.ChildGuid).ToList(), instanceWcids, writer);
}
}
}
19
Source : WeenieSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(Weenie input, StreamWriter writer)
{
writer.WriteLine("INSERT INTO `weenie` (`clreplaced_Id`, `clreplaced_Name`, `type`, `last_Modified`)");
var output = $"VALUES ({input.ClreplacedId}, '{input.ClreplacedName}', {input.Type}, '{input.LastModified:yyyy-MM-dd HH:mm:ss}') /* {Enum.GetName(typeof(WeenieType), input.Type)} */;";
output = FixNullFields(output);
writer.WriteLine(output);
if (input.WeeniePropertiesInt != null && input.WeeniePropertiesInt.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesInt.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesInt64 != null && input.WeeniePropertiesInt64.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesInt64.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesBool != null && input.WeeniePropertiesBool.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesBool.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesFloat != null && input.WeeniePropertiesFloat.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesFloat.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesString != null && input.WeeniePropertiesString.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesString.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesDID != null && input.WeeniePropertiesDID.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesDID.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesPosition != null && input.WeeniePropertiesPosition.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesPosition.OrderBy(r => r.PositionType).ToList(), writer);
}
if (input.WeeniePropertiesIID != null && input.WeeniePropertiesIID.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesIID.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesAttribute != null && input.WeeniePropertiesAttribute.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesAttribute.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesAttribute2nd != null && input.WeeniePropertiesAttribute2nd.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesAttribute2nd.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesSkill != null && input.WeeniePropertiesSkill.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesSkill.OrderBy(r => r.Type).ToList(), writer);
}
if (input.WeeniePropertiesBodyPart != null && input.WeeniePropertiesBodyPart.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesBodyPart.OrderBy(r => r.Key).ToList(), writer);
}
if (input.WeeniePropertiesSpellBook != null && input.WeeniePropertiesSpellBook.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesSpellBook.ToList(), writer);
}
if (input.WeeniePropertiesEventFilter != null && input.WeeniePropertiesEventFilter.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesEventFilter.OrderBy(r => r.Event).ToList(), writer);
}
if (input.WeeniePropertiesEmote != null && input.WeeniePropertiesEmote.Count > 0)
{
//writer.WriteLine(); // This is not needed because CreateSQLINSERTStatement will take care of it for us on each Recipe.
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesEmote.OrderBy(r => r.Category).ToList(), writer);
}
if (input.WeeniePropertiesCreateList != null && input.WeeniePropertiesCreateList.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesCreateList.OrderBy(r => r.DestinationType).ToList(), writer);
}
if (input.WeeniePropertiesBook != null)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesBook, writer);
}
if (input.WeeniePropertiesBookPageData != null && input.WeeniePropertiesBookPageData.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesBookPageData.OrderBy(r => r.PageId).ToList(), writer);
}
if (input.WeeniePropertiesGenerator != null && input.WeeniePropertiesGenerator.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesGenerator.ToList(), writer);
}
if (input.WeeniePropertiesPalette != null && input.WeeniePropertiesPalette.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesPalette.OrderBy(r => r.SubPaletteId).ToList(), writer);
}
if (input.WeeniePropertiesTextureMap != null && input.WeeniePropertiesTextureMap.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesTextureMap.OrderBy(r => r.Index).ToList(), writer);
}
if (input.WeeniePropertiesAnimPart != null && input.WeeniePropertiesAnimPart.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.ClreplacedId, input.WeeniePropertiesAnimPart.OrderBy(r => r.Index).ToList(), writer);
}
}
19
Source : RecipeSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(Recipe input, StreamWriter writer)
{
writer.WriteLine("INSERT INTO `recipe` (`id`, `unknown_1`, `skill`, `difficulty`, `salvage_Type`, `success_W_C_I_D`, `success_Amount`, `success_Message`, `fail_W_C_I_D`, `fail_Amount`, `fail_Message`, " +
"`success_Destroy_Source_Chance`, `success_Destroy_Source_Amount`, `success_Destroy_Source_Message`, `success_Destroy_Target_Chance`, `success_Destroy_Target_Amount`, `success_Destroy_Target_Message`, " +
"`fail_Destroy_Source_Chance`, `fail_Destroy_Source_Amount`, `fail_Destroy_Source_Message`, `fail_Destroy_Target_Chance`, `fail_Destroy_Target_Amount`, `fail_Destroy_Target_Message`, " +
"`data_Id`, `last_Modified`)");
string skillLabel = null;
if (input.Skill != 0)
skillLabel = Enum.GetName(typeof(Skill), input.Skill);
string successWeenieLabel = null;
if (WeenieNames != null)
WeenieNames.TryGetValue(input.SuccessWCID, out successWeenieLabel);
string failWeenieLabel = null;
if (WeenieNames != null)
WeenieNames.TryGetValue(input.FailWCID, out failWeenieLabel);
var output = "VALUES (" +
$"{input.Id}, " +
$"{input.Unknown1}, " +
$"{input.Skill} /* {skillLabel} */, " +
$"{input.Difficulty}, " +
$"{input.SalvageType}, " +
$"{input.SuccessWCID} /* {successWeenieLabel} */, " +
$"{input.SuccessAmount}, " +
$"{GetSQLString(input.SuccessMessage)}, " +
$"{input.FailWCID} /* {failWeenieLabel} */, " +
$"{input.FailAmount}, " +
$"{GetSQLString(input.FailMessage)}, " +
$"{input.SuccessDestroySourceChance}, " +
$"{input.SuccessDestroySourceAmount}, " +
$"{GetSQLString(input.SuccessDestroySourceMessage)}, " +
$"{input.SuccessDestroyTargetChance}, " +
$"{input.SuccessDestroyTargetAmount}, " +
$"{GetSQLString(input.SuccessDestroyTargetMessage)}, " +
$"{input.FailDestroySourceChance}, " +
$"{input.FailDestroySourceAmount}, " +
$"{GetSQLString(input.FailDestroySourceMessage)}, " +
$"{input.FailDestroyTargetChance}, " +
$"{input.FailDestroyTargetAmount}, " +
$"{GetSQLString(input.FailDestroyTargetMessage)}, " +
$"{input.DataId}, " +
$"'{input.LastModified:yyyy-MM-dd HH:mm:ss}'" +
");";
output = FixNullFields(output);
writer.WriteLine(output);
if (input.RecipeRequirementsInt != null && input.RecipeRequirementsInt.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.RecipeRequirementsInt.ToList(), writer);
}
if (input.RecipeRequirementsDID != null && input.RecipeRequirementsDID.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.RecipeRequirementsDID.ToList(), writer);
}
if (input.RecipeRequirementsIID != null && input.RecipeRequirementsIID.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.RecipeRequirementsIID.ToList(), writer);
}
if (input.RecipeRequirementsFloat != null && input.RecipeRequirementsFloat.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.RecipeRequirementsFloat.ToList(), writer);
}
if (input.RecipeRequirementsString != null && input.RecipeRequirementsString.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.RecipeRequirementsString.ToList(), writer);
}
if (input.RecipeRequirementsBool != null && input.RecipeRequirementsBool.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.RecipeRequirementsBool.ToList(), writer);
}
if (input.RecipeMod != null && input.RecipeMod.Count > 0)
{
//writer.WriteLine(); // This is not needed because CreateSQLINSERTStatement will take care of it for us on each Recipe.
CreateSQLINSERTStatement(input.Id, input.RecipeMod.ToList(), writer);
}
}
19
Source : CharacterSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(Character input, StreamWriter writer)
{
writer.WriteLine("INSERT INTO `character` (`id`, `account_Id`, `name`, `is_Plussed`, `is_Deleted`, `delete_Time`, `last_Login_Timestamp`, `total_Logins`, `character_Options_1`, `character_Options_2`, `gameplay_Options`, `spellbook_Filters`, `hair_Texture`, `default_Hair_Texture`)");
var output = $"VALUES ({input.Id}, {input.AccountId}, {GetSQLString(input.Name)}, {input.IsPlussed}, {input.IsDeleted}, {input.DeleteTime}, {input.LastLoginTimestamp}, {input.TotalLogins}, {input.CharacterOptions1}, {input.CharacterOptions2}, {input.GameplayOptions}, {input.SpellbookFilters}, {input.HairTexture}, {input.DefaultHairTexture});";
output = FixNullFields(output);
writer.WriteLine(output);
if (input.CharacterPropertiesContractRegistry != null && input.CharacterPropertiesContractRegistry.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesContractRegistry.OrderBy(r => r.ContractId).ToList(), writer);
}
if (input.CharacterPropertiesFillCompBook != null && input.CharacterPropertiesFillCompBook.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesFillCompBook.OrderBy(r => r.SpellComponentId).ToList(), writer);
}
if (input.CharacterPropertiesFriendList != null && input.CharacterPropertiesFriendList.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesFriendList.OrderBy(r => r.FriendId).ToList(), writer);
}
if (input.CharacterPropertiesQuestRegistry != null && input.CharacterPropertiesQuestRegistry.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesQuestRegistry.OrderBy(r => r.QuestName).ToList(), writer);
}
if (input.CharacterPropertiesShortcutBar != null && input.CharacterPropertiesShortcutBar.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesShortcutBar.OrderBy(r => r.ShortcutBarIndex).ToList(), writer);
}
if (input.CharacterPropertiesSpellBar != null && input.CharacterPropertiesSpellBar.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesSpellBar.OrderBy(r => r.SpellBarNumber).ThenBy(r => r.SpellBarIndex).ToList(), writer);
}
if (input.CharacterPropertiesreplacedleBook != null && input.CharacterPropertiesreplacedleBook.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(input.Id, input.CharacterPropertiesreplacedleBook.OrderBy(r => r.replacedleId).ToList(), writer);
}
}
19
Source : WeenieSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void CreateSQLINSERTStatement(uint weenieClreplacedID, IList<WeeniePropertiesEmote> input, StreamWriter writer)
{
foreach (var value in input)
{
writer.WriteLine();
writer.WriteLine("INSERT INTO `weenie_properties_emote` (`object_Id`, `category`, `probability`, `weenie_Clreplaced_Id`, `style`, `substyle`, `quest`, `vendor_Type`, `min_Health`, `max_Health`)");
var categoryLabel = Enum.GetName(typeof(EmoteCategory), value.Category);
if (categoryLabel != null)
categoryLabel = $" /* {categoryLabel} */";
string weenieClreplacedIdLabel = null;
if (WeenieNames != null && value.WeenieClreplacedId.HasValue)
{
WeenieNames.TryGetValue(value.WeenieClreplacedId.Value, out weenieClreplacedIdLabel);
if (weenieClreplacedIdLabel != null)
weenieClreplacedIdLabel = $" /* {weenieClreplacedIdLabel} */";
}
string styleLabel = null;
if (value.Style.HasValue)
{
styleLabel = Enum.GetName(typeof(MotionStance), value.Style.Value);
if (styleLabel != null)
styleLabel = $" /* {styleLabel} */";
}
string substyleLabel = null;
if (value.Substyle.HasValue)
{
substyleLabel = Enum.GetName(typeof(MotionCommand), value.Substyle.Value);
if (substyleLabel != null)
substyleLabel = $" /* {substyleLabel} */";
}
string vendorTypeLabel = null;
if (value.VendorType.HasValue)
{
vendorTypeLabel = Enum.GetName(typeof(VendorType), value.VendorType.Value);
if (vendorTypeLabel != null)
vendorTypeLabel = $" /* {vendorTypeLabel} */";
}
var output = "VALUES (" +
$"{weenieClreplacedID}, " +
$"{value.Category.ToString().PadLeft(2)}{categoryLabel}, " +
$"{value.Probability.ToString("0.######", CultureInfo.InvariantCulture).PadLeft(6)}, " +
$"{value.WeenieClreplacedId}{weenieClreplacedIdLabel}, " +
$"{(value.Style.HasValue ? "0x" : "")}{value.Style:X8}{styleLabel}, " +
$"{(value.Substyle.HasValue ? "0x" : "")}{value.Substyle:X8}{substyleLabel}, " +
$"{GetSQLString(value.Quest)}, " +
$"{value.VendorType}{vendorTypeLabel}, " +
$"{value.MinHealth:0.######}, " +
$"{value.MaxHealth:0.######}" +
");";
output = FixNullFields(output);
writer.WriteLine(output);
if (value.WeeniePropertiesEmoteAction != null && value.WeeniePropertiesEmoteAction.Count > 0)
{
writer.WriteLine();
writer.WriteLine("SET @parent_id = LAST_INSERT_ID();");
writer.WriteLine();
CreateSQLINSERTStatement(value.WeeniePropertiesEmoteAction.OrderBy(r => r.Order).ToList(), writer);
}
}
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
public void Generate(TextWriter writer, POCatalog catalog)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (catalog == null)
throw new ArgumentNullException(nameof(catalog));
if (!HasFlags(Flags.IgnoreEncoding))
{
if (writer.Encoding.GetByteCount(" ") > 1)
throw new ArgumentException(Resources.EncodingNotSingleByte, nameof(writer));
if (catalog.Encoding == null || Encoding.GetEncoding(catalog.Encoding).WebName != writer.Encoding.WebName)
throw new ArgumentException(Resources.EncodingMismatch, nameof(writer));
}
_writer = writer;
_catalog = catalog;
_stringBreak = "\"" + _writer.NewLine + "\"";
_lineStartIndex = 0;
try
{
WriteEntry(CreateHeaderEntry(), _ => { });
for (int i = 0, n = catalog.Count; i < n; i++)
WriteEntry(catalog[i], w => w.WriteLine());
}
finally
{
_builder.Clear();
if (_builder.Capacity > 1024)
_builder.Capacity = 1024;
}
}
19
Source : Formatter.cs
with MIT License
from adrianoc
with MIT License
from adrianoc
public static void WriteMethodBody(TextWriter writer, MethodDefinition method)
{
var body = method.Body;
WriteVariables(writer, body);
foreach (var instruction in body.Instructions)
{
var sequence_point = method.DebugInformation.GetSequencePoint(instruction);
if (sequence_point != null)
{
writer.Write('\t');
WriteSequencePoint(writer, sequence_point);
writer.WriteLine();
}
writer.Write('\t');
WriteInstruction(writer, instruction);
writer.WriteLine();
}
WriteExceptionHandlers(writer, body);
}
19
Source : Tester.cs
with Mozilla Public License 2.0
from agebullhu
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 : DecompileFullOutput.cs
with GNU General Public License v3.0
from ahmed605
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
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 : DecompileScruffOutput.cs
with GNU General Public License v3.0
from ahmed605
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 : VariablesOutput.cs
with GNU General Public License v3.0
from ahmed605
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 : Program.cs
with GNU General Public License v3.0
from ahmed605
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
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 : CodePathOutput.cs
with GNU General Public License v3.0
from ahmed605
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
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 : CancerspaceInspector.cs
with GNU General Public License v3.0
from AkaiMage
with GNU General Public License v3.0
from AkaiMage
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) {
if (!initialized) {
customRenderQueue = (materialEditor.target as Material).shader.renderQueue;
rng = new System.Random();
initialized = true;
}
cancerfree = (materialEditor.target as Material).shader.name.Contains("Cancerfree");
GUIStyle defaultStyle = new GUIStyle(EditorStyles.foldout);
defaultStyle.fontStyle = FontStyle.Bold;
defaultStyle.onNormal = EditorStyles.boldLabel.onNormal;
defaultStyle.onFocused = EditorStyles.boldLabel.onFocused;
List<CSCategory> categories = new List<CSCategory>();
categories.Add(new CSCategory(Styles.falloffSettingsreplacedle, defaultStyle, me => {
CSProperty falloffCurve = FindProperty("_FalloffCurve", props);
CSProperty falloffDepth = FindProperty("_DepthFalloff", props);
CSProperty falloffColor = FindProperty("_ColorFalloff", props);
DisplayRegularProperty(me, falloffCurve);
if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_MinFalloff", props));
DisplayRegularProperty(me, FindProperty("_MaxFalloff", props));
DisplayRegularProperty(me, falloffDepth);
if (falloffDepth.prop.floatValue > .5) {
CSProperty falloffDepthCurve = FindProperty("_DepthFalloffCurve", props);
DisplayRegularProperty(me, falloffDepthCurve);
if (falloffDepthCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_DepthMinFalloff", props));
DisplayRegularProperty(me, FindProperty("_DepthMaxFalloff", props));
}
DisplayRegularProperty(me, falloffColor);
if (falloffColor.prop.floatValue > .5) {
CSProperty falloffColorCurve = FindProperty("_ColorFalloffCurve", props);
DisplayRegularProperty(me, FindProperty("_ColorChannelForFalloff", props));
DisplayRegularProperty(me, falloffColorCurve);
if (falloffColorCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_ColorMinFalloff", props));
DisplayRegularProperty(me, FindProperty("_ColorMaxFalloff", props));
}
}));
categories.Add(new CSCategory(Styles.particleSystemSettingsreplacedle, defaultStyle, me => {
CSProperty falloffCurve = FindProperty("_LifetimeFalloffCurve", props);
CSProperty falloff = FindProperty("_LifetimeFalloff", props);
DisplayRegularProperty(me, FindProperty("_ParticleSystem", props));
DisplayRegularProperty(me, falloff);
if (falloff.prop.floatValue > .5) {
DisplayRegularProperty(me, falloffCurve);
if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_LifetimeMinFalloff", props));
DisplayRegularProperty(me, FindProperty("_LifetimeMaxFalloff", props));
}
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.screenShakeSettingsreplacedle, defaultStyle, me => {
DisplayFloatWithSliderMode(me, FindProperty("_XShake", props));
DisplayFloatWithSliderMode(me, FindProperty("_YShake", props));
DisplayFloatWithSliderMode(me, FindProperty("_XShakeSpeed", props));
DisplayFloatWithSliderMode(me, FindProperty("_YShakeSpeed", props));
DisplayFloatWithSliderMode(me, FindProperty("_ShakeAmplitude", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.wobbleSettingsreplacedle, defaultStyle, me => {
DisplayFloatRangeProperty(me, FindProperty("_XWobbleAmount", props));
DisplayFloatRangeProperty(me, FindProperty("_YWobbleAmount", props));
DisplayFloatRangeProperty(me, FindProperty("_XWobbleTiling", props));
DisplayFloatRangeProperty(me, FindProperty("_YWobbleTiling", props));
DisplayFloatWithSliderMode(me, FindProperty("_XWobbleSpeed", props));
DisplayFloatWithSliderMode(me, FindProperty("_YWobbleSpeed", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.blurSettingsreplacedle, defaultStyle, me => {
DisplayFloatWithSliderMode(me, FindProperty("_BlurRadius", props));
DisplayIntSlider(me, FindProperty("_BlurSampling", props), 1, 5);
DisplayRegularProperty(me, FindProperty("_AnimatedSampling", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.distortionMapSettingsreplacedle, defaultStyle, me => {
CSProperty distortionType = FindProperty("_DistortionType", props);
CSProperty distortionMapRotation = FindProperty("_DistortionMapRotation", props);
CSProperty distortionAmplitude = FindProperty("_DistortionAmplitude", props);
CSProperty distortionRotation = FindProperty("_DistortionRotation", props);
CSProperty distortFlipbook = FindProperty("_DistortFlipbook", props);
DisplayRegularProperty(me, distortionType);
DisplayRegularProperty(me, FindProperty("_DistortionTarget", props));
switch ((int) distortionType.prop.floatValue) {
case 0:
DisplayRegularProperty(me, FindProperty("_BumpMap", props));
DisplayFloatWithSliderMode(me, distortionMapRotation);
DisplayFloatWithSliderMode(me, distortionAmplitude);
DisplayFloatWithSliderMode(me, distortionRotation);
DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedX", props));
DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedY", props));
break;
case 1:
DisplayRegularProperty(me, FindProperty("_MeltMap", props));
DisplayFloatWithSliderMode(me, distortionMapRotation);
DisplayFloatWithSliderMode(me, distortionAmplitude);
DisplayFloatWithSliderMode(me, distortionRotation);
DisplayFloatWithSliderMode(me, FindProperty("_MeltController", props));
DisplayFloatWithSliderMode(me, FindProperty("_MeltActivationScale", props));
break;
}
DisplayRegularProperty(me, distortFlipbook);
if (distortFlipbook.prop.floatValue != 0) {
DisplayIntField(me, FindProperty("_DistortFlipbookTotalFrames", props));
DisplayIntField(me, FindProperty("_DistortFlipbookStartFrame", props));
DisplayIntField(me, FindProperty("_DistortFlipbookRows", props));
DisplayIntField(me, FindProperty("_DistortFlipbookColumns", props));
DisplayFloatProperty(me, FindProperty("_DistortFlipbookFPS", props));
}
}));
categories.Add(new CSCategory(Styles.overlaySettingsreplacedle, defaultStyle, me => {
CSProperty overlayImageType = FindProperty("_OverlayImageType", props);
CSProperty overlayImage = FindProperty("_MainTex", props);
CSProperty overlayRotation = FindProperty("_MainTexRotation", props);
CSProperty overlayPixelate = FindProperty("_PixelatedSampling", props);
CSProperty overlayScrollSpeedX = FindProperty("_MainTexScrollSpeedX", props);
CSProperty overlayScrollSpeedY = FindProperty("_MainTexScrollSpeedY", props);
CSProperty overlayBoundary = FindProperty("_OverlayBoundaryHandling", props);
CSProperty overlayColor = FindProperty("_OverlayColor", props);
if (!cancerfree) BlendModePopup(me, FindProperty("_BlendMode", props));
DisplayRegularProperty(me, overlayImageType);
switch ((int) overlayImageType.prop.floatValue) {
// TODO: replace these with proper enums so there's no magic numbers
case 0:
DisplayRegularProperty(me, overlayBoundary);
DisplayRegularProperty(me, overlayPixelate);
me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
me.TextureScaleOffsetProperty(overlayImage.prop);
DisplayFloatWithSliderMode(me, overlayRotation);
if (overlayBoundary.prop.floatValue != 0) {
DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
}
break;
case 1:
DisplayRegularProperty(me, overlayBoundary);
DisplayRegularProperty(me, overlayPixelate);
me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
me.TextureScaleOffsetProperty(overlayImage.prop);
DisplayFloatWithSliderMode(me, overlayRotation);
if (overlayBoundary.prop.floatValue != 0) {
DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
}
DisplayIntField(me, FindProperty("_FlipbookTotalFrames", props));
DisplayIntField(me, FindProperty("_FlipbookStartFrame", props));
DisplayIntField(me, FindProperty("_FlipbookRows", props));
DisplayIntField(me, FindProperty("_FlipbookColumns", props));
DisplayFloatProperty(me, FindProperty("_FlipbookFPS", props));
break;
case 2:
DisplayRegularProperty(me, FindProperty("_OverlayCubemap", props));
DisplayColorProperty(me, overlayColor);
DisplayVec3WithSliderMode(
me,
"Rotation",
FindProperty("_OverlayCubemapRotationX", props),
FindProperty("_OverlayCubemapRotationY", props),
FindProperty("_OverlayCubemapRotationZ", props)
);
DisplayVec3WithSliderMode(
me,
"Rotation Speed",
FindProperty("_OverlayCubemapSpeedX", props),
FindProperty("_OverlayCubemapSpeedY", props),
FindProperty("_OverlayCubemapSpeedZ", props)
);
break;
}
DisplayFloatRangeProperty(me, FindProperty("_BlendAmount", props));
}));
if (cancerfree) categories.Add(new CSCategory(Styles.blendSettingsreplacedle, defaultStyle, me => {
DisplayRegularProperty(me, FindProperty("_BlendOp", props));
DisplayRegularProperty(me, FindProperty("_BlendSource", props));
DisplayRegularProperty(me, FindProperty("_BlendDestination", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.screenColorAdjustmentsreplacedle, defaultStyle, me => {
CSProperty colorBurningToggle = FindProperty("_Burn", props);
DisplayVec3WithSliderMode(
me,
"HSV Add",
FindProperty("_HueAdd", props),
FindProperty("_SaturationAdd", props),
FindProperty("_ValueAdd", props)
);
DisplayVec3WithSliderMode(
me,
"HSV Multiply",
FindProperty("_HueMultiply", props),
FindProperty("_SaturationMultiply", props),
FindProperty("_ValueMultiply", props)
);
DisplayFloatRangeProperty(me, FindProperty("_InversionAmount", props));
DisplayColorProperty(me, FindProperty("_Color", props));
BlendModePopup(me, FindProperty("_ScreenColorBlendMode", props));
DisplayRegularProperty(me, colorBurningToggle);
if (colorBurningToggle.prop.floatValue == 1) {
DisplayFloatRangeProperty(me, FindProperty("_BurnLow", props));
DisplayFloatRangeProperty(me, FindProperty("_BurnHigh", props));
}
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.screenTransformreplacedle, defaultStyle, me => {
DisplayRegularProperty(me, FindProperty("_ScreenBoundaryHandling", props));
DisplayRegularProperty(me, FindProperty("_ScreenReprojection", props));
DisplayFloatWithSliderMode(me, FindProperty("_Zoom", props));
DisplayRegularProperty(me, FindProperty("_Pixelation", props));
CSProperty screenXOffsetR = FindProperty("_ScreenXOffsetR", props);
CSProperty screenXOffsetG = FindProperty("_ScreenXOffsetG", props);
CSProperty screenXOffsetB = FindProperty("_ScreenXOffsetB", props);
CSProperty screenXOffsetA = FindProperty("_ScreenXOffsetA", props);
CSProperty screenYOffsetR = FindProperty("_ScreenYOffsetR", props);
CSProperty screenYOffsetG = FindProperty("_ScreenYOffsetG", props);
CSProperty screenYOffsetB = FindProperty("_ScreenYOffsetB", props);
CSProperty screenYOffsetA = FindProperty("_ScreenYOffsetA", props);
CSProperty screenXMultiplierR = FindProperty("_ScreenXMultiplierR", props);
CSProperty screenXMultiplierG = FindProperty("_ScreenXMultiplierG", props);
CSProperty screenXMultiplierB = FindProperty("_ScreenXMultiplierB", props);
CSProperty screenXMultiplierA = FindProperty("_ScreenXMultiplierA", props);
CSProperty screenYMultiplierR = FindProperty("_ScreenYMultiplierR", props);
CSProperty screenYMultiplierG = FindProperty("_ScreenYMultiplierG", props);
CSProperty screenYMultiplierB = FindProperty("_ScreenYMultiplierB", props);
CSProperty screenYMultiplierA = FindProperty("_ScreenYMultiplierA", props);
if (sliderMode) {
DisplayFloatRangeProperty(me, screenXOffsetA);
DisplayFloatRangeProperty(me, screenYOffsetA);
DisplayFloatRangeProperty(me, screenXOffsetR);
DisplayFloatRangeProperty(me, screenYOffsetR);
DisplayFloatRangeProperty(me, screenXOffsetG);
DisplayFloatRangeProperty(me, screenYOffsetG);
DisplayFloatRangeProperty(me, screenXOffsetB);
DisplayFloatRangeProperty(me, screenYOffsetB);
DisplayFloatRangeProperty(me, screenXMultiplierA);
DisplayFloatRangeProperty(me, screenYMultiplierA);
DisplayFloatRangeProperty(me, screenXMultiplierR);
DisplayFloatRangeProperty(me, screenYMultiplierR);
DisplayFloatRangeProperty(me, screenXMultiplierG);
DisplayFloatRangeProperty(me, screenYMultiplierG);
DisplayFloatRangeProperty(me, screenXMultiplierB);
DisplayFloatRangeProperty(me, screenYMultiplierB);
} else {
DisplayVec4Field(me, "Screen X Offset (RGB)", screenXOffsetR, screenXOffsetG, screenXOffsetB, screenXOffsetA);
DisplayVec4Field(me, "Screen Y Offset (RGB)", screenYOffsetR, screenYOffsetG, screenYOffsetB, screenYOffsetA);
DisplayVec4Field(me, "Screen X Multiplier (RGB)", screenXMultiplierR, screenXMultiplierG, screenXMultiplierB, screenXMultiplierA);
DisplayVec4Field(me, "Screen Y Multiplier (RGB)", screenYMultiplierR, screenYMultiplierG, screenYMultiplierB, screenYMultiplierA);
}
DisplayFloatRangeProperty(me, FindProperty("_ScreenRotationAngle", props));
}));
categories.Add(new CSCategory(Styles.targetObjectSettingsreplacedle, defaultStyle, me => {
DisplayVec4Field(
me,
"Position",
FindProperty("_ObjectPositionX", props),
FindProperty("_ObjectPositionY", props),
FindProperty("_ObjectPositionZ", props),
FindProperty("_ObjectPositionA", props)
);
DisplayVec3Field(
me,
"Rotation",
FindProperty("_ObjectRotationX", props),
FindProperty("_ObjectRotationY", props),
FindProperty("_ObjectRotationZ", props)
);
DisplayVec4Field(
me,
"Scale",
FindProperty("_ObjectScaleX", props),
FindProperty("_ObjectScaleY", props),
FindProperty("_ObjectScaleZ", props),
FindProperty("_ObjectScaleA", props)
);
DisplayRegularProperty(me, FindProperty("_Puffiness", props));
}));
categories.Add(new CSCategory(Styles.stencilreplacedle, defaultStyle, me => {
DisplayIntSlider(me, FindProperty("_StencilRef", props), 0, 255);
DisplayRegularProperty(me, FindProperty("_StencilComp", props));
DisplayRegularProperty(me, FindProperty("_StencilPreplacedOp", props));
DisplayRegularProperty(me, FindProperty("_StencilFailOp", props));
DisplayRegularProperty(me, FindProperty("_StencilZFailOp", props));
DisplayIntSlider(me, FindProperty("_StencilReadMask", props), 0, 255);
DisplayIntSlider(me, FindProperty("_StencilWriteMask", props), 0, 255);
}));
categories.Add(new CSCategory(Styles.maskingreplacedle, defaultStyle, me => {
if (!cancerfree) {
DisplayRegularProperty(me, FindProperty("_DistortionMask", props));
DisplayFloatRangeProperty(me, FindProperty("_DistortionMaskOpacity", props));
}
DisplayRegularProperty(me, FindProperty("_OverlayMask", props));
DisplayFloatRangeProperty(me, FindProperty("_OverlayMaskOpacity", props));
DisplayRegularProperty(me, FindProperty("_OverallEffectMask", props));
DisplayFloatRangeProperty(me, FindProperty("_OverallEffectMaskOpacity", props));
BlendModePopup(me, FindProperty("_OverallEffectMaskBlendMode", props));
EditorGUILayout.Space();
DisplayRegularProperty(me, FindProperty("_OverallAmplitudeMask", props));
DisplayFloatRangeProperty(me, FindProperty("_OverallAmplitudeMaskOpacity", props));
}));
categories.Add(new CSCategory(Styles.miscSettingsreplacedle, defaultStyle, me => {
DisplayRegularProperty(me, FindProperty("_CullMode", props));
DisplayRegularProperty(me, FindProperty("_ZTest", props));
DisplayRegularProperty(me, FindProperty("_ZWrite", props));
ShowColorMaskFlags(me, FindProperty("_ColorMask", props));
DisplayRegularProperty(me, FindProperty("_MirrorMode", props));
DisplayRegularProperty(me, FindProperty("_EyeSelector", props));
DisplayRegularProperty(me, FindProperty("_PlatformSelector", props));
CSProperty projectionType = FindProperty("_ProjectionType", props);
DisplayRegularProperty(me, projectionType);
if (projectionType.prop.floatValue != 2) {
DisplayVec3WithSliderMode(
me,
Styles.projectionRotationText,
FindProperty("_ProjectionRotX", props),
FindProperty("_ProjectionRotY", props),
FindProperty("_ProjectionRotZ", props)
);
}
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.renderQueueExportreplacedle, defaultStyle, me => {
Material material = me.target as Material;
customRenderQueue = EditorGUILayout.IntSlider(Styles.customRenderQueueSliderText, customRenderQueue, 0, 5000);
if (GUILayout.Button(Styles.exportCustomRenderQueueButtonText)) {
int relativeQueue = customRenderQueue - ((int) UnityEngine.Rendering.RenderQueue.Transparent);
string newQueueString = "Transparent" + (relativeQueue >= 0 ? "+" : "") + relativeQueue;
string shaderName = "RedMage/Cancer" + (cancerfree ? "free" : "space");
string newShaderPath = shaderName + " Queue " + customRenderQueue;
string shaderPath = replacedetDatabase.GetreplacedetPath(material.shader.GetInstanceID());
string outputLocation = shaderPath.Substring(0, shaderPath.Replace("\\", "/").LastIndexOf('/') + 1) + "CancerspaceQueue" + customRenderQueue + ".shader";
try {
using (StreamWriter sw = new StreamWriter(outputLocation)) {
using (StreamReader sr = new StreamReader(shaderPath)) {
string line;
while ((line = sr.ReadLine()) != null) {
if (line.Contains("\"Transparent+")) {
Regex rx = new Regex(@"Transparent[+-]\d+", RegexOptions.Compiled);
MatchCollection matches = rx.Matches(line);
foreach (Match match in matches) {
line = line.Replace(match.Value, newQueueString);
}
} else if (line.Contains(shaderName)) {
Regex rx = new Regex("\"[^\"]+\"", RegexOptions.Compiled);
MatchCollection matches = rx.Matches(line);
foreach (Match match in matches) {
line = line.Replace(match.Value, "\"" + newShaderPath + "\"");
}
}
if (!cancerfree) line = line.Replace("_Garb", "_Garb" + customRenderQueue);
sw.Write(line);
sw.WriteLine();
}
}
}
} catch (Exception e) {
Debug.Log("AAAGAGHH WHAT? HOW? WHY??? WHAT ARE YOU DOING? Shader file could not be read / written.");
Debug.Log(e.Message);
return;
}
replacedetDatabase.Refresh();
material.shader = Shader.Find(newShaderPath);
replacedetDatabase.Savereplacedets();
}
}));
EditorGUIUtility.labelWidth = 0f;
sliderMode = EditorGUILayout.ToggleLeft(Styles.sliderModeCheckboxText, sliderMode);
showRandomizerOptions = EditorGUILayout.ToggleLeft(Styles.randomizerOptionsCheckboxText, showRandomizerOptions);
if (showRandomizerOptions) {
randomizingCurrentPreplaced = GUILayout.Button("Randomize Values");
}
int oldflags = GetExpansionFlags();
int newflags = 0;
for (int i = 0; i < categories.Count; ++i) {
bool expanded = EditorGUILayout.Foldout((oldflags & (1 << i)) != 0, categories[i].name, true, categories[i].style);
newflags |= (expanded ? 1 : 0) << i;
if (expanded) {
EditorGUI.indentLevel++;
categories[i].setupDelegate(materialEditor);
EditorGUI.indentLevel--;
}
}
SetExpansionFlags(newflags);
if (!cancerfree) GUI.enabled = false;
materialEditor.RenderQueueField();
randomizingCurrentPreplaced = false;
}
19
Source : SerilogTextFormatter.cs
with MIT License
from akasarto
with MIT License
from akasarto
public void Format(LogEvent logEvent, TextWriter output)
{
output.WriteLine($"[{logEvent.Level.ToUpperCaseString()}] [{logEvent.Timestamp}] {logEvent.RenderMessage()}");
output.WriteLine();
foreach (var prop in logEvent.Properties)
{
output.WriteLine($" - {prop.Key}: {prop.Value}");
}
if (logEvent.Exception != null)
{
output.WriteLine();
output.WriteLine($" - {logEvent.Exception}");
}
output.WriteLine();
output.WriteLine("-------------------------------------------------------");
output.WriteLine();
}
19
Source : JsonTextWriter.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected override void WriteIndent()
{
_writer.WriteLine();
// levels of indentation multiplied by the indent count
int currentIndentCount = Top * _indentation;
if (currentIndentCount > 0)
{
if (_indentChars == null)
{
_indentChars = new string(_indentChar, 10).ToCharArray();
}
while (currentIndentCount > 0)
{
int writeCount = Math.Min(currentIndentCount, 10);
_writer.Write(_indentChars, 0, writeCount);
currentIndentCount -= writeCount;
}
}
}
19
Source : MainProgram.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception)args.ExceptionObject;
string errorLogLoc = Path.Combine(dataFolderLocation, "error_log.txt");
string subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
RegistryKey thekey = Registry.LocalMachine;
RegistryKey skey = thekey.OpenSubKey(subKey);
string windowsVersionName = skey.GetValue("ProductName").ToString();
string rawWindowsVersion = Environment.OSVersion.ToString();
int totalExecutions = 0;
foreach (int action in Properties.Settings.Default.TotalActionsExecuted) {
totalExecutions += action;
}
if (File.Exists(errorLogLoc))
try {
File.Delete(errorLogLoc);
} catch {
DoDebug("Failed to delete error log");
}
if (!File.Exists(errorLogLoc)) {
try {
using (var tw = new StreamWriter(errorLogLoc, true)) {
tw.WriteLine("OS;");
tw.WriteLine("- " + windowsVersionName);
tw.WriteLine("- " + rawWindowsVersion);
tw.WriteLine();
tw.WriteLine("ACC info;");
tw.WriteLine("- Version; " + softwareVersion + ", " + releaseDate);
tw.WriteLine("- UID; " + Properties.Settings.Default.UID);
tw.WriteLine("- Running from; " + currentLocationFull);
tw.WriteLine("- Start with Windows; " + (ACCStartsWithWindows() ? "[Yes]" : "[No]"));
tw.WriteLine("- Check for updates; " + (Properties.Settings.Default.CheckForUpdates ? "[Yes]" : "[No]"));
tw.WriteLine("- In beta program; " + (Properties.Settings.Default.BetaProgram ? "[Yes]" : "[No]"));
tw.WriteLine("- Has completed setup guide; " + (Properties.Settings.Default.HasCompletedTutorial ? "[Yes]" : "[No]"));
tw.WriteLine("- Check path; " + CheckPath());
tw.WriteLine("- Check extension; " + Properties.Settings.Default.ActionFileExtension);
tw.WriteLine("- Actions executed; " + totalExecutions);
tw.WriteLine("- replacedistant type; " + "[Google replacedistant: " + Properties.Settings.Default.replacedistantType[0] + "] [Alexa: " + Properties.Settings.Default.replacedistantType[1] + "] [Unknown: " + Properties.Settings.Default.replacedistantType[1] + "]");
tw.WriteLine();
tw.WriteLine(e);
tw.Close();
}
} catch {
//Caught exception when trying to log exception... *sigh*
}
}
File.AppendAllText(errorLogLoc, DateTime.Now.ToString() + ": " + e + Environment.NewLine);
if (debug) {
Console.WriteLine(e);
}
MessageBox.Show("A critical error occurred. The developer has been notified and will resolve this issue ASAP! Try and start ACC again, and avoid whatever just made it crash (for now) :)", "ACC | Error");
}
19
Source : MixtureDocumentationWindow.cs
with MIT License
from alelievr
with MIT License
from alelievr
void GenerateNodeMarkdownDoc(BaseNodeView view)
{
using (var fs = new FileStream(nodeManualDir + view.nodeTarget.GetType().ToString() + ".md", FileMode.OpenOrCreate))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs))
{
// Append replacedle
sw.WriteLine($"# {view.nodeTarget.name}");
// Add link to node image
sw.WriteLine($"![{view.nodeTarget.GetType()}]({GetImageLink(view.nodeTarget)})");
// Add node input tooltips
if (view.inputPortViews.Count > 0)
{
sw.WriteLine($"## Inputs");
sw.WriteLine("Port Name | Description");
sw.WriteLine("--- | ---");
foreach (var pv in view.inputPortViews)
sw.WriteLine($"{pv.portData.displayName} | {pv.portData.tooltip ?? ""}");
}
// Empty line to end the table
sw.WriteLine();
// Add node output tooltips
if (view.outputPortViews.Count > 0)
{
sw.WriteLine($"## Output");
sw.WriteLine("Port Name | Description");
sw.WriteLine("--- | ---");
foreach (var pv in view.outputPortViews)
sw.WriteLine($"{pv.portData.displayName} | {pv.portData.tooltip ?? ""}");
}
// Empty line to end the table
sw.WriteLine();
sw.WriteLine("## Description");
// Add node doreplacedentation if any
var docAttr = view.nodeTarget.GetType().GetCustomAttribute<DoreplacedentationAttribute>();
if (docAttr != null)
{
sw.WriteLine(docAttr.markdown.Trim());
}
sw.WriteLine();
if (view.nodeTarget is ShaderNode s)
{
// In case a node doesn't support all dimensions:
if (s.supportedDimensions.Count != 3)
{
sw.WriteLine("Please note that this node only support " + string.Join(" and ", s.supportedDimensions) + " dimension(s).");
}
}
sw.Flush();
}
}
}
19
Source : MixtureDocumentationWindow.cs
with MIT License
from alelievr
with MIT License
from alelievr
void GenerateNodeIndexFiles(List<BaseNodeView> nodeViews)
{
using (var fs = new FileStream(nodeManualDir + nodeIndexFile, FileMode.OpenOrCreate))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs))
{
foreach (var nodeView in nodeViews)
{
sw.WriteLine($"[{GetNodeName(nodeView)}]({nodeView.nodeTarget.GetType()}.md) ");
sw.WriteLine();
}
sw.Flush();
}
}
// We also generate toc.yml in the nodes folder
using (var fs = new FileStream(nodeManualDir + "toc.yml", FileMode.OpenOrCreate))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs))
{
foreach (var nodeView in nodeViews)
{
sw.WriteLine($"- name: {GetNodeName(nodeView)}");
sw.WriteLine($" href: {nodeView.nodeTarget.GetType().ToString()}.md");
}
}
}
}
19
Source : CrashHandler.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private static void CreateCrashLog(string directory, Exception exception)
{
StreamWriter writer = null;
try
{
string filePath = Path.Combine(directory, "crash.log");
writer = new StreamWriter(filePath);
writer.WriteLine(string.Format(
Strings.SendLogFile, Properties.Resources.MailAddress));
writer.WriteLine();
writer.WriteLine("Version: {0}", Program.GetVersionString());
writer.WriteLine("Mono: {0}", MonoHelper.IsRunningOnMono ? "yes" : "no");
if (MonoHelper.IsRunningOnMono)
writer.WriteLine("Mono version: {0}", MonoHelper.Version);
writer.WriteLine("OS: {0}", Environment.OSVersion.VersionString);
writer.WriteLine();
writer.WriteLine(exception.Message);
Exception innerException = exception.InnerException;
while (innerException != null)
{
writer.WriteLine(innerException.Message);
innerException = innerException.InnerException;
}
writer.WriteLine();
writer.WriteLine(exception.StackTrace);
}
catch
{
// Do nothing
}
finally
{
if (writer != null)
writer.Close();
}
}
19
Source : Computer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private static void NewSection(TextWriter writer) {
for (int i = 0; i < 8; i++)
writer.Write("----------");
writer.WriteLine();
writer.WriteLine();
}
19
Source : Logger.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void CreateNewLogFile() {
IList<ISensor> list = new List<ISensor>();
SensorVisitor visitor = new SensorVisitor(sensor => {
list.Add(sensor);
});
visitor.VisitComputer(computer);
sensors = list.ToArray();
identifiers = sensors.Select(s => s.Identifier.ToString()).ToArray();
using (StreamWriter writer = new StreamWriter(fileName, false)) {
writer.Write(",");
for (int i = 0; i < sensors.Length; i++) {
writer.Write(sensors[i].Identifier);
if (i < sensors.Length - 1)
writer.Write(",");
else
writer.WriteLine();
}
writer.Write("Time,");
for (int i = 0; i < sensors.Length; i++) {
writer.Write('"');
writer.Write(sensors[i].Name);
writer.Write('"');
if (i < sensors.Length - 1)
writer.Write(",");
else
writer.WriteLine();
}
}
}
19
Source : Logger.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void Log() {
var now = DateTime.Now;
if (lastLoggedTime + LoggingInterval - new TimeSpan(5000000) > now)
return;
if (day != now.Date || !File.Exists(fileName)) {
day = now.Date;
fileName = GetFileName(day);
if (!OpenExistingLogFile())
CreateNewLogFile();
}
try {
using (StreamWriter writer = new StreamWriter(new FileStream(fileName,
FileMode.Append, FileAccess.Write, FileShare.ReadWrite))) {
writer.Write(now.ToString("G", CultureInfo.InvariantCulture));
writer.Write(",");
for (int i = 0; i < sensors.Length; i++) {
if (sensors[i] != null) {
float? value = sensors[i].Value;
if (value.HasValue)
writer.Write(
value.Value.ToString("R", CultureInfo.InvariantCulture));
}
if (i < sensors.Length - 1)
writer.Write(",");
else
writer.WriteLine();
}
}
} catch (IOException) { }
lastLoggedTime = now;
}
19
Source : Computer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public string GetReport() {
using (StringWriter w = new StringWriter(CultureInfo.InvariantCulture)) {
w.WriteLine();
w.WriteLine("Open Hardware Monitor Report");
w.WriteLine();
Version version = typeof(Computer).replacedembly.GetName().Version;
NewSection(w);
w.Write("Version: "); w.WriteLine(version.ToString());
w.WriteLine();
NewSection(w);
w.Write("Common Language Runtime: ");
w.WriteLine(Environment.Version.ToString());
w.Write("Operating System: ");
w.WriteLine(Environment.OSVersion.ToString());
w.Write("Process Type: ");
w.WriteLine(IntPtr.Size == 4 ? "32-Bit" : "64-Bit");
w.WriteLine();
string r = Ring0.GetReport();
if (r != null) {
NewSection(w);
w.Write(r);
w.WriteLine();
}
NewSection(w);
w.WriteLine("Sensors");
w.WriteLine();
foreach (IGroup group in groups) {
foreach (IHardware hardware in group.Hardware)
ReportHardwareSensorTree(hardware, w, "");
}
w.WriteLine();
NewSection(w);
w.WriteLine("Parameters");
w.WriteLine();
foreach (IGroup group in groups) {
foreach (IHardware hardware in group.Hardware)
ReportHardwareParameterTree(hardware, w, "");
}
w.WriteLine();
foreach (IGroup group in groups) {
string report = group.GetReport();
if (!string.IsNullOrEmpty(report)) {
NewSection(w);
w.Write(report);
}
IHardware[] hardwareArray = group.Hardware;
foreach (IHardware hardware in hardwareArray)
ReportHardware(hardware, w);
}
return w.ToString();
}
}
19
Source : TextReportWriter.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void WriteHeader(Header h)
{
if (h.Text == null)
{
return;
}
WriteLine(h);
if (h.Level == 1)
{
this.WriteLine("=".Repeat(h.Text.Length));
}
this.WriteLine();
}
19
Source : TextReportWriter.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void WriteParagraph(Paragraph p)
{
foreach (string line in p.Text.SplitLines(this.MaxLineLength))
{
WriteLine(line);
}
this.WriteLine();
}
19
Source : TextReportWriter.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void WriteTable(Table t)
{
this.tableCounter++;
this.WriteLine(string.Format("Table {0}. {1}", this.tableCounter, t.Caption));
this.WriteLine();
int rows = t.Rows.Count;
int cols = t.Columns.Count;
var columnWidth = new int[cols];
int totalLength = 0;
for (int j = 0; j < cols; j++)
{
columnWidth[j] = 0;
foreach (var tr in t.Rows)
{
TableCell cell = tr.Cells[j];
string text = cell.Content;
columnWidth[j] = Math.Max(columnWidth[j], text != null ? text.Length : 0);
}
totalLength += columnWidth[j];
}
// WriteLine("-".Repeat(totalLength));
foreach (var tr in t.Rows)
{
for (int j = 0; j < cols; j++)
{
TableCell cell = tr.Cells[j];
string text = cell.Content;
this.Write(GetCellText(j, cols, PadString(text, t.Columns[j].Alignment, columnWidth[j])));
}
this.WriteLine();
}
this.WriteLine();
}
19
Source : WikiReportWriter.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void WriteTable(Table t)
{
this.tableCounter++;
this.WriteLine(string.Format("Table {0}. {1}", this.tableCounter, t.Caption));
this.WriteLine();
int rows = t.Rows.Count;
int cols = t.Columns.Count;
var columnWidth = new int[cols];
int totalLength = 0;
for (int j = 0; j < cols; j++)
{
columnWidth[j] = 0;
foreach (var tr in t.Rows)
{
TableCell cell = tr.Cells[j];
string text = cell.Content;
columnWidth[j] = Math.Max(columnWidth[j], text != null ? text.Length : 0);
}
totalLength += columnWidth[j];
}
// WriteLine("-".Repeat(totalLength));
foreach (var tr in t.Rows)
{
for (int j = 0; j < cols; j++)
{
TableCell cell = tr.Cells[j];
string text = cell.Content;
bool isHeader = tr.IsHeader || t.Columns[j].IsHeader;
this.Write(GetCellText(j, cols, PadString(text, t.Columns[j].Alignment, columnWidth[j]), isHeader));
}
this.WriteLine();
}
this.WriteLine();
}
19
Source : StochasticOscillator.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Save()
{
try
{
if (string.IsNullOrWhiteSpace(Name))
{
return;
}
using (StreamWriter writer = new StreamWriter(@"Engine\" + Name + @".txt", false))
{
TypeCalculationAverage = MovingAverageTypeCalculation.Simple;
writer.WriteLine(P1);
writer.WriteLine(P2);
writer.WriteLine(P3);
writer.WriteLine(TypeCalculationAverage);
writer.WriteLine();
writer.WriteLine(ColorUp.ToArgb());
writer.WriteLine(ColorDown.ToArgb());
writer.WriteLine(PaintOn);
writer.Close();
}
}
catch (Exception)
{
// send to log
// отправить в лог
}
}
19
Source : RedirectFS.cs
with MIT License
from alhimik45
with MIT License
from alhimik45
private static void ShowHelp ()
{
Console.Error.WriteLine ("usage: redirectfs [options] mountpoint basedir:");
FileSystem.ShowFuseHelp ("redirectfs");
Console.Error.WriteLine ();
Console.Error.WriteLine ("redirectfs options:");
Console.Error.WriteLine (" basedir Directory to mirror");
}
19
Source : RedirectFS-FH.cs
with MIT License
from alhimik45
with MIT License
from alhimik45
private static void ShowHelp ()
{
Console.Error.WriteLine ("usage: redirectfs [options] mountpoint:");
FileSystem.ShowFuseHelp ("redirectfs-fh");
Console.Error.WriteLine ();
Console.Error.WriteLine ("redirectfs-fh options");
Console.Error.WriteLine (" basedir Directory to mirror");
}
19
Source : ImageMetaData.cs
with Apache License 2.0
from alibaba
with Apache License 2.0
from alibaba
public void SaveMetaDate()
{
using (StreamWriter sw = new StreamWriter(metaPath, false))
{
sw.WriteLine(raw_name);
sw.WriteLine("" + width + "\t" + height);
sw.WriteLine(vPoly.Count);
foreach (Poly poly in vPoly)
{
sw.WriteLine(poly.angle);
foreach (Point p in poly.rgP)
{
sw.Write("" + p.X + "\t" + p.Y + "\t");
}
sw.WriteLine();
sw.WriteLine(poly.name);
}
}
}
19
Source : Config.cs
with MIT License
from altugbakan
with MIT License
from altugbakan
public static void CreateConfigurationFile()
{
StreamWriter file = new StreamWriter(configurationFile);
file.WriteLine("# Set your requested accessories here. Separate items on a category using commas.");
file.WriteLine("# You can leave a category empty for \"none\". Mouths cannot be \"none\".");
file.WriteLine("# Any category that is not included will be accepted as \"category: any\"");
file.WriteLine("glreplacedes: any");
file.WriteLine("hats: none, cap, beanie-banano");
file.WriteLine("misc: none");
file.WriteLine("mouths: any");
file.WriteLine("shirts-pants: tshirt-short-white");
file.WriteLine("shoes: # left empty for \"none\"");
file.WriteLine("# tails not included for \"any\".");
file.WriteLine();
file.WriteLine("# Set the amount of MonKey requests in each batch. Leave empty for default (100).");
file.WriteLine("request-amount: 100");
file.WriteLine();
file.WriteLine("# Set true if you want your MonKey data to be saved to a .txt file. Leave empty for default (false).");
file.WriteLine("log-data: true");
file.Close();
}
19
Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
protected override void DoRun()
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try
{
try
{
// Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
mgmtServer.Start();
try
{
try
{
// Purge stale log files.
var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
{
SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
if (File.GetLastWriteTimeUtc(f) <= timestamp)
{
try { File.Delete(LogPath); }
catch { }
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception) { /* Failure to remove stale log files is not fatal. */ }
try
{
// Save OpenVPN configuration file.
using (var fs = new FileStream(
ConfigurationPath,
FileMode.Create,
FileAccess.Write,
FileShare.Read,
1048576,
FileOptions.SequentialScan))
using (var sw = new StreamWriter(fs))
{
// Save profile's configuration to file.
if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
{
// Remove options on the OpenVPNRemoveOptions list on the fly.
using (var sr = new StringReader(ProfileConfig))
{
string inlineTerm = null;
bool inlineRemove = false;
for (; ; )
{
var line = sr.ReadLine();
if (line == null)
break;
var trimmedLine = line.Trim();
if (!string.IsNullOrEmpty(trimmedLine))
{
// Not an empty line.
if (inlineTerm == null)
{
// Not inside an inline option block = Regular parsing mode.
if (!trimmedLine.StartsWith("#") &&
!trimmedLine.StartsWith(";"))
{
// Not a comment.
var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
if (option.Count > 0)
{
if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
{
// Start of an inline option.
var o = option[0].Substring(1, option[0].Length - 2);
inlineTerm = "</" + o + ">";
inlineRemove = openVPNRemoveOptions.Contains(o);
if (inlineRemove)
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
else if (openVPNRemoveOptions.Contains(option[0]))
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
}
}
else
{
// Inside an inline option block.
if (inlineRemove)
{
// Remove the inline option content.
line = "# " + line;
}
if (trimmedLine == inlineTerm)
{
// Inline option terminator found. Returning to regular parsing mode.
inlineTerm = null;
}
}
}
sw.WriteLine(line);
}
}
}
else
sw.Write(ProfileConfig);
// Append eduVPN Client specific configuration directives.
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# eduVPN Client for Windows");
// Introduce ourself (to OpenVPN server).
var replacedembly = replacedembly.GetExecutingreplacedembly();
var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
var replacedemblyVersion = replacedembly?.GetName()?.Version;
sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));
// Configure log file (relative to WorkingFolder).
sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));
// Configure interaction between us and openvpn.exe.
sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
sw.WriteLine("management-client");
sw.WriteLine("management-hold");
sw.WriteLine("management-query-preplacedwords");
sw.WriteLine("management-query-remote");
// Configure client certificate.
sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
// Ask when username/preplacedword is denied.
sw.WriteLine("auth-retry interact");
sw.WriteLine("auth-nocache");
// Set Wintun interface to be used.
sw.Write("windows-driver wintun\n");
sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");
#if DEBUG
// Renegotiate data channel every 5 minutes in debug versions.
sw.WriteLine("reneg-sec 300");
#endif
if (Environment.OSVersion.Version < new Version(6, 2))
{
// Windows 7 is using tiny 8kB send/receive socket buffers by default.
// Increase to 64kB which is default from Windows 8 on.
sw.WriteLine("sndbuf 65536");
sw.WriteLine("rcvbuf 65536");
}
var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
{
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# Added by OpenVPNAddOptions setting:");
sw.WriteLine(openVPNAddOptions);
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }
bool retry;
do
{
retry = false;
// Connect to OpenVPN Interactive Service to launch the openvpn.exe.
using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
{
var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
try
{
openvpnInteractiveServiceConnection.Connect(
string.Format("openvpn{0}\\service", InstanceName),
WorkingFolder,
new string[] { "--config", ConnectionId + ".conf", },
mgmtPreplacedword + "\n",
3000,
SessionAndWindowInProgress.Token);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }
try
{
// Wait and accept the openvpn.exe on our management interface (--management-client parameter).
var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
catch (AggregateException ex) { throw ex.InnerException; }
var mgmtClient = mgmtClientTask.Result;
try
{
// Start the management session.
ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);
// Initialize session and release openvpn.exe to get started.
ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
try
{
// Wait for the session to end gracefully.
ManagementSession.Monitor.Join();
if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
{
// Session reported an error. Retry.
retry = true;
}
}
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
}
finally { mgmtClient.Close(); }
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnecting;
StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
TunnelAddress = null;
IPv6TunnelAddress = null;
ConnectedAt = null;
BytesIn = null;
BytesOut = null;
}));
// Wait for openvpn.exe to finish. Maximum 30s.
try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
catch (ArgumentException) { }
}
}
} while (retry);
}
finally
{
mgmtServer.Stop();
}
}
finally
{
// Delete profile configuration file. If possible.
try { File.Delete(ConfigurationPath); }
catch { }
}
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnected;
StateDescription = "";
Wizard.TaskCount--;
}));
PropertyUpdater.Stop();
}
}
19
Source : CodeWriter.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
public void WriteLine()
{
_writer.WriteLine();
_shouldIndent = true;
}
See More Examples