Here are the examples of the csharp api System.IO.TextWriter.Write(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1807 Examples
19
Source : AnalyzeTask.cs
with GNU General Public License v3.0
from AtomCrafty
with GNU General Public License v3.0
from AtomCrafty
public void Echo(string prefix, string value, string suffix, string type, TextWriter w) {
if(flags.Has('v')) Console.Write(prefix + value + suffix);
w.Write($@"{prefix}<span clreplaced=""code {type}"">{value}</span>{suffix}");
}
19
Source : AvaTaxOfflineHelper.cs
with Apache License 2.0
from avadev
with Apache License 2.0
from avadev
private static void WriteZipRateFile(TaxRateModel zipRate, string zip, string path)
{
TextWriter writer = null;
try {
Directory.GetAccessControl(path);
var content = JsonConvert.SerializeObject(zipRate);
writer = new StreamWriter(Path.Combine(path, zip + ".json"));
writer.Write(content);
}
finally {
if (writer != null) {
writer.Flush();
writer.Close();
}
}
}
19
Source : ITextSource.cs
with MIT License
from AvaloniaUI
with MIT License
from AvaloniaUI
public void WriteTextTo(TextWriter writer)
{
writer.Write(Text);
}
19
Source : HtmlOptions.cs
with MIT License
from AvaloniaUI
with MIT License
from AvaloniaUI
public virtual void WriteStyleAttributeForColor(TextWriter writer, HighlightingColor color)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (color == null)
throw new ArgumentNullException(nameof(color));
writer.Write(" style=\"");
writer.Write(WebUtility.HtmlEncode(color.ToCss()));
writer.Write('"');
}
19
Source : ITextSource.cs
with MIT License
from AvaloniaUI
with MIT License
from AvaloniaUI
public void WriteTextTo(TextWriter writer, int offset, int length)
{
writer.Write(Text.Substring(offset, length));
}
19
Source : IndentedTextWriter.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private void WriteIndents()
{
for (int i = 0; i < Indents; i++)
_writer.Write(Indent);
}
19
Source : RazorTemplateBase.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public virtual void WriteLiteral(string value)
{
if (!string.IsNullOrEmpty(value))
{
Output.Write(value);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from az64
with GNU General Public License v3.0
from az64
static int Main(string[] args)
{
var argsDictionary = DictionaryHelper.FromProgramArguments(args);
var settings = new GameplaySettings();
var outputSettings = new OutputSettings();
settings.Update("fz1mr--16psr-lc-f");
settings.CustomItemListString = "81-80000000----3fff-ffffffff-ffffffff-fe000000-6619ff-7fffffff-f378ffff-ffffffff";
settings.CustomItemList = ConvertIntString(settings.CustomItemListString);
settings.CustomStartingItemListString = "-3fc04000-";
settings.CustomStartingItemList = ConverreplacedemString(ItemUtils.StartingItems().Where(item => !item.Name().Contains("Heart")).ToList(), settings.CustomStartingItemListString);
settings.CustomJunkLocationsString = "----------200000--f000";
settings.CustomJunkLocations = ConverreplacedemString(ItemUtils.AllLocations().ToList(), settings.CustomJunkLocationsString);
outputSettings.GeneratePatch = argsDictionary.ContainsKey("-patch");
outputSettings.GenerateSpoilerLog = argsDictionary.ContainsKey("-spoiler");
outputSettings.GenerateHTMLLog = argsDictionary.ContainsKey("-html");
outputSettings.GenerateROM = argsDictionary.ContainsKey("-rom");
int seed;
if (argsDictionary.ContainsKey("-seed"))
{
seed = int.Parse(argsDictionary["-seed"][0]);
}
else
{
seed = new Random().Next();
}
var outputArg = argsDictionary.GetValueOrDefault("-output");
if (outputArg != null)
{
if (outputArg.Count > 1)
{
throw new ArgumentException("Invalid argument.", "-output");
}
outputSettings.OutputROMFilename = outputArg.SingleOrDefault();
}
outputSettings.OutputROMFilename ??= Path.Combine("output", FileUtils.MakeFilenameValid(DateTime.UtcNow.ToString("o")));
var inputArg = argsDictionary.GetValueOrDefault("-input");
if (inputArg != null)
{
if (inputArg.Count > 1)
{
throw new ArgumentException("Invalid argument.", "-input");
}
outputSettings.InputROMFilename = inputArg.SingleOrDefault();
}
outputSettings.InputROMFilename ??= "input.z64";
var validationResult = settings.Validate();
if (validationResult != null)
{
Console.WriteLine(validationResult);
return -1;
}
try
{
string result;
using (var progressBar = new ProgressBar())
{
//var progressReporter = new TextWriterProgressReporter(Console.Out);
var progressReporter = new ProgressBarProgressReporter(progressBar);
result = ConfigurationProcessor.Process(new Configuration
{
GameplaySettings = settings,
OutputSettings = outputSettings,
}, seed, progressReporter);
}
if (result != null)
{
Console.Error.WriteLine(result);
}
else
{
Console.WriteLine("Generation complete!");
}
return result == null ? 0 : -1;
}
catch (Exception e)
{
Console.Error.Write(e.Message);
Console.Error.Write(e.StackTrace);
return -1;
}
}
19
Source : Schema.FieldDef.cs
with MIT License
from azist
with MIT License
from azist
void IJsonWritable.WriteAsJson(System.IO.TextWriter wri, int nestingLevel, JsonWritingOptions options)
{
var attr = this[null];
if (attr != null && attr.NonUI)
{
wri.Write("{}");
return;//nothing to write for NONUI
}
bool typeIsNullable;
string tp = JSONMappings.MapCLRTypeToJSON(m_Type, out typeIsNullable);
var map = new Dictionary<string, object>
{
{"Name", m_Name},
{"Order", m_Order},
{"Type", tp},
{"Nullable", typeIsNullable},
{"GetOnly", m_GetOnly}
};
//20190322 DKh inner schema
if (typeof(Doc).IsreplacedignableFrom(NonNullableType))
{
map["IsDataDoc"] = true;
map["IsAmorphous"] = typeof(IAmorphousData).IsreplacedignableFrom(NonNullableType);
map["IsForm"] = typeof(Form).IsreplacedignableFrom(NonNullableType);
if (typeof(TypedDoc).IsreplacedignableFrom(NonNullableType))
{
var innerSchema = Schema.GetForTypedDoc(NonNullableType);
if (innerSchema.Any(fd => typeof(TypedDoc).IsreplacedignableFrom(fd.Type)))
map["DataDocSchema"] = "@complex";
else
map["DataDocSchema"] = innerSchema;
}
}
if (attr != null)
{
map.Add("IsKey", attr.Key);
map.Add("IsRequired", attr.Required);
map.Add("Visible", attr.Visible);
if (attr.Default != null) map.Add("Default", attr.Default);
if (attr.CharCase != CharCase.AsIs) map.Add("CharCase", attr.CharCase);
if (attr.Kind != DataKind.Text) map.Add("Kind", attr.Kind);
if (attr.MinLength != 0) map.Add("MinLen", attr.MinLength);
if (attr.MaxLength != 0) map.Add("MaxLen", attr.MaxLength);
if (attr.Min != null) map.Add("Min", attr.Min);
if (attr.Max != null) map.Add("Max", attr.Max);
if (attr.ValueList != null) map.Add("ValueList", attr.ValueList);
if (attr.Description != null) map.Add("Description", attr.Description);
//metadata content is in the internal format and not dumped
}
JsonWriter.WriteMap(wri, map, nestingLevel, options);
}
19
Source : ConsoleUtils.cs
with MIT License
from azist
with MIT License
from azist
public static void WriteMarkupContentAsHTML(System.IO.TextWriter output,
string content,
Encoding encoding = null, // UTF8 if null
char open = '<', char close = '>',
string mkpPRE = "pre",
string mkpCssForeColorPrefix = "conForeColor_",
string mkpCssBackColorPrefix = "conBackColor_",
ConsoleColor defaultForeColor = ConsoleColor.White,
ConsoleColor defaultBackColor = ConsoleColor.Black)
{
// [mkpPRE]<span clreplaced='conColor_red'>This string will be red</span>[/mkpPRE]
if (mkpPRE.IsNotNullOrWhiteSpace())
{
output.Write('<');
output.Write(mkpPRE);
output.Write('>');
}
TokenParser parser = new TokenParser(content, open, close);
Stack<ConsoleColor> stack = new Stack<ConsoleColor>();
bool collapsespaces = false;
ConsoleColor foreColor = defaultForeColor, backColor = defaultBackColor;
bool isSpanOpen = false;
foreach (TokenParser.Token tok in parser)
{
if (tok.IsSimpleText)
{
if (collapsespaces)
output.Write(WebUtility.HtmlEncode(tok.Content.Trim()));
else
output.Write(WebUtility.HtmlEncode(tok.Content));
continue;
}
string name = tok.Name.ToUpperInvariant().Trim();
if (name == "LITERAL")
{
collapsespaces = false;
continue;
}
if (name == "HTML")
{
collapsespaces = true;
continue;
}
if (name == "BR")
{
output.WriteLine();
continue;
}
if ((name == "SP") || (name == "SPACE"))
{
string txt = " ";
int cnt = 1;
try { cnt = int.Parse(tok["COUNT"]); }
catch { }
while (txt.Length < cnt) txt += " ";
output.Write(WebUtility.HtmlEncode(txt));
continue;
}
if (name == "PUSH")
{
stack.Push(foreColor);
stack.Push(backColor);
continue;
}
if (name == "POP")
{
if (stack.Count > 1)
{
backColor = stack.Pop();
foreColor = stack.Pop();
if (isSpanOpen)
{
isSpanOpen = false;
output.Write("</span>");
if (stack.Count > 1)
{
isSpanOpen = true;
output.Write("<span clreplaced='{0}{1} {2}{3}'>".Args(mkpCssForeColorPrefix, foreColor, mkpCssBackColorPrefix, backColor));
}
}
}
continue;
}
if (name == "RESET")
{
foreColor = defaultForeColor;
if (isSpanOpen)
{
isSpanOpen = false;
output.Write("</span>");
}
continue;
}
if ((name == "F") || (name == "FORE") || (name == "FOREGROUND"))
{
try
{
ConsoleColor clr = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), tok["COLOR"], true);
foreColor = clr;
if (isSpanOpen) output.Write("</span>");
output.Write("<span clreplaced='{0}{1} {2}{3}'>".Args(mkpCssForeColorPrefix, foreColor, mkpCssBackColorPrefix, backColor));
isSpanOpen = true;
}
catch { }
continue;
}
if ((name == "B") || (name == "BACK") || (name == "BACKGROUND"))
{
try
{
ConsoleColor clr = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), tok["COLOR"], true);
backColor = clr;
if (isSpanOpen) output.Write("</span>");
output.Write("<span clreplaced='{0}{1} {2}{3}'>".Args(mkpCssForeColorPrefix, foreColor, mkpCssBackColorPrefix, backColor));
isSpanOpen = true;
}
catch { }
continue;
}
if ((name == "J") || (name == "JUST") || (name == "JUSTIFY"))
{
try
{
int width = int.Parse(tok["WIDTH"]);
direction dir = (direction)Enum.Parse(typeof(direction), tok["DIR"], true);
string txt = tok["TEXT"];
switch (dir)
{
case direction.Right:
{
while (txt.Length < width) txt = " " + txt;
break;
}
case direction.Center:
{
while (txt.Length < width) txt = " " + txt + " ";
if (txt.Length > width) txt = txt.Substring(0, txt.Length - 1);
break;
}
default:
{
while (txt.Length < width) txt = txt + " ";
break;
}
}
output.Write(WebUtility.HtmlEncode(txt));
}
catch { }
continue;
}
}
if (mkpPRE.IsNotNullOrWhiteSpace())
{
output.Write('<');
output.Write('/');
output.Write(mkpPRE);
output.Write('>');
}
}
19
Source : TeleConsoleProto.cs
with MIT License
from azist
with MIT License
from azist
void IJsonWritable.WriteAsJson(TextWriter wri, int nestingLevel, JsonWritingOptions options)
{
wri.Write("{\"n\":"); JsonWriter.EncodeString(wri, Name, options); wri.Write(",");
wri.Write("\"c\":\""); wri.Write(Cmd.ToString()); wri.Write("\"");
if (Text!=null)
{
wri.Write(",\"t\":"); JsonWriter.EncodeString(wri, Text, options);
}
if (Background.HasValue)
{
wri.Write(",\"bg\":");
wri.Write(Background.Value.ToString());
}
if (Foreground.HasValue)
{
wri.Write(",\"fg\":");
wri.Write(Foreground.Value.ToString());
}
wri.Write("}");
}
19
Source : CSVWriter.cs
with MIT License
from azist
with MIT License
from azist
private static void writeValue(object value, TextWriter wri, CSVWritingOptions options)
{
if (value == null)
{
wri.Write(options.NullValue);
return;
}
if (value is string)
{
wri.Write(escape((string)value, options.FieldDelimiter));
return;
}
if (value is bool)
{
wri.Write(((bool)value) ? "true" : "false");
return;
}
if (value is int || value is long)
{
wri.Write(((IConvertible)value).ToString(System.Globalization.CultureInfo.InvariantCulture));
return;
}
if (value is double || value is float || value is decimal)
{
wri.Write(escape(((IConvertible)value).ToString(System.Globalization.CultureInfo.InvariantCulture),
options.FieldDelimiter));
return;
}
if (value is DateTime)
{
wri.Write(((DateTime)value).ToString(System.Globalization.CultureInfo.InvariantCulture));
return;
}
if (value is TimeSpan)
{
var ts = (TimeSpan)value;
wri.Write(ts.Ticks);
return;
}
wri.Write(escape(value.ToString(), options.FieldDelimiter));
}
19
Source : JsonWriter.cs
with MIT License
from azist
with MIT License
from azist
public static void EncodeString(TextWriter wri, string data, JsonWritingOptions opt = null)
{
if (data.IsNullOrEmpty())
{
wri.Write("\"\"");
return;
}
if (opt==null)
opt = JsonWritingOptions.Compact;
wri.Write('"');
for (int i = 0; i < data.Length; i++)
{
char c = data[i];
if (c > 0x7f && opt.ASCIITarget)
{
wri.Write("\\u");
wri.Write(((int)c).ToString("x4"));
continue;
}
switch (c)
{
case '\\': { wri.Write(@"\\"); break; }
case '/': { wri.Write(@"\/"); break; }
case (char)CharCodes.Char0: { wri.Write(@"\u0000"); break; }
case (char)CharCodes.AlertBell: { wri.Write(@"\u"); ((int)c).ToString("x4"); break; }
case (char)CharCodes.Backspace: { wri.Write(@"\b"); break; }
case (char)CharCodes.Formfeed: { wri.Write(@"\f"); break; }
case (char)CharCodes.LF: { wri.Write(@"\n"); break; }
case (char)CharCodes.CR: { wri.Write(@"\r"); break; }
case (char)CharCodes.Tab: { wri.Write(@"\t"); break; }
case '"': { wri.Write(@"\"""); break; }
default:
{
if (c < 0x20)
{
wri.Write("\\u");
wri.Write(((int)c).ToString("x4"));
break;
}
wri.Write(c);
break;
}
}
}//for
wri.Write('"');
}
19
Source : JsonWriter.cs
with MIT License
from azist
with MIT License
from azist
public static void EncodeDateTime(TextWriter wri, DateTime data, JsonWritingOptions opt = null, TimeSpan? utcOffset = null)
{
if (opt==null) opt = JsonWritingOptions.Compact;
if (!opt.ISODates)
{
wri.Write("new Date({0})".Args( data.ToMillisecondsSinceUnixEpochStart() ));
return;
}
wri.Write('"');
var year = data.Year;
if (year>999) wri.Write(year);
else if (year>99) { wri.Write('0'); wri.Write(year); }
else if (year>9) { wri.Write("00"); wri.Write(year); }
else if (year>0) { wri.Write("000"); wri.Write(year); }
wri.Write('-');
var month = data.Month;
if (month>9) wri.Write(month);
else { wri.Write('0'); wri.Write(month); }
wri.Write('-');
var day = data.Day;
if (day>9) wri.Write(day);
else { wri.Write('0'); wri.Write(day); }
wri.Write('T');
var hour = data.Hour;
if (hour>9) wri.Write(hour);
else { wri.Write('0'); wri.Write(hour); }
wri.Write(':');
var minute = data.Minute;
if (minute>9) wri.Write(minute);
else { wri.Write('0'); wri.Write(minute); }
wri.Write(':');
var second = data.Second;
if (second>9) wri.Write(second);
else { wri.Write('0'); wri.Write(second); }
var ms = data.Millisecond;
if (ms>0)
{
wri.Write('.');
if (ms>99) wri.Write(ms);
else if (ms>9) { wri.Write('0'); wri.Write(ms); }
else { wri.Write("00"); wri.Write(ms); }
}
if (data.Kind==DateTimeKind.Utc)
wri.Write('Z');
else
{
var offset = utcOffset==null ? TimeZoneInfo.Local.GetUtcOffset(data) : utcOffset.Value;
wri.Write( offset.Ticks<0 ? '-' : '+' );
hour = Math.Abs(offset.Hours);
if (hour>9) wri.Write(hour);
else { wri.Write('0'); wri.Write(hour); }
wri.Write(':');
minute = Math.Abs(offset.Minutes);
if (minute>9) wri.Write(minute);
else { wri.Write('0'); wri.Write(minute); }
}
wri.Write('"');
}
19
Source : JsonWriter.cs
with MIT License
from azist
with MIT License
from azist
private static void writeAny(TextWriter wri, object data, int level, JsonWritingOptions opt)
{
if (data==null)
{
wri.Write("null");//do NOT LOCALIZE!
return;
}
if (level>opt.MaxNestingLevel)
throw new JSONSerializationException(StringConsts.JSON_SERIALIZATION_MAX_NESTING_EXCEEDED_ERROR.Args(opt.MaxNestingLevel));
if (data is string)
{
EncodeString(wri, (string)data, opt);
return;
}
//20210717 - #514
if (data is byte[] buff && buff.Length > 8)
{
EncodeString(wri, buff.ToWebSafeBase64(), opt);
return;
}
if (data is bool)//the check is here for speed
{
wri.Write( ((bool)data) ? "true" : "false");//do NOT LOCALIZE!
return;
}
if (data is int || data is long)//the check is here for speed
{
wri.Write( ((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture) );
return;
}
if (data is double || data is float || data is decimal)//the check is here for speed
{
wri.Write( ((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture) );
return;
}
if (data is DateTime)
{
EncodeDateTime(wri, (DateTime)data, opt);
return;
}
if (data is TimeSpan)
{
var ts = (TimeSpan)data;
wri.Write(ts.Ticks);
return;
}
if (data is Guid)
{
var guid = (Guid)data;
wri.Write('"');
wri.Write(guid.ToString("D"));
wri.Write('"');
return;
}
if (data is IJsonWritable)//these types know how to directly write themselves
{
((IJsonWritable)data).WriteAsJson(wri, level, opt);
return;
}
if (data is JsonDynamicObject)//unwrap dynamic
{
writeAny(wri, ((JsonDynamicObject)data).Data, level, opt);
return;
}
if (data is IDictionary)//must be BEFORE IEnumerable
{
writeMap(wri, (IDictionary)data, level, opt);
return;
}
if (data is IEnumerable)
{
writeArray(wri, (IEnumerable)data, level, opt);
return;
}
var tdata = data.GetType();
if (tdata.IsPrimitive || tdata.IsEnum)
{
string val;
if (data is IConvertible)
val = ((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture);
else
val = data.ToString();
EncodeString(wri, val, opt);
return;
}
var fields = SerializationUtils.GetSerializableFields(tdata);
var dict = fields.Select(
f =>
{
var name = f.Name;
var iop = name.IndexOf('<');
if (iop>=0)//handle anonymous type field name
{
var icl = name.IndexOf('>');
if (icl>iop+1)
name = name.Substring(iop+1, icl-iop-1);
}
return new DictionaryEntry(name, f.GetValue(data));
});//select
writeMap(wri, dict, level, opt);
}
19
Source : JsonWriter.cs
with MIT License
from azist
with MIT License
from azist
private static void writeMap(TextWriter wri, IEnumerable<DictionaryEntry> data, int level, JsonWritingOptions opt)
{
if (level>0) level++;
if (opt.ObjectLineBreak)
{
wri.WriteLine();
indent(wri, level, opt);
}
wri.Write('{');
//20200615 DKh #304
if (opt.MapSortKeys)
{
data = data.OrderBy( kvp => (kvp.Key?.ToString()).Default(string.Empty), StringComparer.Ordinal);
}
var first = true;
foreach(DictionaryEntry entry in data)
{
if (opt.MapSkipNulls)
{
if (entry.Value == null) continue;
// NLSMap is a special type which is treated as a ref type for perf optimization
if (entry.Value is NLSMap && ((NLSMap)entry.Value).Count == 0) continue;
}
if (!first)
wri.Write(opt.SpaceSymbols ? ", " : ",");
if (opt.MemberLineBreak)
{
wri.WriteLine();
indent(wri, level+1, opt);
}
EncodeString(wri, entry.Key.ToString(), opt);
wri.Write(opt.SpaceSymbols ? ": " : ":");
writeAny(wri, entry.Value, level+1, opt);
first = false;
}
if (!first && opt.MemberLineBreak)
{
wri.WriteLine();
indent(wri, level, opt);
}
wri.Write('}');
}
19
Source : JsonWriter.cs
with MIT License
from azist
with MIT License
from azist
private static void writeArray(TextWriter wri, IEnumerable data, int level, JsonWritingOptions opt)
{
wri.Write('[');
var first = true;
foreach(var elm in data)
{
if (!first)
wri.Write(opt.SpaceSymbols ? ", " : ",");
writeAny(wri, elm, level+1, opt);
first = false;
}
wri.Write(']');
}
19
Source : NLSMap.cs
with MIT License
from azist
with MIT License
from azist
void IJsonWritable.WriteAsJson(TextWriter wri, int nestingLevel, JsonWritingOptions options)
{
if (m_Data==null)
{
wri.Write("{}");
return;
}
if (options==null ||
options.Purpose==JsonSerializationPurpose.Marshalling ||
options.NLSMapLanguageISO.IsZero)
{
JsonWriter.WriteMap(wri, nestingLevel, options,
m_Data.Select
(
e => new System.Collections.DictionaryEntry(e.ISO.Value, e)
).ToArray() );
return;
}
var pair = this[options.NLSMapLanguageISO];
if (!pair.Isreplacedigned && options.NLSMapLanguageISODefault != options.NLSMapLanguageISO)
pair = this[options.NLSMapLanguageISODefault];
if (pair.Isreplacedigned)
JsonWriter.WriteMap(wri, nestingLevel, options, new System.Collections.DictionaryEntry("n", pair.Name),
new System.Collections.DictionaryEntry("d", pair.Description));
else
JsonWriter.WriteMap(wri, nestingLevel, options, new System.Collections.DictionaryEntry("n", null),
new System.Collections.DictionaryEntry("d", null));
}
19
Source : SyntaxNode.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
private static void TreePrint(TextWriter writer, SyntaxNode node, string indent = "", bool isLast = true)
{
var isToConsole = writer == Console.Out;
var marker = isLast ? "└──" : "├──";
if (isToConsole)
Console.ForegroundColor = ConsoleColor.DarkGray;
writer.Write(indent);
writer.Write(marker);
if (isToConsole)
Console.ForegroundColor = node is SyntaxToken ? ConsoleColor.Blue : ConsoleColor.Cyan;
writer.Write(node.Kind);
if (node is SyntaxToken t && t.Value != null)
{
writer.Write(" ");
writer.Write(t.Value);
}
if (isToConsole)
Console.ResetColor();
writer.WriteLine();
indent += isLast ? " " : "│ ";
var lastChild = node.GetChildren().LastOrDefault();
foreach (var child in node.GetChildren())
TreePrint(writer, child, indent, child == lastChild);
}
19
Source : WriterExtensions.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
public static void WriteKeyword(this TextWriter writer, string text)
{
writer.SetForeground(ConsoleColor.Blue);
writer.Write(text);
writer.ResetColor();
}
19
Source : WriterExtensions.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
public static void WriteIdentifier(this TextWriter writer, string text)
{
writer.SetForeground(ConsoleColor.DarkYellow);
writer.Write(text);
writer.ResetColor();
}
19
Source : WriterExtensions.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
public static void WriteNumber(this TextWriter writer, string text)
{
writer.SetForeground(ConsoleColor.Cyan);
writer.Write(text);
writer.ResetColor();
}
19
Source : WriterExtensions.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
public static void WriteString(this TextWriter writer, string text)
{
writer.SetForeground(ConsoleColor.Magenta);
writer.Write(text);
writer.ResetColor();
}
19
Source : WriterExtensions.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
public static void WritePunctuation(this TextWriter writer, string text)
{
writer.SetForeground(ConsoleColor.DarkGray);
writer.Write(text);
writer.ResetColor();
}
19
Source : ProgressWriter.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
private void IdleWriter(object state)
{
lock (_thisLock)
{
if (!disposed)
{
_idling = true;
// Write progress
_output.Write(".");
// Set next timer to fire when we write the next idle progress
_timer.Change(_idlingDelay, Timeout.InfiniteTimeSpan);
}
}
}
19
Source : StoryTellerDumper.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
protected virtual void AppendLine(PacketBase packet, UniversalGuid? guid, string text, bool skipPacketNumber = false)
{
if (pendingAppend != null)
{
var pending = pendingAppend;
pendingAppend = null;
AppendLine(packet, guid, pending);
}
var state = GetWriterState(guid);
if (!state.lastTime.HasValue)
state.lastTime = packet.Time.ToDateTime();
else
{
TimeSpan diff = packet.Time.ToDateTime().Subtract(state.lastTime.Value);
if (diff.TotalMilliseconds > 130)
{
state.writer.WriteLine();
if (perGuidWriter != null)
state.writer.Write(" ");
state.writer.WriteLine("After " + diff.TotalMilliseconds + " ms");
state.lastTime = packet.Time.ToDateTime();
}
}
if (!skipPacketNumber)
state.writer.WriteLine(" " + text + " ["+packet.Number+"]");
else
state.writer.WriteLine(" " + text);
}
19
Source : Options.cs
with The Unlicense
from BattletechModders
with The Unlicense
from BattletechModders
void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
{
bool indent = false;
foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
19
Source : Options.cs
with The Unlicense
from BattletechModders
with The Unlicense
from BattletechModders
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (p.Hidden)
continue;
Category c = p as Category;
if (c != null) {
WriteDescription (o, p.Description, "", 80, 80);
continue;
}
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
foreach (ArgumentSource s in sources) {
string[] names = s.GetNames ();
if (names == null || names.Length == 0)
continue;
int written = 0;
Write (o, ref written, " ");
Write (o, ref written, names [0]);
for (int i = 1; i < names.Length; ++i) {
Write (o, ref written, ", ");
Write (o, ref written, names [i]);
}
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
}
19
Source : WebUtility.cs
with MIT License
from bbepis
with MIT License
from bbepis
public static unsafe void HtmlEncode( string value, TextWriter output )
{
if( value == null )
{
return;
}
if( output == null )
{
throw new ArgumentNullException( "output" );
}
int index = IndexOfHtmlEncodingChars( value, 0 );
if( index == -1 )
{
output.Write( value );
return;
}
int cch = value.Length - index;
fixed( char* str = value )
{
char* pch = str;
while( index-- > 0 )
{
output.Write( *pch++ );
}
for( ; cch > 0; cch--, pch++ )
{
char ch = *pch;
if( ch <= '>' )
{
switch( ch )
{
case '<':
output.Write( "<" );
break;
case '>':
output.Write( ">" );
break;
case '"':
output.Write( """ );
break;
case '\'':
output.Write( "'" );
break;
case '&':
output.Write( "&" );
break;
default:
output.Write( ch );
break;
}
}
else
{
// write out the character directly
output.Write( ch );
}
}
}
}
19
Source : WebUtility.cs
with MIT License
from bbepis
with MIT License
from bbepis
public static void HtmlDecode( string value, TextWriter output )
{
if( value == null )
{
return;
}
if( output == null )
{
throw new ArgumentNullException( "output" );
}
if( !StringRequiresHtmlDecoding( value ) )
{
output.Write( value ); // good as is
return;
}
int l = value.Length;
for( int i = 0; i < l; i++ )
{
char ch = value[ i ];
if( ch == '&' )
{
// We found a '&'. Now look for the next ';' or '&'. The idea is that
// if we find another '&' before finding a ';', then this is not an enreplacedy,
// and the next '&' might start a real enreplacedy (VSWhidbey 275184)
int index = value.IndexOfAny( _htmlEnreplacedyEndingChars, i + 1 );
if( index > 0 && value[ index ] == ';' )
{
string enreplacedy = value.Substring( i + 1, index - i - 1 );
if( enreplacedy.Length > 1 && enreplacedy[ 0 ] == '#' )
{
// The # syntax can be in decimal or hex, e.g.
// å --> decimal
// å --> same char in hex
// See http://www.w3.org/TR/REC-html40/charset.html#enreplacedies
bool parsedSuccessfully;
uint parsedValue;
if( enreplacedy[ 1 ] == 'x' || enreplacedy[ 1 ] == 'X' )
{
parsedSuccessfully = UInt32.TryParse( enreplacedy.Substring( 2 ), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out parsedValue );
}
else
{
parsedSuccessfully = UInt32.TryParse( enreplacedy.Substring( 1 ), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out parsedValue );
}
if( parsedSuccessfully )
{
parsedSuccessfully = ( 0 < parsedValue && parsedValue <= UNICODE_PLANE00_END );
}
if( parsedSuccessfully )
{
if( parsedValue <= UNICODE_PLANE00_END )
{
// single character
output.Write( (char)parsedValue );
}
else
{
// multi-character
char leadingSurrogate, trailingSurrogate;
ConvertSmpToUtf16( parsedValue, out leadingSurrogate, out trailingSurrogate );
output.Write( leadingSurrogate );
output.Write( trailingSurrogate );
}
i = index; // already looked at everything until semicolon
continue;
}
}
else
{
i = index; // already looked at everything until semicolon
char enreplacedyChar = HtmlEnreplacedies.Lookup( enreplacedy );
if( enreplacedyChar != (char)0 )
{
ch = enreplacedyChar;
}
else
{
output.Write( '&' );
output.Write( enreplacedy );
output.Write( ';' );
continue;
}
}
}
}
output.Write( ch );
}
}
19
Source : IndentedTextWriter.cs
with MIT License
from bbepis
with MIT License
from bbepis
public void WriteLine( string line )
{
_writer.Write( new string( _indent, Indent ) );
_writer.WriteLine( line );
}
19
Source : TranslationError.cs
with MIT License
from bbepis
with MIT License
from bbepis
internal override void Encode( TextWriter writer )
{
writer.WriteLine( Id.ToString() );
writer.WriteLine( (int)FailureCode );
writer.Write( Reason );
}
19
Source : ConfigurationMessage.cs
with MIT License
from bbepis
with MIT License
from bbepis
internal override void Encode( TextWriter writer )
{
writer.WriteLine( Id.ToString() );
writer.Write( Config );
}
19
Source : LinuxConsoleDriver.cs
with GNU Lesser General Public License v2.1
from BepInEx
with GNU Lesser General Public License v2.1
from BepInEx
public void SetConsolereplacedle(string replacedle)
{
if (StdoutRedirected)
return;
if (UseMonoTtyDriver && SafeConsole.replacedleExists)
SafeConsole.replacedle = replacedle;
else
ConsoleOut.Write($"\u001B]2;{replacedle.Replace("\\", "\\\\")}\u0007");
}
19
Source : ConsoleSetOutFix.cs
with GNU Lesser General Public License v2.1
from BepInEx
with GNU Lesser General Public License v2.1
from BepInEx
public override void Write(string value)
{
ConsoleSetOutFix.ConsoleLogSource.LogInfo(value);
Parent.Write(value);
}
19
Source : TestTools.cs
with MIT License
from BepInEx
with MIT License
from BepInEx
public static void Log(object obj, int indentLevel = 1, int? indentLevelAfterNewLine = null, bool writeLine = true)
{
var indentBeforeNewLine = new string('\t', indentLevel);
var indentAfterNewLine = new string('\t', indentLevelAfterNewLine ?? indentLevel + 1);
var text = $"{indentBeforeNewLine}{obj?.ToString().Replace("\n", "\n" + indentAfterNewLine) ?? "null"}";
if (writeLine)
LogWriter.WriteLine(text);
else
LogWriter.Write(text);
}
19
Source : TestConsole.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
public virtual ConsoleKeyInfo? ReadKey(bool intercept = false)
{
ConsoleKeyInfo consoleKeyInfo;
do
{
consoleKeyInfo = _onReadKey?.Invoke(this)
?? new ConsoleKeyInfo('\u0000', ConsoleKey.Enter, false, false, false);
// mimic System.Console which does not interrupt during ReadKey
// and does not return Ctrl+C unless TreatControlCAsInput == true.
} while (!TreatControlCAsInput && consoleKeyInfo.IsCtrlC());
if (!intercept)
{
if (consoleKeyInfo.Key == ConsoleKey.Enter)
{
Out.WriteLine("");
}
else
{
Out.Write(consoleKeyInfo.KeyChar.ToString());
}
}
return consoleKeyInfo;
}
19
Source : RazorScriptHost.cs
with MIT License
from bjorkstromm
with MIT License
from bjorkstromm
public virtual void BeginWriteAttribute(string name, string prefix, int prefixOffset, string suffix, int suffixOffset, int attributeValuesCount)
{
Output.Write(prefix);
AttributeEnding = suffix;
}
19
Source : RazorScriptHost.cs
with MIT License
from bjorkstromm
with MIT License
from bjorkstromm
public virtual void EndWriteAttribute()
{
var attributes = string.Join(" ", AttributeValues);
Output.Write(attributes);
AttributeValues = null;
Output.Write(AttributeEnding);
AttributeEnding = null;
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private void WriteMessage(TextWriter writer, IMessage message)
{
if (message == null)
{
WriteNull(writer);
return;
}
if (DiagnosticOnly)
{
ICustomDiagnosticMessage customDiagnosticMessage = message as ICustomDiagnosticMessage;
if (customDiagnosticMessage != null)
{
writer.Write(customDiagnosticMessage.ToDiagnosticString());
return;
}
}
writer.Write("{ ");
bool writtenFields = WriteMessageFields(writer, message, false);
writer.Write(writtenFields ? " }" : "}");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private bool WriteMessageFields(TextWriter writer, IMessage message, bool replacedumeFirstFieldWritten)
{
var fields = message.Descriptor.Fields;
bool first = !replacedumeFirstFieldWritten;
// First non-oneof fields
foreach (var field in fields.InFieldNumberOrder())
{
var accessor = field.Accessor;
if (field.ContainingOneof != null && field.ContainingOneof.Accessor.GetCaseFieldDescriptor(message) != field)
{
continue;
}
// Omit default values unless we're asked to format them, or they're oneofs (where the default
// value is still formatted regardless, because that's how we preserve the oneof case).
object value = accessor.GetValue(message);
if (field.ContainingOneof == null && !settings.FormatDefaultValues && IsDefaultValue(accessor, value))
{
continue;
}
// Okay, all tests complete: let's write the field value...
if (!first)
{
writer.Write(PropertySeparator);
}
WriteString(writer, accessor.Descriptor.JsonName);
writer.Write(NameValueSeparator);
WriteValue(writer, value);
first = false;
}
return !first;
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private static void WriteNull(TextWriter writer)
{
writer.Write("null");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
public void WriteValue(TextWriter writer, object value)
{
if (value == null)
{
WriteNull(writer);
}
else if (value is bool)
{
writer.Write((bool)value ? "true" : "false");
}
else if (value is ByteString)
{
// Nothing in Base64 needs escaping
writer.Write('"');
writer.Write(((ByteString)value).ToBase64());
writer.Write('"');
}
else if (value is string)
{
WriteString(writer, (string)value);
}
else if (value is IDictionary)
{
WriteDictionary(writer, (IDictionary)value);
}
else if (value is IList)
{
WriteList(writer, (IList)value);
}
else if (value is int || value is uint)
{
IFormattable formattable = (IFormattable) value;
writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture));
}
else if (value is long || value is ulong)
{
writer.Write('"');
IFormattable formattable = (IFormattable) value;
writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture));
writer.Write('"');
}
else if (value is System.Enum)
{
if (settings.FormatEnumsAsIntegers)
{
WriteValue(writer, (int)value);
}
else
{
string name = OriginalEnumValueHelper.GetOriginalName(value);
if (name != null)
{
WriteString(writer, name);
}
else
{
WriteValue(writer, (int)value);
}
}
}
else if (value is float || value is double)
{
string text = ((IFormattable) value).ToString("r", CultureInfo.InvariantCulture);
if (text == "NaN" || text == "Infinity" || text == "-Infinity")
{
writer.Write('"');
writer.Write(text);
writer.Write('"');
}
else
{
writer.Write(text);
}
}
else if (value is IMessage)
{
Format((IMessage)value, writer);
}
else
{
throw new ArgumentException("Unable to format value of type " + value.GetType());
}
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private void WriteAny(TextWriter writer, IMessage value)
{
if (DiagnosticOnly)
{
WriteDiagnosticOnlyAny(writer, value);
return;
}
string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value);
ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value);
string typeName = Any.GetTypeName(typeUrl);
MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName);
if (descriptor == null)
{
throw new InvalidOperationException("Type registry has no descriptor for type name '" + typeName + "'");
}
IMessage message = descriptor.Parser.ParseFrom(data);
writer.Write("{ ");
WriteString(writer, AnyTypeUrlField);
writer.Write(NameValueSeparator);
WriteString(writer, typeUrl);
if (descriptor.IsWellKnownType)
{
writer.Write(PropertySeparator);
WriteString(writer, AnyWellKnownTypeValueField);
writer.Write(NameValueSeparator);
WriteWellKnownTypeValue(writer, descriptor, message);
}
else
{
WriteMessageFields(writer, message, true);
}
writer.Write(" }");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private void WriteDiagnosticOnlyAny(TextWriter writer, IMessage value)
{
string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value);
ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value);
writer.Write("{ ");
WriteString(writer, AnyTypeUrlField);
writer.Write(NameValueSeparator);
WriteString(writer, typeUrl);
writer.Write(PropertySeparator);
WriteString(writer, AnyDiagnosticValueField);
writer.Write(NameValueSeparator);
writer.Write('"');
writer.Write(data.ToBase64());
writer.Write('"');
writer.Write(" }");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private void WriteStruct(TextWriter writer, IMessage message)
{
writer.Write("{ ");
IDictionary fields = (IDictionary) message.Descriptor.Fields[Struct.FieldsFieldNumber].Accessor.GetValue(message);
bool first = true;
foreach (DictionaryEntry entry in fields)
{
string key = (string) entry.Key;
IMessage value = (IMessage) entry.Value;
if (string.IsNullOrEmpty(key) || value == null)
{
throw new InvalidOperationException("Struct fields cannot have an empty key or a null value.");
}
if (!first)
{
writer.Write(PropertySeparator);
}
WriteString(writer, key);
writer.Write(NameValueSeparator);
WriteStructFieldValue(writer, value);
first = false;
}
writer.Write(first ? "}" : " }");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
internal void WriteList(TextWriter writer, IList list)
{
writer.Write("[ ");
bool first = true;
foreach (var value in list)
{
if (!first)
{
writer.Write(PropertySeparator);
}
WriteValue(writer, value);
first = false;
}
writer.Write(first ? "]" : " ]");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
internal void WriteDictionary(TextWriter writer, IDictionary dictionary)
{
writer.Write("{ ");
bool first = true;
// This will box each pair. Could use IDictionaryEnumerator, but that's ugly in terms of disposal.
foreach (DictionaryEntry pair in dictionary)
{
if (!first)
{
writer.Write(PropertySeparator);
}
string keyText;
if (pair.Key is string)
{
keyText = (string) pair.Key;
}
else if (pair.Key is bool)
{
keyText = (bool) pair.Key ? "true" : "false";
}
else if (pair.Key is int || pair.Key is uint | pair.Key is long || pair.Key is ulong)
{
keyText = ((IFormattable) pair.Key).ToString("d", CultureInfo.InvariantCulture);
}
else
{
if (pair.Key == null)
{
throw new ArgumentException("Dictionary has entry with null key");
}
throw new ArgumentException("Unhandled dictionary key type: " + pair.Key.GetType());
}
WriteString(writer, keyText);
writer.Write(NameValueSeparator);
WriteValue(writer, pair.Value);
first = false;
}
writer.Write(first ? "}" : " }");
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
private static void HexEncodeUtf16CodeUnit(TextWriter writer, char c)
{
writer.Write("\\u");
writer.Write(Hex[(c >> 12) & 0xf]);
writer.Write(Hex[(c >> 8) & 0xf]);
writer.Write(Hex[(c >> 4) & 0xf]);
writer.Write(Hex[(c >> 0) & 0xf]);
}
19
Source : JsonFormatter.cs
with MIT License
from bluexo
with MIT License
from bluexo
internal static void WriteString(TextWriter writer, string text)
{
writer.Write('"');
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c < 0xa0)
{
writer.Write(CommonRepresentations[c]);
continue;
}
if (char.IsHighSurrogate(c))
{
// Encountered first part of a surrogate pair.
// Check that we have the whole pair, and encode both parts as hex.
i++;
if (i == text.Length || !char.IsLowSurrogate(text[i]))
{
throw new ArgumentException("String contains low surrogate not followed by high surrogate");
}
HexEncodeUtf16CodeUnit(writer, c);
HexEncodeUtf16CodeUnit(writer, text[i]);
continue;
}
else if (char.IsLowSurrogate(c))
{
throw new ArgumentException("String contains high surrogate not preceded by low surrogate");
}
switch ((uint) c)
{
// These are not required by json spec
// but used to prevent security bugs in javascript.
case 0xfeff: // Zero width no-break space
case 0xfff9: // Interlinear annotation anchor
case 0xfffa: // Interlinear annotation separator
case 0xfffb: // Interlinear annotation terminator
case 0x00ad: // Soft-hyphen
case 0x06dd: // Arabic end of ayah
case 0x070f: // Syriac abbreviation mark
case 0x17b4: // Khmer vowel inherent Aq
case 0x17b5: // Khmer vowel inherent Aa
HexEncodeUtf16CodeUnit(writer, c);
break;
default:
if ((c >= 0x0600 && c <= 0x0603) || // Arabic signs
(c >= 0x200b && c <= 0x200f) || // Zero width etc.
(c >= 0x2028 && c <= 0x202e) || // Separators etc.
(c >= 0x2060 && c <= 0x2064) || // Invisible etc.
(c >= 0x206a && c <= 0x206f))
{
HexEncodeUtf16CodeUnit(writer, c);
}
else
{
// No handling of surrogates here - that's done earlier
writer.Write(c);
}
break;
}
}
writer.Write('"');
}
See More Examples