System.IO.StringWriter.ToString()

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

2451 Examples 7

19 Source : HtmlContent.cs
with MIT License
from 188867052

internal static string ToHtml(IHtmlContent content)
        {
            using (var writer = new StringWriter())
            {
                content.WriteTo(writer, HtmlEncoder.Default);
                return writer.ToString();
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, string code, List<DbTableInfo> dbTables, DbTableInfo dbTableInfo)
        {
            StringBuilder plus = new StringBuilder();
            try
            {
                var config = new TemplateServiceConfiguration();
                config.EncodedStringFactory = new RawStringFactory();
                Engine.Razor = RazorEngineService.Create(config);
                var razorId = Guid.NewGuid().ToString("N");
                Engine.Razor.Compile(code, razorId);

                var sw = new StringWriter();
                var model = new RazorModel(taskBuild, dbTables, dbTableInfo);
                Engine.Razor.Run(razorId, sw, null, model);

                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.AppendLine("// <auto-generated>");
                plus.AppendLine("//     此代码由工具生成。");
                plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                plus.AppendLine("//     Website: http://www.freesql.net");
                plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                plus.AppendLine("// </auto-generated>");
                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.Append(sw.ToString());
                plus.AppendLine();
                return await Task.FromResult(plus.ToString());
            }
            catch
            {
                return await Task.FromResult(plus.ToString());
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

19 Source : JsonData.cs
with MIT License
from 404Lcc

public string ToJson ()
        {
            if (json != null)
                return json;

            StringWriter sw = new StringWriter ();
            JsonWriter writer = new JsonWriter (sw);
            writer.Validate = false;

            WriteJson (this, writer);
            json = sw.ToString ();

            return json;
        }

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

static void Main(string[] args)
        {
            for (int i = 0; i < tag.Length; i++)
            {
                for (int j = 0; j < scd.Length; j++)
                {
                    Gen1(tag[i], scd[j]);
                }
            }
            File.WriteAllText("./EnreplacedyManagerUtilitySingleton.gen", sw.ToString());
        }

19 Source : HighlightedLine.cs
with MIT License
from Abdesol

public string ToHtml(HtmlOptions options = null)
		{
			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
				WriteTo(htmlWriter);
			}
			return stringWriter.ToString();
		}

19 Source : HighlightedLine.cs
with MIT License
from Abdesol

public string ToHtml(int startOffset, int endOffset, HtmlOptions options = null)
		{
			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
				WriteTo(htmlWriter, startOffset, endOffset);
			}
			return stringWriter.ToString();
		}

19 Source : RichText.cs
with MIT License
from Abdesol

public string ToHtml(HtmlOptions options = null)
		{
			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
				htmlWriter.Write(this);
			}
			return stringWriter.ToString();
		}

19 Source : RichText.cs
with MIT License
from Abdesol

public string ToHtml(int offset, int length, HtmlOptions options = null)
		{
			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
				htmlWriter.Write(this, offset, length);
			}
			return stringWriter.ToString();
		}

19 Source : SyncUsageHelper.cs
with MIT License
from ABTSoftware

public void WriteToIsolatedStorage()
        {
            try
            {
                using (var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.replacedembly,
                    null, null))
                {
                    using (var stream = new IsolatedStorageFileStream("Usage.xml", FileMode.Create, isf))
                    {
                        var xml = SerializationUtil.Serialize(
                            _usageCalculator.Usages.Values.Where(e => e.VisitCount > 0));
                        xml.Root.Add(new XAttribute("UserId", userId));
                        xml.Root.Add(new XAttribute("Enabled", Enabled));
                        xml.Root.Add(new XAttribute("LastSent", lastSent.ToString("o")));

                        using (var stringWriter = new StringWriter())
                        {
                            xml.Save(stringWriter);

                            var encryptedUsage = _encryptionHelper.Encrypt(stringWriter.ToString());
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.Write(encryptedUsage);
                            }
                        }
                    }
                }
            }
            catch { }
        }

19 Source : XMLSerializer.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public string Serialize<T>(T ObjectToSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

            using (StringWriter textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, ObjectToSerialize);
                return textWriter.ToString();
            }
        }

19 Source : LiquidExtensions.cs
with MIT License
from Adoxio

public static string WebTemplate(this HtmlHelper html, EnreplacedyReference webTemplateReference, IDictionary<string, object> variables = null, Action fallback = null)
		{
			using (var output = new StringWriter())
			{
				RenderWebTemplate(html, webTemplateReference, output, variables, fallback);
				return output.ToString();
			}
		}

19 Source : LiquidExtensions.cs
with MIT License
from Adoxio

internal static string WebTemplate(this HtmlHelper html, EnreplacedyReference webTemplateReference, Context context)
		{
			if (webTemplateReference == null) throw new ArgumentNullException("webTemplateReference");

			using (var output = new StringWriter())
			{
				RenderWebTemplate(html, webTemplateReference, output, context);
				return output.ToString();
			}
		}

19 Source : LiquidExtensions.cs
with MIT License
from Adoxio

public static string Liquid(this HtmlHelper html, string source, IDictionary<string, object> variables = null)
		{
			using (var output = new StringWriter())
			{
				RenderLiquid(html, source, null, output, variables);
				return output.ToString();
			}
		}

19 Source : LiquidExtensions.cs
with MIT License
from Adoxio

internal static string Liquid(this HtmlHelper html, string source, Context context)
		{
			using (var output = new StringWriter())
			{
				InternalRenderLiquid(source, null, output, context);
				return output.ToString();
			}
		}

19 Source : ChatAuthController.cs
with MIT License
from Adoxio

[HttpGet]
		[AllowAnonymous]
		public ActionResult PublicKey()
		{
			using (var cryptoServiceProvider = ChatAuthController.GetCryptoProvider(false))
			{
				var stringWriter = new StringWriter();
				ChatAuthController.ExportPublicKey(cryptoServiceProvider, stringWriter);
				return this.Content(stringWriter.ToString(), "text/plain");
			}
		}

19 Source : WebTemplateNoMaster.aspx.cs
with MIT License
from Adoxio

protected void Page_Init(object sender, EventArgs args)
		{
			if (!System.Web.SiteMap.Enabled)
			{
				return;
			}

			var currentNode = System.Web.SiteMap.CurrentNode;

			if (currentNode == null)
			{
				return;
			}

			var templateIdString = currentNode["adx_webtemplateid"];

			if (string.IsNullOrEmpty(templateIdString))
			{
				return;
			}

			Guid templateId;

			if (!Guid.TryParse(templateIdString, out templateId))
			{
				return;
			}

			var fetch = new Fetch
			{
				Enreplacedy = new FetchEnreplacedy("adx_webtemplate")
				{
					Attributes = new[] { new FetchAttribute("adx_source"), new FetchAttribute("adx_mimetype") },
					Filters = new[]
					{
						new Filter
						{
							Conditions = new[]
							{
								new Condition("adx_webtemplateid", ConditionOperator.Equal, templateId),
								new Condition("statecode", ConditionOperator.Equal, 0)
							}
						}
					}
				}
			};

			var webTemplate = PortalOrganizationService.RetrieveSingle(fetch);
			if (webTemplate == null)
			{
				return;
			}

			var source = webTemplate.GetAttributeValue<string>("adx_source");
			using (var output = new System.IO.StringWriter())
			{
				Html.RenderLiquid(source, string.Format("{0}:{1}", webTemplate.LogicalName, webTemplate.Id), output);
				Liquid.Html = output.ToString();
			}

			var mimetype = webTemplate.GetAttributeValue<string>("adx_mimetype");

			if (!string.IsNullOrWhiteSpace(mimetype))
			{
				ContentType = mimetype;
			}
		}

19 Source : Formatter.cs
with MIT License
from adrianoc

public static string FormatInstruction(Instruction instruction)
        {
            var writer = new StringWriter();
            WriteInstruction(writer, instruction);
            return writer.ToString();
        }

19 Source : Formatter.cs
with MIT License
from adrianoc

public static string FormatMethodBody(MethodDefinition method)
        {
            var writer = new StringWriter();
            WriteMethodBody(writer, method);
            return writer.ToString();
        }

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

public Control GetView(File file)
        {
            var data = file.GetData();

            var ms = new MemoryStream(data);
            var hyperTextFile = new HyperTextFile();
            try
            {
                hyperTextFile.Open(ms);
            }
            finally
            {
                ms.Close();
            }

            StringWriter sw = new StringWriter();
            hyperTextFile.WriteHTML(sw);

            // Create a temporary folder
            string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string htmlPath = Path.Combine(tempPath, "exported.html");

            Directory.CreateDirectory(tempPath);
            System.IO.File.WriteAllText(htmlPath, sw.ToString());

            if (hyperTextFile.EmbeddedTextureFile != null)
            {
                foreach (var texture in hyperTextFile.EmbeddedTextureFile)
                {
                    string imagePath = Path.Combine(tempPath, texture.Name + ".png");

                    string directory = Path.GetDirectoryName(imagePath);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    Image image = texture.Decode();
                    image.Save(imagePath, ImageFormat.Png);
                }
            }

            WebBrowser browser = new WebBrowser();
            browser.AllowNavigation = false;
            browser.AllowWebBrowserDrop = false;
            //_browser.WebBrowserShortcutsEnabled = false;
            //_browser.IsWebBrowserContextMenuEnabled = false;

            //browser.DoreplacedentText = sw.ToString();
            browser.Navigate(htmlPath);

            browser.Disposed += delegate
                                    {
                                        Directory.Delete(tempPath, true);

                                        if (hyperTextFile.EmbeddedTextureFile != null)
                                        {
                                            hyperTextFile.EmbeddedTextureFile.Dispose();
                                        }
                                    };

            return browser;
        }

19 Source : StringExtensions.cs
with MIT License
from ahydrax

public static string JsonPretiffy(this string json)
        {
            using (var stringReader = new StringReader(json))
            using (var stringWriter = new StringWriter())
            {
                var jsonReader = new JsonTextReader(stringReader);
                var jsonWriter = new JsonTextWriter(stringWriter)
                {
                    Formatting = Formatting.Indented
                };
                jsonWriter.WriteToken(jsonReader);
                return stringWriter.ToString();
            }
        }

19 Source : DiscordJson.cs
with MIT License
from Aiko-IT-Systems

private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
        {
            var stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
            using (var jsonTextWriter = new JsonTextWriter(stringWriter))
            {
                jsonTextWriter.Formatting = jsonSerializer.Formatting;
                jsonSerializer.Serialize(jsonTextWriter, value, type);
            }
            return stringWriter.ToString();
        }

19 Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static string GetPubKey()
        {
            StringWriter outStream = new StringWriter();
            ExportPublicKey(Config.Rsa, outStream);
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(outStream.ToString()));
        }

19 Source : ScreenTests.cs
with MIT License
from akamud

[Test]
            public void ShouldPrintTheVisualTreeWithItsElements()
            {
                var stringWriter = new StringWriter();
                TestingLibraryOptions.DebugOptions.OutputTextWriter = stringWriter;
                var testPage = new ContentPage
                {
                    Content = new StackLayout
                    {
                        AutomationId = "aut", HeightRequest = 50, Children = {new Label {Text = "LabelText"}}
                    }
                };
                var screen = new Renderer<App>().Render(testPage);

                screen.Debug();

                var debugText = stringWriter.ToString();
                var br = Environment.NewLine;
                var expectedDebugText =
                    $"ContentPage{br}`-- StackLayout{br}    |-- AutomationId: aut{br}    |-- HeightRequest: 50{br}    `-- Label{br}        |-- Text: LabelText{br}        `-- FormattedText: <null>{br}";
                debugText.Should().BeEquivalentTo(expectedDebugText);

                TestingLibraryOptions.DebugOptions.OutputTextWriter = Console.Out;
            }

19 Source : JRaw.cs
with MIT License
from akaskela

public static JRaw Create(JsonReader reader)
        {
            using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.WriteToken(reader);

                return new JRaw(sw.ToString());
            }
        }

19 Source : JToken.cs
with MIT License
from akaskela

public string ToString(Formatting formatting, params JsonConverter[] converters)
        {
            using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonTextWriter jw = new JsonTextWriter(sw);
                jw.Formatting = formatting;

                WriteTo(jw, converters);

                return sw.ToString();
            }
        }

19 Source : QueryExpression.cs
with MIT License
from akaskela

private bool EqualsWithStringCoercion(JValue value, JValue queryValue)
        {
            if (value.Equals(queryValue))
            {
                return true;
            }

            if (queryValue.Type != JTokenType.String)
            {
                return false;
            }

            string queryValueString = (string)queryValue.Value;

            string currentValueString;

            // potential performance issue with converting every value to string?
            switch (value.Type)
            {
                case JTokenType.Date:
                    using (StringWriter writer = StringUtils.CreateStringWriter(64))
                    {
#if !NET20
                        if (value.Value is DateTimeOffset)
                        {
                            DateTimeUtils.WriteDateTimeOffsetString(writer, (DateTimeOffset)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture);
                        }
                        else
#endif
                        {
                            DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture);
                        }

                        currentValueString = writer.ToString();
                    }
                    break;
                case JTokenType.Bytes:
                    currentValueString = Convert.ToBase64String((byte[])value.Value);
                    break;
                case JTokenType.Guid:
                case JTokenType.TimeSpan:
                    currentValueString = value.Value.ToString();
                    break;
                case JTokenType.Uri:
                    currentValueString = ((Uri)value.Value).OriginalString;
                    break;
                default:
                    return false;
            }

            return string.Equals(currentValueString, queryValueString, StringComparison.Ordinal);
        }

19 Source : JsonConvert.cs
with MIT License
from akaskela

public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
        {
            DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);

            using (StringWriter writer = StringUtils.CreateStringWriter(64))
            {
                writer.Write('"');
                DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
                writer.Write('"');
                return writer.ToString();
            }
        }

19 Source : JsonConvert.cs
with MIT License
from akaskela

public static string ToString(DateTimeOffset value, DateFormatHandling format)
        {
            using (StringWriter writer = StringUtils.CreateStringWriter(64))
            {
                writer.Write('"');
                DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
                writer.Write('"');
                return writer.ToString();
            }
        }

19 Source : JsonSerializerInternalWriter.cs
with MIT License
from akaskela

private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
        {
            string propertyName;

            if (contract.ContractType == JsonContractType.Primitive)
            {
                JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
                if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
                {
                    DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling);

                    escape = false;
                    StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
                    DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
                    return sw.ToString();
                }
#if !NET20
                else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
                {
                    escape = false;
                    StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
                    DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
                    return sw.ToString();
                }
#endif
                else
                {
                    escape = true;
                    return Convert.ToString(name, CultureInfo.InvariantCulture);
                }
            }
            else if (TryConvertToString(name, name.GetType(), out propertyName))
            {
                escape = true;
                return propertyName;
            }
            else
            {
                escape = true;
                return name.ToString();
            }
        }

19 Source : JavaScriptUtils.cs
with MIT License
from akaskela

public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling)
        {
            bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter);

            using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16))
            {
                char[] buffer = null;
                WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer);
                return w.ToString();
            }
        }

19 Source : JsonValidatingReader.cs
with MIT License
from akaskela

private void WriteToken(IList<JsonSchemaModel> schemas)
        {
            foreach (SchemaScope schemaScope in _stack)
            {
                bool isInUniqueArray = (schemaScope.TokenType == JTokenType.Array && schemaScope.IsUniqueArray && schemaScope.ArrayItemCount > 0);

                if (isInUniqueArray || schemas.Any(s => s.Enum != null))
                {
                    if (schemaScope.CurrenreplacedemWriter == null)
                    {
                        if (JsonTokenUtils.IsEndToken(_reader.TokenType))
                        {
                            continue;
                        }

                        schemaScope.CurrenreplacedemWriter = new JTokenWriter();
                    }

                    schemaScope.CurrenreplacedemWriter.WriteToken(_reader, false);

                    // finished writing current item
                    if (schemaScope.CurrenreplacedemWriter.Top == 0 && _reader.TokenType != JsonToken.PropertyName)
                    {
                        JToken finishedItem = schemaScope.CurrenreplacedemWriter.Token;

                        // start next item with new writer
                        schemaScope.CurrenreplacedemWriter = null;

                        if (isInUniqueArray)
                        {
                            if (schemaScope.UniqueArrayItems.Contains(finishedItem, JToken.EqualityComparer))
                            {
                                RaiseError("Non-unique array item at index {0}.".FormatWith(CultureInfo.InvariantCulture, schemaScope.ArrayItemCount - 1), schemaScope.Schemas.First(s => s.UniqueItems));
                            }

                            schemaScope.UniqueArrayItems.Add(finishedItem);
                        }
                        else if (schemas.Any(s => s.Enum != null))
                        {
                            foreach (JsonSchemaModel schema in schemas)
                            {
                                if (schema.Enum != null)
                                {
                                    if (!schema.Enum.ContainsValue(finishedItem, JToken.EqualityComparer))
                                    {
                                        StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
                                        finishedItem.WriteTo(new JsonTextWriter(sw));

                                        RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, sw.ToString()), schema);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : JsonSchema.cs
with MIT License
from akaskela

public override string ToString()
        {
            StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);
            jsonWriter.Formatting = Formatting.Indented;

            WriteTo(jsonWriter);

            return writer.ToString();
        }

19 Source : TraceJsonReader.cs
with MIT License
from akaskela

public string GetDeserializedJsonMessage()
        {
            return _sw.ToString();
        }

19 Source : TraceJsonWriter.cs
with MIT License
from akaskela

public string GetSerializedJsonMessage()
        {
            return _sw.ToString();
        }

19 Source : JsonConvert.cs
with MIT License
from akaskela

private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
        {
            StringBuilder sb = new StringBuilder(256);
            StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = jsonSerializer.Formatting;

                jsonSerializer.Serialize(jsonWriter, value, type);
            }

            return sw.ToString();
        }

19 Source : AboutDialog.xaml.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

public static string ConvertToPlainText(string html)
        {
            HtmlDoreplacedent doc = new HtmlDoreplacedent();
            doc.LoadHtml(html);

            StringWriter sw = new StringWriter();
            ConvertTo(doc.DoreplacedentNode, sw);
            sw.Flush();
            return sw.ToString();
        }

19 Source : MiniDict.cs
with MIT License
from Alan-FGR

public override string ToString()
    {
        var sw = new StringWriter();
        sw.WriteLine($"MiniDict<{nameof(TKey)}, {nameof(TValue)}>({Count} items):");
        for (int i = 0; i < Count; i++)
            sw.WriteLine($"  {keys_[i]}: {data_[i]}");
        return sw.ToString();
    }

19 Source : Program.cs
with MIT License
from Alan-FGR

static void Main(string[] args)
    {
        String[] files = {"Registry", "ArchetypePool"};
        string path = "Archetypes";

        Console.WriteLine("C# VARIADIC GENERATOR. VALID TAGS:");
        foreach (var modeFunction in modeFunctions)
        {
            Console.WriteLine($"  {modeFunction.Key}");
            Console.WriteLine($"    Description: {modeFunction.Value.descr}");
        }

        foreach (string file in Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories))
        {
            var pathElements = file.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
            if (pathElements.Contains("obj"))
                continue;
            if (!files.Contains(Path.GetFileName(file)) && !files.Contains(Path.GetFileNameWithoutExtension(file)))
                continue;
            
            var code = File.ReadAllLines(file);
            var generatedCode = new StringWriter();

            Console.WriteLine($"PARSING FILE: {file}...");

            var regions = new List<(int qty, List<string> lines)>();

            List<string> currentRegion = null;

            foreach (string line in code)
            {
                if (line.ToLowerInvariant().Contains("#region variadic"))
                {
                    currentRegion = new List<string>();
                    regions.Add((int.Parse(line.Trim().Split(' ')[2]), currentRegion));
                    continue;
                }

                if (line.ToLowerInvariant().Contains("#endregion"))
                {
                    currentRegion = null;
                    continue;
                }

                currentRegion?.Add(line);
            }

            foreach (var tuple in regions)
            {
                curRegion = tuple.lines;
                for (int qti = 2; qti <= tuple.qty; qti++)
                {
                    curQty = qti;
                    for (var i = 0; i < tuple.lines.Count; i++)
                    {
                        string line = tuple.lines[i];

                        var trimmed = line.TrimStart(' ');
                        if (trimmed.Length >= 2)
                        {
                            string substring = trimmed.Substring(0, 2);
                            if (substring == "//")
                                continue;
                            if (substring == "/*")
                                Console.WriteLine($"MULTILINE COMMENT BLOCKS (DETECTED ON LINE {i}) NOT SUPPORTED." +
                                                  "YOU CAN USE THEM FOR COMMENTS AS USUAL BUT MAKE SURE THERE ARE NO TAGS IN THEM.");
                        }

                        if (line.ToLowerInvariant().Contains("genvariadic"))
                        {
                            var pars = line.Split("genvariadic")[1].Split(' ', StringSplitOptions.RemoveEmptyEntries);
                            Console.WriteLine(
                                $"found variadic on line {i}, {pars.Length} parameters: {string.Join(", ", pars)}");

                            if (pars.Length < 1)
                            {
                                Console.WriteLine("NO PARAMETERS!");
                                continue;
                            }

                            var mode = pars.First();
                            var options = pars.Skip(1).ToArray();

                            if (modeFunctions.TryGetValue(mode, out var value))
                            {
                                var str = value.Item2(options, i);
                                generatedCode.WriteLine(str);
                            }
                            else
                            {
                                string err = $"INVALID MODE: {mode}";
                                Console.WriteLine(err);
                                generatedCode.WriteLine(err);
                            }
                        }
                        else
                        {
                            generatedCode.WriteLine(line);
                        }
                    }
                }
            }

            Console.WriteLine($"PARSED FILE: {file}\n");


            var allcode = "";
            foreach (string line in code)
            {
                var trimmed = (line.Trim());
                if (trimmed.Length > 6)
                    if (trimmed.Substring(0, 5) == "using")
                        allcode += line+"\r\n";
            }

            allcode += $"public unsafe partial clreplaced {Path.GetFileNameWithoutExtension(file)} {{";

            allcode += generatedCode.ToString();

            allcode += "}";

            File.WriteAllText(Path.Combine(path, Path.GetFileNameWithoutExtension(file)+"GeneratedVariadic.cs"), allcode);

        }

        //Console.ReadKey();
    }

19 Source : ObjectExtensions.cs
with MIT License
from albyho

public static string ToXml(this object source, bool noneXsn = false)
        {
            string serializedObject = String.Empty;

            if (source != null)
            {

                var serializer = new XmlSerializer(source.GetType());

                if (noneXsn)
                {
                    var sb = new StringBuilder();

                    //去除xml version...
                    var settings = new XmlWriterSettings
                    {
                        Indent = true,
                        Encoding = Encoding.UTF8,
                        OmitXmlDeclaration = true, //Remove the <?xml version="1.0" encoding="utf-8"?>
                    };
                    var xmlWriter = XmlWriter.Create(sb, settings);

                    //去除默认命名空间
                    var xsn = new XmlSerializerNamespaces();
                    xsn.Add(String.Empty, String.Empty);

                    serializer.Serialize(xmlWriter, source, xsn);
                    return sb.ToString();
                }
                else
                {
                    using (var writer = new StringWriter())
                    {
                        serializer.Serialize(writer, source);
                        return writer.ToString();
                    }
                }
            }
            return serializedObject;
        }

19 Source : XmlUtility.cs
with MIT License
from AlenToma

public static string ToXml(this object o)
        {
            string xmlResult = "";
            ToXml(o, ref xmlResult);
            var xmlDoc = new System.Xml.XmlDoreplacedent();
            StringWriter sw = new StringWriter();
            xmlDoc.LoadXml(xmlResult);
            xmlDoc.Save(sw);
            return sw.ToString();
        }

19 Source : SerializeUtils.cs
with MIT License
from AlexanderPro

public static string Serialize<T>(T obj)
        {
            var serializer = new XmlSerializer(typeof(T));
            var stringWriter = new StringWriter();
            using (var xmlWriter = new XmlTextWriter(stringWriter))
            {
                xmlWriter.Formatting = Formatting.Indented;
                serializer.Serialize(xmlWriter, obj);
            }
            return stringWriter.ToString();
        }

19 Source : GMDCMarkdown.cs
with GNU General Public License v3.0
from alexdillon

public static string ToXaml(string markdown, MarkdownPipeline pipeline = null, Uri baseUri = null)
        {
            if (markdown == null)
            {
                throw new ArgumentNullException(nameof(markdown));
            }

            using (var writer = new StringWriter())
            {
                ToXaml(markdown, writer, pipeline, baseUri);
                return writer.ToString();
            }
        }

19 Source : IdentityGeneratorType.cs
with GNU General Public License v3.0
from alexgracianoarj

public static string Serialize<T>(this T toSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            
            var settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;

            using (StringWriter stream = new StringWriter())
                using (var writer = XmlWriter.Create(stream, settings))
                {
                    xmlSerializer.Serialize(writer, toSerialize, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
                    return stream.ToString();
                }
        }

19 Source : Computer.cs
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 : ViewRenderService.cs
with MIT License
from alexyz79

public async Task<string> RenderToStringAsync(string viewName, object model)
        {
            var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
 
            using (var sw = new StringWriter())
            {
                var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);
 
                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"{viewName} does not match any available view");
                }
 
                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };
 
                var viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    sw,
                    new HtmlHelperOptions()
                );
 
                viewContext.ViewData["Hostname"] = Program.Hostname;
                viewContext.ViewData["Port"] = Program.Port;
                await viewResult.View.RenderAsync(viewContext);
                return sw.ToString();
            }
        }

19 Source : Document.cs
with MIT License
from aliencube

private string Render(OpenApiSpecVersion version, OpenApiFormat format)
        {
            using (var sw = new StringWriter())
            {
                this.OpenApiDoreplacedent.Serialise(sw, version, format);

                return sw.ToString();
            }
        }

19 Source : MessagePackSerializer.Json.cs
with Apache License 2.0
from allenai

public static string SerializeToJson<T>(T obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
        {
            var writer = new StringWriter();
            SerializeToJson(writer, obj, options, cancellationToken);
            return writer.ToString();
        }

19 Source : MessagePackSerializer.Json.cs
with Apache License 2.0
from allenai

public static string ConvertToJson(in ReadOnlySequence<byte> bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
        {
            var jsonWriter = new StringWriter();
            var reader = new MessagePackReader(bytes)
            {
                CancellationToken = cancellationToken,
            };
            ConvertToJson(ref reader, jsonWriter, options);
            return jsonWriter.ToString();
        }

See More Examples