System.IO.TextWriter.Write(char)

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

528 Examples 7

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : AnotherEnd15

private void PutString (string str)
        {
            Put (String.Empty);

            writer.Write ('"');
            writer.Write(str);
            writer.Write('"');
            return;
/*
            int n = str.Length;
            for (int i = 0; i < n; i++) {
                switch (str[i]) {
                case '\n':
                    writer.Write ("\\n");
                    continue;

                case '\r':
                    writer.Write ("\\r");
                    continue;

                case '\t':
                    writer.Write ("\\t");
                    continue;

                case '"':
                case '\\':
                    writer.Write ('\\');
                    writer.Write (str[i]);
                    continue;

                case '\f':
                    writer.Write ("\\f");
                    continue;

                case '\b':
                    writer.Write ("\\b");
                    continue;
                }

                if ((int) str[i] >= 32 && (int) str[i] <= 126) {
                    writer.Write (str[i]);
                    continue;
                }

                // Default, turn into a \uXXXX sequence
                IntToHex ((int) str[i], hex_seq);
                writer.Write ("\\u");
                writer.Write (hex_seq);
            }

            writer.Write ('"');
*/
        }

19 View Source File : LineProtocolPointBase.cs
License : Apache License 2.0
Project Creator : AppMetrics

protected void WriteCommon(TextWriter textWriter)
        {
            textWriter.Write(LineProtocolSyntax.EscapeName(Measurement));

            if (Tags.Count > 0)
            {
                for (var i = 0; i < Tags.Count; i++)
                {
                    textWriter.Write(',');
                    textWriter.Write(LineProtocolSyntax.EscapeName(Tags.Keys[i]));
                    textWriter.Write('=');
                    textWriter.Write(LineProtocolSyntax.EscapeName(Tags.Values[i]));
                }
            }
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

protected override void WriteIndentSpace()
        {
            _writer.Write(' ');
        }

19 View Source File : RequestWriter.cs
License : MIT License
Project Creator : angelobreuer

public static void WriteRequest(TextWriter writer, HttpRequestMessage request, long contentLength, NameValueCollection contentHeaders)
        {
            // status line
            writer.Write(request.Method);
            writer.Write(' ');
            writer.Write(request.RequestUri!.PathAndQuery);
            writer.Write(" HTTP/1.1");
            writer.Write(HTTP_EOL);

            WriteHeader(writer, "Content-Length", contentLength.ToString());

            // ---------------------------------------------------------- Shahid Changes
            // ------------------------------------------------------------ Content headers were
            // missing, and if they are not present and parsed, they will not be forwarded ahead
            // leading to errors

            foreach (string key in contentHeaders)
            {
                WriteHeader(writer, key, contentHeaders[key]);
            }

            // headers
            foreach (var (key, value) in request.Headers)
            {
                WriteHeader(writer, key, string.Join(",", value));
            }

            writer.Write(HTTP_EOL);
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(Guid value)
        {
            InternalWriteValue(JsonToken.String);

            string text = null;

#if !(DOTNET || PORTABLE40 || PORTABLE)
            text = value.ToString("D", CultureInfo.InvariantCulture);
#else
            text = value.ToString("D");
#endif

            _writer.Write(_quoteChar);
            _writer.Write(text);
            _writer.Write(_quoteChar);
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

protected override void WriteEnd(JsonToken token)
        {
            switch (token)
            {
                case JsonToken.EndObject:
                    _writer.Write('}');
                    break;
                case JsonToken.EndArray:
                    _writer.Write(']');
                    break;
                case JsonToken.EndConstructor:
                    _writer.Write(')');
                    break;
                default:
                    throw JsonWriterException.Create(this, "Invalid JsonToken: " + token, null);
            }
        }

19 View Source File : TextWriterAdapter.cs
License : Apache License 2.0
Project Creator : apache

public override void Write(char value) 
		{
			m_writer.Write(value);
		}

19 View Source File : Formatter.cs
License : MIT License
Project Creator : 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 View Source File : LineProtocolPoints.cs
License : Apache License 2.0
Project Creator : AppMetrics

public void Write(TextWriter textWriter, bool writeTimestamp = true)
        {
            if (textWriter == null)
            {
                return;
            }

            var points = _points.ToList();

            foreach (var point in points)
            {
                point.Write(textWriter, writeTimestamp);
                textWriter.Write('\n');
            }
        }

19 View Source File : Formatter.cs
License : MIT License
Project Creator : adrianoc

private static void WriteInstruction(TextWriter writer, Instruction instruction)
        {
            writer.Write(FormatLabel(instruction.Offset));
            writer.Write(": ");
            writer.Write(instruction.OpCode.Name);
            if (null != instruction.Operand)
            {
                writer.Write(' ');
                WriteOperand(writer, instruction.Operand);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : alexshtf

private static long MeasureMsec(string message, TextWriter logWriter, Action op)
        {
            logWriter.Write('\t');
            logWriter.Write(message);
            logWriter.Write(" ...");

            var stopWatch = Stopwatch.StartNew();
            op();
            var time = stopWatch.ElapsedMilliseconds;
            logWriter.WriteLine(" done in {0} msec", time);
            
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Default, true);
            return time;
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

private void WriteIntegerValue(long value)
        {
            if (value >= 0 && value <= 9)
            {
                _writer.Write((char)('0' + value));
            }
            else
            {
                ulong uvalue = (value < 0) ? (ulong)-value : (ulong)value;

                if (value < 0)
                {
                    _writer.Write('-');
                }

                WriteIntegerValue(uvalue);
            }
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteStartArray()
        {
            InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);

            _writer.Write('[');
        }

19 View Source File : LogstashJsonFormatter.cs
License : Apache License 2.0
Project Creator : anjoy8

private static void WriteProperties(IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
        {
            if (properties.Any()) output.Write(",");

            var precedingDelimiter = "";
            foreach (var property in properties)
            {
                output.Write(precedingDelimiter);
                precedingDelimiter = ",";

                var camelCasePropertyKey = property.Key[0].ToString().ToLower() + property.Key.Substring(1);
                JsonValueFormatter.WriteQuotedJsonString(camelCasePropertyKey, output);
                output.Write(':');
                ValueFormatter.Format(property.Value, output);
            }
        }

19 View Source File : HtmlRichTextWriter.cs
License : MIT License
Project Creator : Abdesol

public override void BeginSpan(HighlightingColor highlightingColor)
		{
			WriteIndentationAndSpace();
			if (options.ColorNeedsSpanForStyling(highlightingColor)) {
				htmlWriter.Write("<span");
				options.WriteStyleAttributeForColor(htmlWriter, highlightingColor);
				htmlWriter.Write('>');
				endTagStack.Push("</span>");
			} else {
				endTagStack.Push(null);
			}
		}

19 View Source File : AbsoluteTimeDateFormatter.cs
License : Apache License 2.0
Project Creator : apache

public virtual void FormatDate(DateTime dateToFormat, TextWriter writer)
		{
                    lock (s_lastTimeStrings)
		    {
			// Calculate the current time precise only to the second
			long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond));

                        string timeString = null;
			// Compare this time with the stored last time
			// If we are in the same second then append
			// the previously calculated time string
                        if (s_lastTimeToTheSecond != currentTimeToTheSecond)
                        {
                            s_lastTimeStrings.Clear();
                        }
                        else
                        {
                            timeString = (string) s_lastTimeStrings[GetType()];
                        }

                        if (timeString == null)
                        {
				// lock so that only one thread can use the buffer and
				// update the s_lastTimeToTheSecond and s_lastTimeStrings

				// PERF: Try removing this lock and using a new StringBuilder each time
				lock(s_lastTimeBuf)
				{
                                        timeString = (string) s_lastTimeStrings[GetType()];

                                        if (timeString == null)
                                        {
						// We are in a new second.
						s_lastTimeBuf.Length = 0;

						// Calculate the new string for this second
						FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf);

						// Render the string buffer to a string
                                                timeString = s_lastTimeBuf.ToString();

#if NET_1_1
						// Ensure that the above string is written into the variable NOW on all threads.
						// This is only required on multiprocessor machines with weak memeory models
						System.Threading.Thread.MemoryBarrier();
#endif
						// Store the time as a string (we only have to do this once per second)
                                                s_lastTimeStrings[GetType()] = timeString;
						s_lastTimeToTheSecond = currentTimeToTheSecond;
					}
				}
			}
			writer.Write(timeString);
	
			// Append the current millisecond info
			writer.Write(',');
			int millis = dateToFormat.Millisecond;
			if (millis < 100) 
			{
				writer.Write('0');
			}
			if (millis < 10) 
			{
				writer.Write('0');
			}
			writer.Write(millis);
                    }
		}

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WritePropertyName(string name, bool escape)
        {
            InternalWritePropertyName(name);

            if (escape)
            {
                WriteEscapedString(name, _quoteName);
            }
            else
            {
                if (_quoteName)
                {
                    _writer.Write(_quoteChar);
                }

                _writer.Write(name);

                if (_quoteName)
                {
                    _writer.Write(_quoteChar);
                }
            }

            _writer.Write(':');
        }

19 View Source File : HealthStatusTextWriter.cs
License : Apache License 2.0
Project Creator : AppMetrics

private void WriteCheckResult(HealthCheck.Result checkResult)
        {
            _textWriter.Write("# CHECK: ");
            _textWriter.Write(checkResult.Name);
            _textWriter.Write('\n');
            _textWriter.Write('\n');
            _textWriter.Write(FormatReadable("MESSAGE", checkResult.IsFromCache ? $"[Cached] {checkResult.Check.Message}" : checkResult.Check.Message));
            _textWriter.Write('\n');
            _textWriter.Write(FormatReadable("STATUS", HealthConstants.HealthStatusDisplay[checkResult.Check.Status]));
            _textWriter.Write("\n--------------------------------------------------------------");
            _textWriter.Write('\n');
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : 404Lcc

private void PutNewline (bool add_comma)
        {
            if (add_comma && ! context.ExpectingValue &&
                context.Count > 1)
                writer.Write (',');

            if (pretty_print && ! context.ExpectingValue)
                writer.Write ('\n');
        }

19 View Source File : LineProtocolPointMultipleValues.cs
License : Apache License 2.0
Project Creator : AppMetrics

public void Write(TextWriter textWriter, bool writeTimestamp = true)
        {
            if (textWriter == null)
            {
                throw new ArgumentNullException(nameof(textWriter));
            }

            WriteCommon(textWriter);

            var fieldDelim = ' ';

            using (var nameEnumerator = FieldsNames.GetEnumerator())
            using (var valueEnumerator = FieldsValues.GetEnumerator())
            {
                while (nameEnumerator.MoveNext() && valueEnumerator.MoveNext())
                {
                    var name = nameEnumerator.Current;
                    var value = valueEnumerator.Current;

                    textWriter.Write(fieldDelim);
                    fieldDelim = ',';
                    textWriter.Write(LineProtocolSyntax.EscapeName(name));
                    textWriter.Write('=');
                    textWriter.Write(LineProtocolSyntax.FormatValue(value));
                }
            }

            if (!writeTimestamp)
            {
                return;
            }

            WriteTimestamp(textWriter);
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(byte[] value)
        {
            if (value == null)
            {
                WriteNull();
            }
            else
            {
                InternalWriteValue(JsonToken.Bytes);
                _writer.Write(_quoteChar);
                Base64Encoder.Encode(value, 0, value.Length);
                Base64Encoder.Flush();
                _writer.Write(_quoteChar);
            }
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(DateTimeOffset value)
        {
            InternalWriteValue(JsonToken.Date);

            if (string.IsNullOrEmpty(DateFormatString))
            {
                EnsureWriteBuffer();

                int pos = 0;
                _writeBuffer[pos++] = _quoteChar;
                pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, (DateFormatHandling == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, DateFormatHandling);
                _writeBuffer[pos++] = _quoteChar;

                _writer.Write(_writeBuffer, 0, pos);
            }
            else
            {
                _writer.Write(_quoteChar);
                _writer.Write(value.ToString(DateFormatString, Culture));
                _writer.Write(_quoteChar);
            }
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : 404Lcc

public void WritePropertyName (string property_name)
        {
            DoValidation (Condition.Property);
            PutNewline ();

            PutString (property_name);

            if (pretty_print) {
                if (property_name.Length > context.Padding)
                    context.Padding = property_name.Length;

                for (int i = context.Padding - property_name.Length;
                     i >= 0; i--)
                    writer.Write (' ');

                writer.Write (": ");
            } else
                writer.Write (':');

            context.ExpectingValue = true;
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(TimeSpan value)
        {
            InternalWriteValue(JsonToken.String);

            string text;
#if (NET35 || NET20)
            text = value.ToString();
#else
            text = value.ToString(null, CultureInfo.InvariantCulture);
#endif

            _writer.Write(_quoteChar);
            _writer.Write(text);
            _writer.Write(_quoteChar);
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr

public override void Write(char value)
            {
                base.Write(value);
                _output.Dispatcher.BeginInvoke(new Action(() =>
                {
                    _output.AppendText(value.ToString());
                }));
            }

19 View Source File : HexUtils.cs
License : MIT License
Project Creator : alexanderdna

public static void AppendHexFromLong(TextWriter writer, long value)
        {
            writer.Write(hexMap8[((ulong)value & 0xf0000000_00000000) >> 60]);
            writer.Write(hexMap8[(value & 0x0f000000_00000000) >> 56]);
            writer.Write(hexMap8[(value & 0x00f00000_00000000) >> 52]);
            writer.Write(hexMap8[(value & 0x000f0000_00000000) >> 48]);

            writer.Write(hexMap8[(value & 0x0000f000_00000000) >> 44]);
            writer.Write(hexMap8[(value & 0x00000f00_00000000) >> 40]);
            writer.Write(hexMap8[(value & 0x000000f0_00000000) >> 36]);
            writer.Write(hexMap8[(value & 0x0000000f_00000000) >> 32]);

            writer.Write(hexMap8[(value & 0x00000000_f0000000) >> 28]);
            writer.Write(hexMap8[(value & 0x00000000_0f000000) >> 24]);
            writer.Write(hexMap8[(value & 0x00000000_00f00000) >> 20]);
            writer.Write(hexMap8[(value & 0x00000000_000f0000) >> 16]);

            writer.Write(hexMap8[(value & 0x00000000_0000f000) >> 12]);
            writer.Write(hexMap8[(value & 0x00000000_00000f00) >> 8]);
            writer.Write(hexMap8[(value & 0x00000000_000000f0) >> 4]);
            writer.Write(hexMap8[(value & 0x00000000_0000000f)]);
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

private void WriteIntegerValue(ulong uvalue)
        {
            if (uvalue <= 9)
            {
                _writer.Write((char)('0' + uvalue));
            }
            else
            {
                EnsureWriteBuffer();

                int totalLength = MathUtils.IntLength(uvalue);
                int length = 0;

                do
                {
                    _writeBuffer[totalLength - ++length] = (char)('0' + (uvalue % 10));
                    uvalue /= 10;
                } while (uvalue != 0);

                _writer.Write(_writeBuffer, 0, length);
            }
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteStartObject()
        {
            InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);

            _writer.Write('{');
        }

19 View Source File : MessagePackSerializer.Json.cs
License : Apache License 2.0
Project Creator : allenai

private static void WriteJsonString(string value, TextWriter builder)
        {
            builder.Write('\"');

            var len = value.Length;
            for (int i = 0; i < len; i++)
            {
                var c = value[i];
                switch (c)
                {
                    case '"':
                        builder.Write("\\\"");
                        break;
                    case '\\':
                        builder.Write("\\\\");
                        break;
                    case '\b':
                        builder.Write("\\b");
                        break;
                    case '\f':
                        builder.Write("\\f");
                        break;
                    case '\n':
                        builder.Write("\\n");
                        break;
                    case '\r':
                        builder.Write("\\r");
                        break;
                    case '\t':
                        builder.Write("\\t");
                        break;
                    default:
                        builder.Write(c);
                        break;
                }
            }

            builder.Write('\"');
        }

19 View Source File : HtmlRichTextWriter.cs
License : MIT License
Project Creator : Abdesol

void FlushSpace(bool nextIsWhitespace)
		{
			if (hreplacedpace) {
				if (spaceNeedsEscaping || nextIsWhitespace)
					htmlWriter.Write(" ");
				else
					htmlWriter.Write(' ');
				hreplacedpace = false;
				spaceNeedsEscaping = true;
			}
		}

19 View Source File : LogstashJsonFormatter.cs
License : Apache License 2.0
Project Creator : anjoy8

private static void FormatContent(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
            if (output == null) throw new ArgumentNullException(nameof(output));

            output.Write('{');

            // 读取相关配置
            var logConfigRootDTOInfo = JsonConfigUtils.GetAppSettings<LogConfigRootDTO>(AppSettingsFileNameConfig.AppSettingsFileName, "LogFiedOutPutConfigs");
            if (logConfigRootDTOInfo == null)
            {
                return;
            }

            // 写入所有的项目配置项的字段 在appsetting中配置的 输出elk节点的数据字段
            foreach (var item in logConfigRootDTOInfo.ConfigsInfo)
            {
                switch (item.FiedName)
                {
                    //case "orgid":
                    //    WritePropertyAndValue(output, "method", HttpContextProvider.GetCurrent().Request.Method);
                    //    output.Write(",");
                    //    break;
                    default:
                        WritePropertyAndValue(output, item.FiedName, item.FiedValue);
                        output.Write(",");
                        break;
                }
            }
            // 写入http对应的信息数据
            if (HttpContextProvider.GetCurrent()!=null && HttpContextProvider.GetCurrent().Request!=null)
            {
                if (!string.IsNullOrEmpty(HttpContextProvider.GetCurrent().Request.Method))
                {
                    WritePropertyAndValue(output, "method", HttpContextProvider.GetCurrent().Request.Method);
                    output.Write(",");
                }
                // 输出请求页面url
                if (!string.IsNullOrEmpty(HttpContextProvider.GetCurrent().Request.Path))
                {
                    WritePropertyAndValue(output, "requestUrl", HttpContextProvider.GetCurrent().Request.Path.ToString());
                    output.Write(",");
                }
                // 输出携带token
                if (HttpContextProvider.GetCurrent().Request.Headers["Authorization"].FirstOrDefault() != null)
                {
                    WritePropertyAndValue(output, "Authorization", HttpContextProvider.GetCurrent().Request.Headers["Authorization"].FirstOrDefault());
                    output.Write(",");
                }
                // 输出请求参数
                if (!string.IsNullOrEmpty(HttpContextProvider.GetCurrent().Request.Method))
                {
                    string contentFromBody = ParamsHelper.GetParams(HttpContextProvider.GetCurrent());
                    WritePropertyAndValue(output, "requestParam", contentFromBody);
                    output.Write(",");
                }
                // 输出请求方法类型
                if (!string.IsNullOrEmpty(HttpContextProvider.GetCurrent().Request.Method))
                {
                    WritePropertyAndValue(output, "method", HttpContextProvider.GetCurrent().Request.Method);
                    output.Write(",");
                }
            }
            // 输出请求时间戳
            WritePropertyAndValue(output, "timestamp", logEvent.Timestamp.ToString("o"));
            output.Write(",");

            // 输出日志级别
            WritePropertyAndValue(output, "level", logEvent.Level.ToString());
            output.Write(",");
          
            // 输出log内容
            WritePropertyAndValue(output, "executeResult", logEvent.MessageTemplate.Render(logEvent.Properties));

            if (logEvent.Exception != null)
            {
                output.Write(",");
                WritePropertyAndValue(output, "exception", logEvent.Exception.ToString());
            }

            WriteProperties(logEvent.Properties, output);

            output.Write('}');
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteStartConstructor(string name)
        {
            InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);

            _writer.Write("new ");
            _writer.Write(name);
            _writer.Write('(');
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : AnotherEnd15

private void PutNewline (bool add_comma)
        {
            if (add_comma && ! context.ExpectingValue &&
                context.Count > 1)
                writer.Write (',');

            if (pretty_print && ! context.ExpectingValue)
                writer.Write (Environment.NewLine);
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : 404Lcc

private void Put (string str)
        {
            if (pretty_print && ! context.ExpectingValue)
                for (int i = 0; i < indentation; i++)
                    writer.Write (' ');

            writer.Write (str);
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : AnotherEnd15

public void WritePropertyName (string property_name)
        {
            DoValidation (Condition.Property);
            PutNewline ();
            string propertyName = (property_name == null || !lower_case_properties)
                ? property_name
                : property_name.ToLowerInvariant();

            PutString (propertyName);

            if (pretty_print) {
                if (propertyName.Length > context.Padding)
                    context.Padding = propertyName.Length;

                for (int i = context.Padding - propertyName.Length;
                     i >= 0; i--)
                    writer.Write (' ');

                writer.Write (": ");
            } else
                writer.Write (':');

            context.ExpectingValue = true;
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WritePropertyName(string name)
        {
            InternalWritePropertyName(name);

            WriteEscapedString(name, _quoteName);

            _writer.Write(':');
        }

19 View Source File : RandomStringPatternConverter.cs
License : Apache License 2.0
Project Creator : apache

protected override void Convert(TextWriter writer, object state) 
		{
			try 
			{
				lock(s_random)
				{
					for(int i=0; i<m_length; i++)
					{
						int randValue = s_random.Next(36);

						if (randValue < 26)
						{
							// Letter
							char ch = (char)('A' + randValue);
							writer.Write(ch);
						}
						else if (randValue < 36)
						{
							// Number
							char ch = (char)('0' + (randValue - 26));
							writer.Write(ch);
						}
						else
						{
							// Should not get here
							writer.Write('X');
						}
					}
				}
			}
			catch (Exception ex) 
			{
				LogLog.Error(declaringType, "Error occurred while converting.", ex);
			}
		}

19 View Source File : PlainRichTextWriter.cs
License : MIT License
Project Creator : Abdesol

public override void Write(char value)
		{
			if (prevChar == '\n')
				WriteIndentation();
			textWriter.Write(value);
			prevChar = value;
			AfterWrite();
		}

19 View Source File : BulkPayload.cs
License : Apache License 2.0
Project Creator : AppMetrics

public void Write(TextWriter textWriter, Guid? doreplacedentId = null)
        {
            if (textWriter == null)
            {
                return;
            }

            foreach (var doreplacedent in _doreplacedents)
            {
                _serializer.Serialize(
                    textWriter,
                    new BulkDoreplacedentMetaData($"{_indexName}.{doreplacedent.MeasurementType}", doreplacedent.MeasurementType, doreplacedentId));

                textWriter.Write('\n');
                _serializer.Serialize(textWriter, doreplacedent);
                textWriter.Write('\n');
            }
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

protected override void WriteValueDelimiter()
        {
            _writer.Write(',');
        }

19 View Source File : LineProtocolPointBase.cs
License : Apache License 2.0
Project Creator : AppMetrics

protected void WriteTimestamp(TextWriter textWriter)
        {
            textWriter.Write(' ');

            if (UtcTimestamp == null)
            {
                textWriter.Write(LineProtocolSyntax.FormatTimestamp(DateTime.UtcNow));
                return;
            }

            textWriter.Write(LineProtocolSyntax.FormatTimestamp(UtcTimestamp.Value));
        }

19 View Source File : Disassembler.cs
License : MIT License
Project Creator : 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 View Source File : LineProtocolPointLegacy.cs
License : Apache License 2.0
Project Creator : AppMetrics

public void Write(TextWriter textWriter, bool writeTimestamp = true)
        {
            if (textWriter == null)
            {
                throw new ArgumentNullException(nameof(textWriter));
            }

            textWriter.Write(LineProtocolSyntax.EscapeName(Measurement));

            if (Tags.Count > 0)
            {
                for (var i = 0; i < Tags.Count; i++)
                {
                    textWriter.Write(',');
                    textWriter.Write(LineProtocolSyntax.EscapeName(Tags.Keys[i]));
                    textWriter.Write('=');
                    textWriter.Write(LineProtocolSyntax.EscapeName(Tags.Values[i]));
                }
            }

            var fieldDelim = ' ';

            foreach (var f in Fields)
            {
                textWriter.Write(fieldDelim);
                fieldDelim = ',';
                textWriter.Write(LineProtocolSyntax.EscapeName(f.Key));
                textWriter.Write('=');
                textWriter.Write(LineProtocolSyntax.FormatValue(f.Value));
            }

            if (!writeTimestamp)
            {
                return;
            }

            textWriter.Write(' ');

            if (UtcTimestamp == null)
            {
                textWriter.Write(LineProtocolSyntax.FormatTimestamp(DateTime.UtcNow));
                return;
            }

            textWriter.Write(LineProtocolSyntax.FormatTimestamp(UtcTimestamp.Value));
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(DateTime value)
        {
            InternalWriteValue(JsonToken.Date);
            value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);

            if (string.IsNullOrEmpty(DateFormatString))
            {
                EnsureWriteBuffer();

                int pos = 0;
                _writeBuffer[pos++] = _quoteChar;
                pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, value, null, value.Kind, DateFormatHandling);
                _writeBuffer[pos++] = _quoteChar;

                _writer.Write(_writeBuffer, 0, pos);
            }
            else
            {
                _writer.Write(_quoteChar);
                _writer.Write(value.ToString(DateFormatString, Culture));
                _writer.Write(_quoteChar);
            }
        }

19 View Source File : Formatter.cs
License : MIT License
Project Creator : adrianoc

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

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

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

                var variable = variables[i];

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

            writer.WriteLine(")");
        }

19 View Source File : LogWriter.cs
License : MIT License
Project Creator : 0x0ade

public override void Write(char value) {
            STDOUT?.Write(value);
            File?.Write(value);
            File?.Flush();
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : 404Lcc

private void PutString (string str)
        {
            Put (String.Empty);

            writer.Write ('"');

            int n = str.Length;
            for (int i = 0; i < n; i++) {
                switch (str[i]) {
                case '\n':
                    writer.Write ("\\n");
                    continue;

                case '\r':
                    writer.Write ("\\r");
                    continue;

                case '\t':
                    writer.Write ("\\t");
                    continue;

                case '"':
                case '\\':
                    writer.Write ('\\');
                    writer.Write (str[i]);
                    continue;

                case '\f':
                    writer.Write ("\\f");
                    continue;

                case '\b':
                    writer.Write ("\\b");
                    continue;
                }

                if ((int) str[i] >= 32 && (int) str[i] <= 126) {
                    writer.Write (str[i]);
                    continue;
                }

                // Default, turn into a \uXXXX sequence
                IntToHex ((int) str[i], hex_seq);
                writer.Write ("\\u");
                writer.Write (hex_seq);
            }

            writer.Write ('"');
        }

19 View Source File : HtmlOptions.cs
License : MIT License
Project Creator : Abdesol

public virtual void WriteStyleAttributeForColor(TextWriter writer, HighlightingColor color)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			if (color == null)
				throw new ArgumentNullException("color");
			writer.Write(" style=\"");
			WebUtility.HtmlEncode(color.ToCss(), writer);
			writer.Write('"');
		}

19 View Source File : JavaScriptUtils.cs
License : MIT License
Project Creator : akaskela

public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters,
            bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer)
        {
            // leading delimiter
            if (appendDelimiters)
            {
                writer.Write(delimiter);
            }

            if (s != null)
            {
                int lastWritePosition = 0;

                for (int i = 0; i < s.Length; i++)
                {
                    var c = s[i];

                    if (c < charEscapeFlags.Length && !charEscapeFlags[c])
                    {
                        continue;
                    }

                    string escapedValue;

                    switch (c)
                    {
                        case '\t':
                            escapedValue = @"\t";
                            break;
                        case '\n':
                            escapedValue = @"\n";
                            break;
                        case '\r':
                            escapedValue = @"\r";
                            break;
                        case '\f':
                            escapedValue = @"\f";
                            break;
                        case '\b':
                            escapedValue = @"\b";
                            break;
                        case '\\':
                            escapedValue = @"\\";
                            break;
                        case '\u0085': // Next Line
                            escapedValue = @"\u0085";
                            break;
                        case '\u2028': // Line Separator
                            escapedValue = @"\u2028";
                            break;
                        case '\u2029': // Paragraph Separator
                            escapedValue = @"\u2029";
                            break;
                        default:
                            if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
                            {
                                if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
                                {
                                    escapedValue = @"\'";
                                }
                                else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
                                {
                                    escapedValue = @"\""";
                                }
                                else
                                {
                                    if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength)
                                    {
                                        writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer);
                                    }

                                    StringUtils.ToCharAsUnicode(c, writeBuffer);

                                    // slightly hacky but it saves multiple conditions in if test
                                    escapedValue = EscapedUnicodeText;
                                }
                            }
                            else
                            {
                                escapedValue = null;
                            }
                            break;
                    }

                    if (escapedValue == null)
                    {
                        continue;
                    }

                    bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText);

                    if (i > lastWritePosition)
                    {
                        int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0);
                        int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0;

                        if (writeBuffer == null || writeBuffer.Length < length)
                        {
                            char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length);

                            // the unicode text is already in the buffer
                            // copy it over when creating new buffer
                            if (isEscapedUnicodeText)
                            {
                                Array.Copy(writeBuffer, newBuffer, UnicodeTextLength);
                            }

                            BufferUtils.ReturnBuffer(bufferPool, writeBuffer);

                            writeBuffer = newBuffer;
                        }

                        s.CopyTo(lastWritePosition, writeBuffer, start, length - start);

                        // write unchanged chars before writing escaped text
                        writer.Write(writeBuffer, start, length - start);
                    }

                    lastWritePosition = i + 1;
                    if (!isEscapedUnicodeText)
                    {
                        writer.Write(escapedValue);
                    }
                    else
                    {
                        writer.Write(writeBuffer, 0, UnicodeTextLength);
                    }
                }

                if (lastWritePosition == 0)
                {
                    // no escaped text, write entire string
                    writer.Write(s);
                }
                else
                {
                    int length = s.Length - lastWritePosition;

                    if (writeBuffer == null || writeBuffer.Length < length)
                    {
                        writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer);
                    }

                    s.CopyTo(lastWritePosition, writeBuffer, 0, length);

                    // write remaining text
                    writer.Write(writeBuffer, 0, length);
                }
            }

            // trailing delimiter
            if (appendDelimiters)
            {
                writer.Write(delimiter);
            }
        }

19 View Source File : HexUtils.cs
License : MIT License
Project Creator : alexanderdna

public static void AppendHexFromInt(TextWriter writer, int value)
        {
            writer.Write(hexMap8[(value & 0xf0000000) >> 28]);
            writer.Write(hexMap8[(value & 0x0f000000) >> 24]);
            writer.Write(hexMap8[(value & 0x00f00000) >> 20]);
            writer.Write(hexMap8[(value & 0x000f0000) >> 16]);

            writer.Write(hexMap8[(value & 0x0000f000) >> 12]);
            writer.Write(hexMap8[(value & 0x00000f00) >> 8]);
            writer.Write(hexMap8[(value & 0x000000f0) >> 4]);
            writer.Write(hexMap8[(value & 0x0000000f)]);
        }

See More Examples