System.IO.StringWriter.GetStringBuilder()

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

213 Examples 7

19 Source : Amf3Writer.cs
with MIT License
from a1q123456

private string XmlToString(XmlDoreplacedent xml)
        {
            using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
                xml.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();
                return stringWriter.GetStringBuilder().ToString();
            }
        }

19 Source : Amf0Writer.cs
with MIT License
from a1q123456

public void WriteBytes(XmlDoreplacedent xml, SerializationContext context)
        {
            string content = null;
            using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
                xml.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();
                content = stringWriter.GetStringBuilder().ToString();
            }

            context.Buffer.WriteToBuffer((byte)Amf0Type.XmlDoreplacedent);
            WriteStringBytesImpl(content, context, out _, forceLongString: true);
        }

19 Source : ArticleViewModel.cs
with MIT License
from Adoxio

private static IHtmlString ExtractContent(string content)
		{
			var html = new HtmlDoreplacedent();
			html.LoadHtml(content);

			var table = html.DoreplacedentNode.SelectSingleNode("//body/table");

			if (table == null)
			{
				return null;
			}

			using (var output = new StringWriter())
			{
				table.WriteTo(output);

				return new HtmlString(output.GetStringBuilder().ToString());
			}
		}

19 Source : EpubBuilder.cs
with GNU General Public License v3.0
from Aeroblast

public void Save(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create))
            using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Create))
            {
                {
                    var entry = zip.CreateEntry("mimetype", CompressionLevel.NoCompression);
                    using (StreamWriter writer = new StreamWriter(entry.Open()))
                        writer.Write("application/epub+zip");
                }
                ZipWriteAllText(zip, "META-INF/container.xml", container);
                for (int i = 0; i < xhtml_names.Count; i++)
                {
                    string p = "OEBPS/Text/" + xhtml_names[i];
                    string ss;
                    var xmlSettings = new XmlWriterSettings { Indent = true, NewLineChars = "\n" };
                    using (var stringWriter = new StringWriter())
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter, xmlSettings))
                    {
                        xhtmls[i].WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        ss = stringWriter.GetStringBuilder().ToString();
                    }
                    ss = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n"
                    + ss.Substring(ss.IndexOf("<html"));
                    ZipWriteAllText(zip, p, ss);
                }
                for (int i = 0; i < css_names.Count; i++)
                {
                    ZipWriteAllText(zip, "OEBPS/Styles/" + css_names[i], csss[i]);
                }
                for (int i = 0; i < img_names.Count; i++)
                {
                    ZipWriteAllBytes(zip, "OEBPS/Images/" + img_names[i], imgs[i]);
                }
                for (int i = 0; i < font_names.Count; i++)
                {
                    ZipWriteAllBytes(zip, "OEBPS/Fonts/" + font_names[i], fonts[i]);
                }
                ZipWriteAllText(zip, "OEBPS/toc.ncx", ncx);
                ZipWriteAllText(zip, "OEBPS/nav.xhtml", nav);
                ZipWriteAllText(zip, "OEBPS/content.opf", opf);
            }
            Log.log("Saved: " + path);
        }

19 Source : ConfigurationBase.cs
with GNU General Public License v3.0
from aiportal

public void SaveConfiguration(string filename)
		{
			try
			{
				Dictionary<string, object> dic = this.GetConfigurations();
				XmlDoreplacedent doc = new XmlDoreplacedent();
				doc.LoadXml(string.Format(@"<{0}></{0}>", ROOT_ELEMENT));
				foreach (string key in dic.Keys)
				{
					var node = doc.CreateElement(key);
					node.InnerText = DataConverter.Serilize(dic[key]);
					doc.DoreplacedentElement.AppendChild(node);
				}

				string xml;
				using (StringWriter sw = new StringWriter())
				using (XmlTextWriter tw = new XmlTextWriter(sw))
				{
					doc.WriteTo(tw);
					xml = sw.GetStringBuilder().ToString();
				}

				byte[] bs = Convert.FromBase64String(Encryption.Encrypt(xml));
				File.WriteAllBytes(filename, bs);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 Source : ConfigurationBase.cs
with GNU General Public License v3.0
from aiportal

public void SaveConfiguration(string filename)
		{
			try
			{
				Dictionary<string, object> dic = this.GetConfigurations();
				XmlDoreplacedent doc = new XmlDoreplacedent();
				doc.LoadXml(string.Format(@"<{0}></{0}>", ROOT_ELEMENT));
				foreach (string key in dic.Keys)
				{
					var node = doc.CreateElement(key);
					node.InnerText = DataConverter.Serialize(dic[key]);
					doc.DoreplacedentElement.AppendChild(node);
				}

				string xml;
				using (StringWriter sw = new StringWriter())
				using (XmlTextWriter tw = new XmlTextWriter(sw))
				{
					doc.WriteTo(tw);
					xml = sw.GetStringBuilder().ToString();
				}

				byte[] bs = Convert.FromBase64String(Encryption.Encrypt(xml));
				File.WriteAllBytes(filename, bs);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 Source : __BaseController.cs
with MIT License
from akasarto

protected string RenderViewToString(string viewName, string masterName = null, object model = null)
		{
			ViewData.Model = model;

			using (var sw = new StringWriter())
			{
				var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, masterName);
				var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

				viewResult.View.Render(viewContext, sw);
				viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);

				return sw.GetStringBuilder().ToString();
			}
		}

19 Source : __BaseController.cs
with MIT License
from akasarto

protected string RenderPartialViewToString(string viewName, object model = null)
		{
			ViewData.Model = model;

			using (var sw = new StringWriter())
			{
				var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
				var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

				viewResult.View.Render(viewContext, sw);
				viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);

				return sw.GetStringBuilder().ToString();
			}
		}

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void WriteStructure(Type type, object? obj, string? explicitTypeName = null)
        {
            string typeName = explicitTypeName ?? type.Name;

            string[] namespaces = type.Namespace.Split('.');

            if (type.IsreplacedignableFrom(shaderType))
            {
                namespaces = namespaces.Concat(new[] { typeName }).ToArray();
            }

            for (int i = 0; i < namespaces.Length - 1; i++)
            {
                writer.Write($"namespace {namespaces[i]} {{ ");
            }

            writer.WriteLine($"namespace {namespaces[namespaces.Length - 1]}");
            writer.WriteLine("{");
            writer.Indent++;

            if (!type.IsreplacedignableFrom(shaderType))
            {
                if (type.IsEnum)
                {
                    writer.WriteLine($"enum clreplaced {typeName}");
                }
                else if (type.IsInterface)
                {
                    writer.WriteLine($"interface {typeName}");
                }
                else
                {
                    writer.Write($"struct {typeName}");

                    bool trim = false;

                    if (type.BaseType != null && type.BaseType != typeof(object) && type.BaseType != typeof(ValueType))
                    {
                        writer.Write($" : {HlslKnownTypes.GetMappedName(type.BaseType)}, ");
                        trim = true;
                    }

                    // NOTE: Types might no expose every interface method.
                    //Type[] interfaces = type.GetInterfaces();

                    //if (interfaces.Length > 0)
                    //{
                    //    foreach (Type interfaceType in interfaces)
                    //    {
                    //        writer.Write(interfaceType.Name + ", ");
                    //    }

                    //    trim = true;
                    //}

                    if (trim)
                    {
                        stringWriter.GetStringBuilder().Length -= 2;
                    }

                    writer.WriteLine();
                }

                writer.WriteLine("{");
                writer.Indent++;
            }

            BindingFlags fieldBindingFlags = GetBindingFlagsForType(type) | BindingFlags.DeclaredOnly;

            if (type.IsEnum)
            {
                fieldBindingFlags &= ~BindingFlags.Instance;
            }

            var fieldAndPropertyInfos = type.GetMembersInOrder(fieldBindingFlags).Where(m => m is FieldInfo || m is PropertyInfo);
            var methodInfos = type.GetMembersInTypeHierarchyInOrder(GetBindingFlagsForType(type)).Where(m => m is MethodInfo);
            var memberInfos = type.IsreplacedignableFrom(shaderType) ? methodInfos : fieldAndPropertyInfos.Concat(methodInfos);

            foreach (MemberInfo memberInfo in memberInfos)
            {
                Type? memberType = memberInfo.GetMemberType(obj);
                object? memberValue = memberInfo.GetMemberValue(obj);

                if (memberInfo is MethodInfo methodInfo && CanWriteMethod(methodInfo))
                {
                    WriteMethod(methodInfo);
                }
                else if (memberValue is Delegate memberDelegate)
                {
                    WriteMethod(memberDelegate.Method, false, memberInfo.Name);
                }
                else if (memberType != null)
                {
                    if (type.IsEnum)
                    {
                        writer.Write(memberInfo.Name);
                        writer.WriteLine(",");
                    }
                    else
                    {
                        WriteStructureField(memberInfo, memberType);
                    }
                }
            }

            stringWriter.GetStringBuilder().TrimEnd().AppendLine();

            if (!type.IsreplacedignableFrom(shaderType))
            {
                writer.Indent--;
                writer.WriteLine("};");
            }

            writer.Indent--;

            for (int i = 0; i < namespaces.Length - 1; i++)
            {
                writer.Write("}");
            }

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

            if (type.IsEnum) return;

            foreach (MemberInfo memberInfo in memberInfos.Where(m => m.IsStatic()))
            {
                Type? memberType = memberInfo.GetMemberType(obj);

                if (memberType != null)
                {
                    WriteStaticStructureField(memberInfo, memberType);
                }
            }
        }

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void WriteAttribute(Attribute attribute)
        {
            Type attributeType = attribute.GetType();

            if (HlslKnownTypes.ContainsKey(attributeType))
            {
                writer.Write("[");
                writer.Write(HlslKnownTypes.GetMappedName(attributeType));

                var fieldAndPropertyInfos = attributeType.GetMembersInOrder(GetBindingFlagsForType(attributeType) | BindingFlags.DeclaredOnly).Where(m => m is FieldInfo || m is PropertyInfo);
                IEnumerable<object> attributeMemberValues = fieldAndPropertyInfos.Where(m => m.GetMemberValue(attribute) != null).Select(m => m.GetMemberValue(attribute))!;

                if (attributeMemberValues.Count() > 0)
                {
                    writer.Write("(");

                    foreach (object memberValue in attributeMemberValues)
                    {
                        string valueString = memberValue is string ? $"\"{memberValue}\"" : memberValue.ToString();

                        writer.Write(valueString);
                        writer.Write(", ");
                    }

                    stringWriter.GetStringBuilder().Length -= 2;

                    writer.Write(")");
                }

                writer.WriteLine("]");
            }
        }

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void WriteTopLevelStructure()
        {
            var allMemberInfos = shaderType.GetMembersInTypeHierarchyInOrder(GetBindingFlagsForType(shaderType));
            var memberInfos = allMemberInfos.Where(m => !(m is MethodInfo));

            foreach (ShaderTypeDefinition type in collectedTypes)
            {
                WriteStructure(type.Type, type.Instance);
            }

            foreach (MemberInfo memberInfo in memberInfos)
            {
                Type? memberType = memberInfo.GetMemberType(shader);
                ShaderResourceAttribute? shaderResourceAttribute = memberInfo.GetShaderResourceAttribute(memberType);

                if (memberType != null && shaderResourceAttribute != null)
                {
                    WriteResource(memberInfo.Name, memberType, shaderResourceAttribute);
                }
            }

            foreach (Type type in shaderType.GetBaseTypes().Reverse())
            {
                WriteStructure(type, shader);
            }

            foreach (MemberInfo memberInfo in shaderType.GetMembersInOrder(GetBindingFlagsForType(shaderType)))
            {
                Type? memberType = memberInfo.GetMemberType(shader);
                object? memberValue = memberInfo.GetMemberValue(shader);

                if (memberInfo is MethodInfo methodInfo && CanWriteMethod(methodInfo))
                {
                    WriteMethod(methodInfo, true);
                }
                else if (memberValue is Delegate memberDelegate)
                {
                    WriteMethod(memberDelegate.Method, true, memberInfo.Name);
                }
            }

            if (action != null && !action.Method.IsDefined(typeof(ShaderMemberAttribute)))
            {
                WriteMethod(action.Method, true, AnonymousMethodEntryPointName, EntryPointAttributes);
            }

            stringWriter.GetStringBuilder().TrimEnd().AppendLine();
        }

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void WriteStaticResource(string memberName, Type memberType, IEnumerable<string>? resourceNames = null)
        {
            if (resourceNames is null)
            {
                List<string> generatedMemberNames = new List<string>();

                foreach (ResourceDefinition resourceDefinition in collectedTypes.First(d => d.Type == memberType).ResourceDefinitions)
                {
                    string generatedMemberName = $"__Generated__{bindingTracker.StaticResource++}__";
                    generatedMemberNames.Add(generatedMemberName);

                    WriteResource(generatedMemberName, resourceDefinition.MemberType, resourceDefinition.ShaderResourceAttribute);
                }

                resourceNames = generatedMemberNames;
            }

            writer.Write($"static {HlslKnownTypes.GetMappedName(memberType)} {memberName}");

            if (resourceNames.Count() > 0)
            {
                writer.Write(" = { ");

                foreach (string resourceName in resourceNames)
                {
                    writer.Write(resourceName);
                    writer.Write(", ");
                }

                stringWriter.GetStringBuilder().Length -= 2;

                writer.Write(" }");
            }

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

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void WriteParameters(MethodInfo methodInfo)
        {
            writer.Write("(");

            ParameterInfo[] parameterInfos = methodInfo.GetParameters();

            if (parameterInfos.Length > 0)
            {
                foreach (ParameterInfo parameterInfo in parameterInfos)
                {
                    if (parameterInfo.ParameterType.IsByRef)
                    {
                        string refString = parameterInfo.IsIn ? "in" : parameterInfo.IsOut ? "out" : "inout";
                        writer.Write(refString);
                        writer.Write(" ");
                    }

                    writer.Write($"{HlslKnownTypes.GetMappedName(parameterInfo.ParameterType)} {parameterInfo.Name}");

                    if (parameterInfo.GetCustomAttributes<ShaderSemanticAttribute>().FirstOrDefault(a => HlslKnownTypes.ContainsKey(a.GetType())) is ShaderSemanticAttribute parameterAttribute)
                    {
                        writer.Write(GetHlslSemantic(parameterAttribute));
                    }

                    writer.Write(", ");
                }

                stringWriter.GetStringBuilder().Length -= 2;
            }

            writer.Write(")");
        }

19 Source : ReusableStringWriter.cs
with Apache License 2.0
from apache

public void Reset(int maxCapacity, int defaultSize)
		{
			// Reset working string buffer
			StringBuilder sb = this.GetStringBuilder();

			sb.Length = 0;
			
			// Check if over max size
			if (sb.Capacity > maxCapacity) 
			{
				sb.Capacity = defaultSize;
			} 
		}

19 Source : Renderer.cs
with Apache License 2.0
from authlete

public async Task<string> Render(string viewName, object model)
        {
            _controller.ViewData.Model = model;

            var result = CreateViewEngineResult(viewName);

            using (var writer = new StringWriter())
            {
                // Prepare a context for rendering.
                var context = CreateViewContext(result, writer);

                // Render the view.
                await result.View.RenderAsync(context);

                // Convert the rendering result to a string.
                return writer.GetStringBuilder().ToString();
            }
        }

19 Source : WriteLine_Should.cs
with Apache License 2.0
from AutomateThePlanet

[Test]
        public void PrintFormattedString_When_FormatAndTwoArgumentAreSpecified()
        {
            // Arrange
            var fixture = new Fixture();
            var expectedText1 = fixture.Create<string>();
            var expectedText2 = fixture.Create<string>();
            var originalConsoleOut = System.Console.Out;
            string formattedStringToBePrinted;
            using (var writer = new StringWriter())
            {
                System.Console.SetOut(writer);

                // Act
                var consoleProvider = new ConsoleProvider();
                consoleProvider.WriteLine("{0}{1}", expectedText1, expectedText2);

                writer.Flush();

                formattedStringToBePrinted = writer.GetStringBuilder().ToString();
            }

            // replacedert
            replacedert.That(formattedStringToBePrinted, Is.EqualTo(string.Concat(expectedText1, expectedText2, "\r\n")));

            // Clean-up
            System.Console.SetOut(originalConsoleOut);
        }

19 Source : Write_Should.cs
with Apache License 2.0
from AutomateThePlanet

[Test]
        public void PrintFormattedString_When_OneArgumentIsSpecified()
        {
            // Arrange
            var originalConsoleOut = System.Console.Out;
            string formattedStringToBePrinted;
            var fixture = new Fixture();
            var expectedText = fixture.Create<string>();
            using (var writer = new StringWriter())
            {
                System.Console.SetOut(writer);

                // Act
                var consoleProvider = new ConsoleProvider();
                consoleProvider.Write(expectedText);

                writer.Flush();

                formattedStringToBePrinted = writer.GetStringBuilder().ToString();
            }

            // replacedert
            replacedert.That(formattedStringToBePrinted, Is.EqualTo(expectedText));

            // Clean-up
            System.Console.SetOut(originalConsoleOut);
        }

19 Source : Write_Should.cs
with Apache License 2.0
from AutomateThePlanet

[Test]
        public void PrintFormattedString_When_FormatAndOneArgumentAreSpecified()
        {
            // Arrange
            var fixture = new Fixture();
            var expectedText = fixture.Create<string>();
            var originalConsoleOut = System.Console.Out;
            string formattedStringToBePrinted;
            using (var writer = new StringWriter())
            {
                System.Console.SetOut(writer);

                // Act
                var consoleProvider = new ConsoleProvider();
                consoleProvider.Write("{0}", expectedText);

                writer.Flush();

                formattedStringToBePrinted = writer.GetStringBuilder().ToString();
            }

            // replacedert
            replacedert.That(formattedStringToBePrinted, Is.EqualTo(expectedText));

            // Clean-up
            System.Console.SetOut(originalConsoleOut);
        }

19 Source : Write_Should.cs
with Apache License 2.0
from AutomateThePlanet

[Test]
        public void PrintFormattedString_When_FormatAndTwoArgumentAreSpecified()
        {
            // Arrange
            var fixture = new Fixture();
            var expectedText1 = fixture.Create<string>();
            var expectedText2 = fixture.Create<string>();
            var originalConsoleOut = System.Console.Out;
            string formattedStringToBePrinted;
            using (var writer = new StringWriter())
            {
                System.Console.SetOut(writer);

                // Act
                var consoleProvider = new ConsoleProvider();
                consoleProvider.Write("{0}{1}", expectedText1, expectedText2);

                writer.Flush();

                formattedStringToBePrinted = writer.GetStringBuilder().ToString();
            }

            // replacedert
            replacedert.That(formattedStringToBePrinted, Is.EqualTo(string.Concat(expectedText1, expectedText2)));

            // Clean-up
            System.Console.SetOut(originalConsoleOut);
        }

19 Source : WriteLine_Should.cs
with Apache License 2.0
from AutomateThePlanet

[Test]
        public void PrintFormattedString_When_OneArgumentIsSpecified()
        {
            // Arrange
            var fixture = new Fixture();
            var expectedText = fixture.Create<string>();
            var originalConsoleOut = System.Console.Out; // preserve the original stream
            string formattedStringToBePrinted;
            using (var writer = new StringWriter())
            {
                System.Console.SetOut(writer);

                // Act
                var consoleProvider = new ConsoleProvider();
                consoleProvider.WriteLine(expectedText);

                writer.Flush();

                formattedStringToBePrinted = writer.GetStringBuilder().ToString();
            }

            // replacedert
            replacedert.That(formattedStringToBePrinted, Is.EqualTo(string.Concat(expectedText, "\r\n")));

            // Clean-up
            System.Console.SetOut(originalConsoleOut);
        }

19 Source : WriteLine_Should.cs
with Apache License 2.0
from AutomateThePlanet

[Test]
        public void PrintFormattedString_When_FormatAndOneArgumentAreSpecified()
        {
            // Arrange
            var fixture = new Fixture();
            var expectedText = fixture.Create<string>();
            var originalConsoleOut = System.Console.Out;
            string formattedStringToBePrinted;
            using (var writer = new StringWriter())
            {
                System.Console.SetOut(writer);

                // Act
                var consoleProvider = new ConsoleProvider();
                consoleProvider.WriteLine("{0}", expectedText);

                writer.Flush();

                formattedStringToBePrinted = writer.GetStringBuilder().ToString();
            }

            // replacedert
            replacedert.That(formattedStringToBePrinted, Is.EqualTo(string.Concat(expectedText, "\r\n")));

            // Clean-up
            System.Console.SetOut(originalConsoleOut);
        }

19 Source : Json.cs
with MIT License
from Azure99

public static string Serialize(object obj, Type type)
        {
            using (StringWriter writer = new StringWriter(new StringBuilder()))
            {
                Serializer.Serialize(writer, obj, type);
                return writer.GetStringBuilder().ToString();
            }
        }

19 Source : AstStatement.cs
with GNU General Public License v3.0
from CheezLang

public override string ToString()
        {
            var sb = new StringWriter();
            new RawAstPrinter(sb).PrintStatement(this);
            return sb.GetStringBuilder().ToString();
        }

19 Source : FoldersManagerForm.cs
with GNU General Public License v3.0
from ClusterM

private string TreeToXml()
        {
            var root = treeView.Nodes[0];
            var xml = new XmlDoreplacedent();
            var treeNode = xml.CreateElement("Tree");
            xml.AppendChild(treeNode);
            NodeToXml(xml, treeNode, root);
            using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = new XmlTextWriter(stringWriter))
            {
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlTextWriter.WriteStartDoreplacedent();
                xml.WriteTo(xmlTextWriter);
                xmlTextWriter.WriteEndDoreplacedent();
                xmlTextWriter.Flush();
                return stringWriter.GetStringBuilder().ToString();
            }
        }

19 Source : System_IO_StringWriter_Binding.cs
with MIT License
from CragonGame

static StackObject* GetStringBuilder_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* ptr_of_this_method;
            StackObject* __ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.StringWriter instance_of_this_method = (System.IO.StringWriter)typeof(System.IO.StringWriter).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetStringBuilder();

            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
        }

19 Source : ViewRenderer.cs
with Apache License 2.0
from crazyants

public async Task<string> RenderViewreplacedtring<TModel>(string viewName, TModel model)
        {

            var viewData = new ViewDataDictionary<TModel>(
                        metadataProvider: new EmptyModelMetadataProvider(),
                        modelState: new ModelStateDictionary())
            {
                Model = model
            };

            var actionContext = actionAccessor.ActionContext;

            var tempData = new TempDataDictionary(actionContext.HttpContext, tempDataProvider);

            using (StringWriter output = new StringWriter())
            {

                ViewEngineResult viewResult = viewEngine.FindView(actionContext, viewName, true);

                ViewContext viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewData,
                    tempData,
                    output,
                    new HtmlHelperOptions()
                );

                await viewResult.View.RenderAsync(viewContext);

                return output.GetStringBuilder().ToString();
            }
        }

19 Source : ContentSecurityPolicyInlineElement.cs
with Apache License 2.0
from crazyants

public void Dispose()
        {
            if (_inlineExecution == ContentSecurityPolicyInlineExecution.Hash)
            {
                StringBuilder elementInnerHtmlBuilder = ((StringWriter)_viewContext.Writer).GetStringBuilder();
                string elementInnerHtml = elementInnerHtmlBuilder.ToString().Replace("\r\n", "\n");
                byte[] elementHashBytes = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(elementInnerHtml));
                string elementHash = Convert.ToBase64String(elementHashBytes);
                ((StringBuilder)_viewContext.HttpContext.Items[_hashListBuilderContextKeys[_elementTag.TagName]]).AppendFormat(_sha256SourceFormat, elementHash);

                _viewContext.Writer.Dispose();
                _viewContext.Writer = _viewContextWriter;
                _viewContext.Writer.Write(elementInnerHtml);
            }

            _elementTag.TagRenderMode = TagRenderMode.EndTag;
            _elementTag.WriteTo(_viewContext.Writer, HtmlEncoder.Default);
        }

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

public static string AskTicket(string user, string domain, string hash, KERB_ETYPE encType, string dc)
        {
            LUID luid = new LUID();
            string ticketoutput = "";
            var originalConsoleOut = Console.Out;
            using (var writer = new StringWriter())
            {
                Console.SetOut(writer);
                Ask.TGT(user, domain, hash, encType, null, true, dc, luid, false);
                writer.Flush();
                ticketoutput = writer.GetStringBuilder().ToString();
            }
            Console.SetOut(originalConsoleOut);
            return ticketoutput;
        }

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

public static string ImportTicket(string ticket)
        {
            LUID luid = new LUID();
            string ticketoutput = "";
            var originalConsoleOut = Console.Out;
            using (var writer = new StringWriter())
            {
                Console.SetOut(writer);
                if (Rubeus.Helpers.IsBase64String(ticket))
                {
                    byte[] kirbiBytes = Convert.FromBase64String(ticket);
                    Rubeus.LSA.ImportTicket(kirbiBytes, luid);
                }
                else if (File.Exists(ticket))
                {
                    byte[] kirbiBytes = File.ReadAllBytes(ticket);
                    Rubeus.LSA.ImportTicket(kirbiBytes, luid);
                }
                writer.Flush();
                ticketoutput = writer.GetStringBuilder().ToString();
            }
            Console.SetOut(originalConsoleOut);
            return ticketoutput;
        }

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

public static void ParseDpapi(StringBuilder sb, List<byte[]> Dpapikeys, List<byte[]> machineMasterKeys, List<byte[]> userMasterKeys, string credDirs = null, string vaultDirs = null, string certDirs = null)
        {
            sb.AppendLine("  [*] SYSTEM master key cache");
            Dictionary<string, string> mappings = DecryptSystemMasterKeys(sb, Dpapikeys, machineMasterKeys, userMasterKeys);
            foreach (KeyValuePair<string, string> kvp in mappings)
            {
                sb.AppendLine(String.Format("{0}:{1}", kvp.Key, kvp.Value));
            }
            var originalConsoleOut = Console.Out;
            using (var writer = new StringWriter())
            {
                Console.SetOut(writer);
                Console.WriteLine("  [*] Dpapi cred blobs");
                var credFiles = Directory.EnumerateFiles(credDirs, "*.*", SearchOption.AllDirectories);
                if (credDirs != null && credFiles.GetEnumerator().MoveNext())
                {
                    Triage.TriageCredFolder(credDirs, mappings);
                }

                var vaultFiles = Directory.EnumerateFiles(vaultDirs, "*.*", SearchOption.AllDirectories);
                if (vaultDirs != null && vaultFiles.GetEnumerator().MoveNext())
                {
                    foreach (var dir in Directory.GetDirectories(vaultDirs))
                    {
                        Triage.TriageVaultFolder(dir, mappings);
                    }
                }

                var certFiles = Directory.EnumerateFiles(certDirs, "*.*", SearchOption.AllDirectories);
                if (certDirs != null && certFiles.GetEnumerator().MoveNext())
                {
                    Triage.TriageCertFolder(certDirs, mappings);
                }
                writer.Flush();
                sb.AppendLine(writer.GetStringBuilder().ToString());
            }
            Console.SetOut(originalConsoleOut);
        }

19 Source : GraphToDotConverterTest.cs
with MIT License
from cyberark

[Test]
		public void ConvertSimpleGraphWith2VerticesAndEdge()
		{
			var graph = new Graph<int>();
			graph.AddVertex(0);
			graph.AddVertex(1);
			graph.AddEdge(new Edge<int>(0, 1));

			var writer = new StringWriter();
			new GraphToDotConverter().Convert(writer, graph, new AttributesProvider());
			var result = writer.GetStringBuilder().ToString().Trim();

			Stringreplacedert.Contains("0 -> 1", result, "output appears to not contain the edge");
		}

19 Source : DotAutomationFactoryRunner.cs
with MIT License
from cyberark

public TextReader RunDot(Action<TextWriter> writeGraph)
        {
            var command = string.Format(
                "\"{0}\"", 
                Path.Combine(this.DotExecutablePath, this.DotExecutable));

            dynamic cmd = AutomationFactory.CreateObject("WScript.Shell");
            dynamic exec = cmd.Exec(command);

            // Note: implementation with custom TextWriter that called Write(char) 
            // on exec.StdIn did not work (couldn't find a cause for that).
            var writer = new StringWriter();
            writeGraph(writer);
            exec.StdIn.Write(writer.GetStringBuilder().ToString());
            exec.StdIn.Close();

            return new StdOutReader(exec.StdOut);
        }

19 Source : DotRunnerLogDecorator.cs
with MIT License
from cyberark

public TextReader RunDot(Action<TextWriter> writeGraph)
        {
            using (var writer = new StringWriter()) 
            {
                writeGraph(writer);
                string graph = writer.GetStringBuilder().ToString();
                var graphFile = Path.Combine(Path.GetTempPath(), this.filename + ".dot");
                File.WriteAllText(graphFile, graph);

                // now we read the file and write it to the real process input.
                using (var reader = this.runner.RunDot(w => w.Write(graph)))
                {
                    // we read all output, save it into another file, and return it as a memory stream
                    var text = reader.ReadToEnd();

                    var layoutFile = Path.Combine(Path.GetTempPath(), this.filename + ".layout.dot");
                    File.WriteAllBytes(layoutFile, Encoding.UTF8.GetBytes(text));
                    return new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(text)));
                }
            }
        }

19 Source : PList.cs
with GNU Lesser General Public License v3.0
from Egomotion

public bool Save(string pathToSaveFile, bool overwrite = false)
        {
            if (!IsValidPath(pathToSaveFile))
            {
                Debug.LogError("EgoXproject: Invalid Save Path: " + pathToSaveFile);
                return false;
            }

            if (!overwrite)
            {
                if (_path != pathToSaveFile && File.Exists(pathToSaveFile))
                {
                    Debug.LogError("EgoXproject: File exists: " + pathToSaveFile);
                    return false;
                }
            }

            XDoreplacedent doc = new XDoreplacedent(_decl);
            bool dtd = false;

            if (_loaded)
            {
                if (_usedDocType != null)
                {
                    doc.AddFirst(_usedDocType);
                    dtd = true;
                }
            }
            else
            {
                doc.AddFirst(_docType);
                dtd = true;
            }

            XElement plist = new XElement("plist");
            plist.SetAttributeValue("version", _version);
            plist.Add(_dict.Xml());
            doc.Add(plist);

            var stringWriter = new Utf8StringWriter();
            doc.Save(stringWriter);
            var content = stringWriter.GetStringBuilder().ToString();
            //http://stackoverflow.com/questions/10303315/convert-stringwriter-to-string
            string[] separator = { System.Environment.NewLine };
            string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            //Remove the spurious [] that get added to DOCTYPE. Grrr.
            if (dtd)
            {
                for (int ii = 0; ii < lines.Length; ii++)
                {
                    var line = lines[ii];

                    if (line.Contains("<!DOCTYPE") && line.Contains("[]"))
                    {
                        lines[ii] = line.Replace("[]", "");
                        break;
                    }
                }
            }

            File.WriteAllLines(pathToSaveFile, lines);
            //TODO this is a crap check.
            bool bSaved = File.Exists(pathToSaveFile);

            if (bSaved)
            {
                _path = pathToSaveFile;
            }

            return bSaved;
        }

19 Source : XmlSerializer.cs
with Apache License 2.0
from ElmahCore

public static string Serialize(object obj)
        {
            var sw = new StringWriter();
            Serialize(obj, sw);
            return sw.GetStringBuilder().ToString();
        }

19 Source : ControllerExtensions.cs
with MIT License
from eznew-net

public static async Task<string> RenderViewContentAsync(this Controller controller, string viewName, object model, string masterName, bool partialView = false)
        {
            controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var actionContext = new ActionContext(controller.HttpContext, controller.RouteData, new ActionDescriptor());
                if (partialView)
                {
                    PartialViewResult partialViewResult = new PartialViewResult()
                    {
                        ViewData = controller.ViewData,
                        TempData = controller.TempData,
                        ViewName = viewName
                    };
                    var partialViewExecutor = controller.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<PartialViewResult>>() as PartialViewResultExecutor;
                    var pView = partialViewExecutor.FindView(actionContext, partialViewResult).View;
                    var pviewContext = new ViewContext(actionContext, pView, partialViewResult.ViewData, partialViewResult.TempData, sw, new HtmlHelperOptions());
                    await pView.RenderAsync(pviewContext).ConfigureAwait(false);
                    return sw.GetStringBuilder().ToString();
                }

                ViewResult viewResult = new ViewResult()
                {
                    ViewData = controller.ViewData,
                    TempData = controller.TempData,
                    ViewName = viewName
                };
                var viewExecutor = controller.HttpContext.RequestServices.GetRequiredService<ViewResultExecutor>();
                var view = viewExecutor.FindView(actionContext, viewResult).View;
                var viewContext = new ViewContext(actionContext, view, viewResult.ViewData, viewResult.TempData, sw, new HtmlHelperOptions());
                await view.RenderAsync(viewContext).ConfigureAwait(false);
                return sw.GetStringBuilder().ToString();
            }
        }

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

private void PerformFlush()
    {
        // *** If local cache was not modified, exit ***
        if (!m_CacheModified) return;
        m_CacheModified = false;

        // *** Copy content of original iniString to temporary string, replace modified values ***
        StringWriter sw = new StringWriter();

        try
        {
            Dictionary<string, string> CurrentSection = null;
            Dictionary<string, string> CurrentSection2 = null;
            StringReader sr = null;
            try
            {
                // *** Open the original file ***
                sr = new StringReader(m_iniString);

                // *** Read the file original content, replace changes with local cache values ***
                string s;
                string SectionName;
                string Key = null;
                string Value = null;
                bool Unmodified;
                bool Reading = true;

                bool Deleted = false;
                string Key2 = null;
                string Value2 = null;

                StringBuilder sb_temp;

                while (Reading)
                {
                    s = sr.ReadLine();
                    Reading = (s != null);

                    // *** Check for end of iniString ***
                    if (Reading)
                    {
                        Unmodified = true;
                        s = s.Trim();
                        SectionName = ParseSectionName(s);
                    }
                    else
                    {
                        Unmodified = false;
                        SectionName = null;
                    }

                    // *** Check for section names ***
                    if ((SectionName != null) || (!Reading))
                    {
                        if (CurrentSection != null)
                        {
                            // *** Write all remaining modified values before leaving a section ****
                            if (CurrentSection.Count > 0)
                            {
                                // *** Optional: All blank lines before new values and sections are removed ****
                                sb_temp = sw.GetStringBuilder();
                                while ((sb_temp[sb_temp.Length - 1] == '\n') || (sb_temp[sb_temp.Length - 1] == '\r'))
                                {
                                    sb_temp.Length = sb_temp.Length - 1;
                                }
                                sw.WriteLine();

                                foreach (string fkey in CurrentSection.Keys)
                                {
                                    if (CurrentSection.TryGetValue(fkey, out Value))
                                    {
                                        sw.Write(fkey);
                                        sw.Write('=');
                                        sw.WriteLine(Value);
                                    }
                                }
                                sw.WriteLine();
                                CurrentSection.Clear();
                            }
                        }

                        if (Reading)
                        {
                            // *** Check if current section is in local modified cache ***
                            if (!m_Modified.TryGetValue(SectionName, out CurrentSection))
                            {
                                CurrentSection = null;
                            }
                        }
                    }
                    else if (CurrentSection != null)
                    {
                        // *** Check for key+value pair ***
                        if (ParseKeyValuePair(s, ref Key, ref Value))
                        {
                            if (CurrentSection.TryGetValue(Key, out Value))
                            {
                                // *** Write modified value to temporary file ***
                                Unmodified = false;
                                CurrentSection.Remove(Key);

                                sw.Write(Key);
                                sw.Write('=');
                                sw.WriteLine(Value);
                            }
                        }
                    }

                    // ** Check if the section/key in current line has been deleted ***
                    if (Unmodified)
                    {
                        if (SectionName != null)
                        {
                            if (!m_Sections.ContainsKey(SectionName))
                            {
                                Deleted = true;
                                CurrentSection2 = null;
                            }
                            else
                            {
                                Deleted = false;
                                m_Sections.TryGetValue(SectionName, out CurrentSection2);
                            }

                        }
                        else if (CurrentSection2 != null)
                        {
                            if (ParseKeyValuePair(s, ref Key2, ref Value2))
                            {
                                if (!CurrentSection2.ContainsKey(Key2)) Deleted = true;
                                else Deleted = false;
                            }
                        }
                    }


                    // *** Write unmodified lines from the original iniString ***
                    if (Unmodified)
                    {
                        if (isComment(s)) sw.WriteLine(s);
                        else if (!Deleted) sw.WriteLine(s);
                    }
                }

                // *** Close string reader ***
                sr.Close();
                sr = null;
            }
            finally
            {
                // *** Cleanup: close string reader ***                  
                if (sr != null) sr.Close();
                sr = null;
            }

            // *** Cycle on all remaining modified values ***
            foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Modified)
            {
                CurrentSection = SectionPair.Value;
                if (CurrentSection.Count > 0)
                {
                    if (!string.IsNullOrEmpty(sw.ToString()))
                        sw.WriteLine();

                    // *** Write the section name ***
                    sw.Write('[');
                    sw.Write(SectionPair.Key);
                    sw.WriteLine(']');

                    // *** Cycle on all key+value pairs in the section ***
                    foreach (KeyValuePair<string, string> ValuePair in CurrentSection)
                    {
                        // *** Write the key+value pair ***
                        sw.Write(ValuePair.Key);
                        sw.Write('=');
                        sw.WriteLine(ValuePair.Value);
                    }
                    CurrentSection.Clear();
                }
            }
            m_Modified.Clear();

            // *** Get result to iniString ***
            m_iniString = sw.ToString();
            sw.Close();
            sw = null;

            // ** Write iniString to file ***
            if (m_FileName != null)
            {
                File.WriteAllText(m_FileName, m_iniString);
            }
        }
        finally
        {
            // *** Cleanup: close string writer ***                  
            if (sw != null) sw.Close();
            sw = null;
        }
    }

19 Source : Common.cs
with GNU General Public License v3.0
from FreeDemon2020

public static string GetFriendlyTypeName(Type type)
        {
            var codeDomProvider = CodeDomProvider.CreateProvider("C#");
            var typeReferenceExpression = new CodeTypeReferenceExpression(new CodeTypeReference(type));
            using (var writer = new StringWriter())
            {
                codeDomProvider.GenerateCodeFromExpression(typeReferenceExpression, writer, new CodeGeneratorOptions());
                return writer.GetStringBuilder().ToString();
            }
        }

19 Source : Script.cs
with MIT License
from fuse-open

public override void WriteIdentifier (Identifier identifier)
			{
				int startOffset = stringWriter.GetStringBuilder ().Length;
				int endOffset = startOffset + (identifier.Name ?? "").Length + (identifier.IsVerbatim ? 1 : 0);
				NewSegments.Add(new KeyValuePair<AstNode, Segment>(identifier, new Segment(startOffset, endOffset - startOffset)));
				base.WriteIdentifier (identifier);
			}

19 Source : Script.cs
with MIT License
from fuse-open

public override void StartNode (AstNode node)
			{
				base.StartNode (node);
				startOffsets.Push(stringWriter.GetStringBuilder ().Length);
			}

19 Source : Script.cs
with MIT License
from fuse-open

public override void EndNode (AstNode node)
			{
				int startOffset = startOffsets.Pop();
				int endOffset = stringWriter.GetStringBuilder ().Length;
				NewSegments.Add(new KeyValuePair<AstNode, Segment>(node, new Segment(startOffset, endOffset - startOffset)));
				base.EndNode (node);
			}

19 Source : CappedStringWriter.cs
with MIT License
from GGG-KILLER

private void CapReached()
        {
            throw new Exception($"Test produced more output than expected ({_expectedLength} characters). Is it in an infinite loop? Output so far:\r\n{GetStringBuilder()}");
        }

19 Source : RebuildFileLists.cs
with zlib License
from gibbed

private static void HandleEntries(
            TArchive fat,
            HashList<THash> knownHashes,
            Tracking tracking,
            string outputPath)
        {
            var localBreakdown = new Breakdown();

            var localNames = new List<string>();
            var localHashes = fat.Entries
                .Select(e => e.NameHash)
                .Concat(GetDependentHashes(fat))
                .Distinct()
                .ToArray();
            foreach (var hash in localHashes)
            {
                var name = knownHashes[hash];
                if (name != null)
                {
                    localNames.Add(name);
                }
                localBreakdown.Total++;
            }

            tracking.Hashes.AddRange(localHashes);
            tracking.Names.AddRange(localNames);

            var distinctLocalNames = localNames.Distinct().ToArray();
            localBreakdown.Known += distinctLocalNames.Length;

            var outputParent = Path.GetDirectoryName(outputPath);
            if (string.IsNullOrEmpty(outputParent) == false)
            {
                Directory.CreateDirectory(outputParent);
            }

            using (var writer = new StringWriter())
            {
                writer.WriteLine("; {0}", localBreakdown);
                if (fat is Big.IDependentArchive<THash> dependentFat)
                {
                    if (dependentFat.HasArchiveHash == true || dependentFat.Dependencies.Count > 0)
                    {
                        writer.WriteLine(";");
                    }
                    if (dependentFat.HasArchiveHash == true)
                    {
                        writer.WriteLine("; archive={0}",
                            knownHashes[dependentFat.ArchiveHash] ??
                                fat.RenderNameHash(dependentFat.ArchiveHash));
                    }
                    foreach (var dependency in dependentFat.Dependencies)
                    {
                        writer.WriteLine("; dependency={0} @ {1}",
                            knownHashes[dependency.ArchiveHash] ??
                                fat.RenderNameHash(dependency.ArchiveHash),
                            knownHashes[dependency.NameHash] ??
                                fat.RenderNameHash(dependency.NameHash));
                    }
                }
                foreach (string name in distinctLocalNames.OrderBy(dn => dn))
                {
                    writer.WriteLine(name);
                }
                writer.Flush();

                using (var output = new StreamWriter(outputPath, false, new UTF8Encoding(false)))
                {
                    output.Write(writer.GetStringBuilder());
                }
            }
        }

19 Source : Program.cs
with zlib License
from gibbed

private static void HandleEntries(IEnumerable<uint> hashes,
                                          HashList<uint> knownHashes,
                                          string outputPath)
        {
            var breakdown = new Breakdown();

            var names = new List<string>();
            foreach (var hash in hashes)
            {
                var name = knownHashes[hash];
                if (name != null)
                {
                    names.Add(name);
                }

                breakdown.Total++;
            }

            var distinctNames = names.Distinct().ToArray();
            breakdown.Known += distinctNames.Length;

            var outputParent = Path.GetDirectoryName(outputPath);
            if (string.IsNullOrEmpty(outputParent) == false)
            {
                Directory.CreateDirectory(outputParent);
            }

            using (var writer = new StringWriter())
            {
                writer.WriteLine("; {0}", breakdown);

                foreach (string name in distinctNames.OrderBy(dn => dn))
                {
                    writer.WriteLine(name);
                }

                writer.Flush();

                using (var output = new StreamWriter(outputPath))
                {
                    output.Write(writer.GetStringBuilder());
                }
            }
        }

19 Source : Program.cs
with zlib License
from gibbed

private static void HandleEntries(IEnumerable<ulong> entries,
                                          HashList<ulong> knownHashes,
                                          Tracking tracking,
                                          Breakdown breakdown,
                                          string outputPath)
        {
            var localBreakdown = new Breakdown();

            var localNames = new List<string>();
            var localHashes = entries.ToArray();
            foreach (var hash in localHashes)
            {
                var name = knownHashes[hash];
                if (name != null)
                {
                    localNames.Add(name);
                }

                localBreakdown.Total++;
            }

            tracking.Hashes.AddRange(localHashes);
            tracking.Names.AddRange(localNames);

            var distinctLocalNames = localNames.Distinct().ToArray();
            localBreakdown.Known += distinctLocalNames.Length;

            breakdown.Known += localBreakdown.Known;
            breakdown.Total += localBreakdown.Total;

            var outputParent = Path.GetDirectoryName(outputPath);
            if (string.IsNullOrEmpty(outputParent) == false)
            {
                Directory.CreateDirectory(outputParent);
            }

            using (var writer = new StringWriter())
            {
                writer.WriteLine("; {0}", localBreakdown);

                foreach (string name in distinctLocalNames.OrderBy(dn => dn))
                {
                    writer.WriteLine(name);
                }

                writer.Flush();

                using (var output = new StreamWriter(outputPath))
                {
                    output.Write(writer.GetStringBuilder());
                }
            }
        }

19 Source : DynamicExecutionManager.cs
with Apache License 2.0
from Ginger-Automation

public static string CreateDynamicRunSetXML(Solution solution, RunsetExecutor runsetExecutor, CLIHelper cliHelper)
        {
            runsetExecutor.RunSetConfig.UpdateRunnersBusinessFlowRunsList();

            //Create execution object
            DynamicGingerExecution dynamicExecution = new DynamicGingerExecution();
            dynamicExecution.SolutionDetails = new SolutionDetails();
            if (cliHelper.DownloadUpgradeSolutionFromSourceControl == true)
            {
                dynamicExecution.SolutionDetails.SourceControlDetails = new SourceControlDetails();
                dynamicExecution.SolutionDetails.SourceControlDetails.Type = solution.SourceControl.GetSourceControlType.ToString();
                if (solution.SourceControl.GetSourceControlType == SourceControlBase.eSourceControlType.SVN)//added for supporting Jenkins way of config creation- need to improve it
                {
                    string modifiedURI = solution.SourceControl.SourceControlURL.TrimEnd(new char[] { '/' });
                    int lastSlash = modifiedURI.LastIndexOf('/');
                    modifiedURI = (lastSlash > -1) ? modifiedURI.Substring(0, lastSlash) : modifiedURI;
                    dynamicExecution.SolutionDetails.SourceControlDetails.Url = modifiedURI;
                }
                else
                {
                    dynamicExecution.SolutionDetails.SourceControlDetails.Url = solution.SourceControl.SourceControlURL.ToString();
                }
                if (solution.SourceControl.SourceControlUser != null && solution.SourceControl.SourceControlPreplaced != null)
                {
                    dynamicExecution.SolutionDetails.SourceControlDetails.User = solution.SourceControl.SourceControlUser;
                    dynamicExecution.SolutionDetails.SourceControlDetails.Preplacedword =  EncryptionHandler.EncryptwithKey(solution.SourceControl.SourceControlPreplaced);
                    dynamicExecution.SolutionDetails.SourceControlDetails.PreplacedwordEncrypted = "Y";
                }
                else
                {
                    dynamicExecution.SolutionDetails.SourceControlDetails.User = "N/A";
                    dynamicExecution.SolutionDetails.SourceControlDetails.Preplacedword = "N/A";
                }
                if (solution.SourceControl.GetSourceControlType == SourceControlBase.eSourceControlType.GIT && solution.SourceControl.SourceControlProxyAddress != null && solution.SourceControl.SourceControlProxyAddress.ToLower().ToString() == "true")
                {
                    dynamicExecution.SolutionDetails.SourceControlDetails.ProxyServer = solution.SourceControl.SourceControlProxyAddress.ToString();
                    dynamicExecution.SolutionDetails.SourceControlDetails.ProxyPort = solution.SourceControl.SourceControlProxyPort.ToString();
                }
            }
            dynamicExecution.SolutionDetails.Path = solution.Folder;
            dynamicExecution.ShowAutoRunWindow = cliHelper.ShowAutoRunWindow;

            AddRunset addRunset = new AddRunset();
            addRunset.Name = "Dynamic_" + runsetExecutor.RunSetConfig.Name;
            addRunset.Environment = runsetExecutor.RunsetExecutionEnvironment.Name;
            addRunset.Runreplacedyzer = cliHelper.Runreplacedyzer;
            addRunset.RunInParallel = runsetExecutor.RunSetConfig.RunModeParallel;

            foreach (GingerRunner gingerRunner in runsetExecutor.RunSetConfig.GingerRunners)
            {
                AddRunner addRunner = new AddRunner();
                addRunner.Name = gingerRunner.Name;
                if (gingerRunner.UseSpecificEnvironment == true && string.IsNullOrEmpty(gingerRunner.SpecificEnvironmentName) == false)
                {
                    addRunner.Environment = gingerRunner.SpecificEnvironmentName;
                }
                if (gingerRunner.RunOption != GingerRunner.eRunOptions.ContinueToRunall)
                {
                    addRunner.RunMode = gingerRunner.RunOption.ToString();
                }

                foreach (GingerCore.Platforms.ApplicationAgent applicationAgent in gingerRunner.ApplicationAgents)
                {
                    addRunner.SetAgents.Add(new SetAgent() { AgentName = applicationAgent.AgentName, ApplicationName = applicationAgent.AppName });
                }

                foreach (BusinessFlowRun businessFlowRun in gingerRunner.BusinessFlowsRunList)
                {
                    AddBusinessFlow addBusinessFlow = new AddBusinessFlow();
                    addBusinessFlow.Name = businessFlowRun.BusinessFlowName;
                    if (businessFlowRun.BusinessFlowCustomizedRunVariables.Count > 0)
                    {
                        addBusinessFlow.InputVariables = new System.Collections.Generic.List<InputVariable>();
                        foreach (VariableBase variableBase in businessFlowRun.BusinessFlowCustomizedRunVariables)
                        {
                            InputVariable inputVar = new InputVariable();
                            if (variableBase.ParentType != "Business Flow")
                            {
                                inputVar.VariableParentType = variableBase.ParentType;
                                inputVar.VariableParentName = variableBase.ParentName;
                            }
                            inputVar.VariableName = variableBase.Name;
                            inputVar.VariableValue = variableBase.Value;

                            addBusinessFlow.InputVariables.Add(inputVar);
                        }
                    }
                    addRunner.AddBusinessFlows.Add(addBusinessFlow);
                }
                addRunset.AddRunners.Add(addRunner);
            }

            foreach (RunSetActionBase runSetOperation in runsetExecutor.RunSetConfig.RunSetActions)
            {
                if (runSetOperation is RunSetActionHTMLReportSendEmail)
                {
                    RunSetActionHTMLReportSendEmail runsetMailReport = (RunSetActionHTMLReportSendEmail)runSetOperation;
                    MailReport dynamicMailReport = new MailReport();
                    dynamicMailReport.Condition = runsetMailReport.Condition.ToString();
                    dynamicMailReport.RunAt = runsetMailReport.RunAt.ToString();

                    dynamicMailReport.MailFrom = runsetMailReport.MailFrom;
                    dynamicMailReport.MailTo = runsetMailReport.MailTo;
                    dynamicMailReport.MailCC = runsetMailReport.MailCC;

                    dynamicMailReport.Subject = runsetMailReport.Subject;
                    dynamicMailReport.Comments = runsetMailReport.Comments;

                    if (runsetMailReport.Email.EmailMethod == GingerCore.GeneralLib.Email.eEmailMethod.OUTLOOK)
                    {
                        dynamicMailReport.SendViaOutlook = true;
                    }
                    else
                    {
                        dynamicMailReport.SmtpDetails = new SmtpDetails();
                        dynamicMailReport.SmtpDetails.Server = runsetMailReport.Email.SMTPMailHost;
                        dynamicMailReport.SmtpDetails.Port = runsetMailReport.Email.SMTPPort.ToString();
                        dynamicMailReport.SmtpDetails.EnableSSL = runsetMailReport.Email.EnableSSL.ToString();
                        if (runsetMailReport.Email.ConfigureCredential)
                        {
                            dynamicMailReport.SmtpDetails.User = runsetMailReport.Email.SMTPUser;
                            dynamicMailReport.SmtpDetails.Preplacedword = runsetMailReport.Email.SMTPPreplaced;
                        }
                    }

                    if (runsetMailReport.EmailAttachments.Where(x => x.AttachmentType == EmailAttachment.eAttachmentType.Report).FirstOrDefault() != null)
                    {
                        dynamicMailReport.IncludeAttachmentReport = true;
                    }
                    else
                    {
                        dynamicMailReport.IncludeAttachmentReport = false;
                    }

                    addRunset.AddRunsetOperations.Add(dynamicMailReport);
                }
                else if (runSetOperation is RunSetActionJSONSummary)
                {
                    JsonReport dynamicJsonReport = new JsonReport();
                    addRunset.AddRunsetOperations.Add(dynamicJsonReport);
                }
                else if (runSetOperation is RunSetActionHTMLReport)
                {
                    RunSetActionHTMLReport runsetActionProduceHTMLReport = (RunSetActionHTMLReport)runSetOperation;
                    ProduceHTML dynamicReport = new ProduceHTML();
                    dynamicReport.Condition = runsetActionProduceHTMLReport.Condition.ToString();
                    dynamicReport.RunAt = runsetActionProduceHTMLReport.RunAt.ToString();
                    dynamicReport.selectedHTMLReportTemplateID = runsetActionProduceHTMLReport.selectedHTMLReportTemplateID;
                    dynamicReport.isHTMLReportFolderNameUsed = runsetActionProduceHTMLReport.isHTMLReportFolderNameUsed;
                    if (runsetActionProduceHTMLReport.isHTMLReportFolderNameUsed)
                    {
                        dynamicReport.HTMLReportFolderName = runsetActionProduceHTMLReport.HTMLReportFolderName;
                    }
                    dynamicReport.isHTMLReportPermanentFolderNameUsed = runsetActionProduceHTMLReport.isHTMLReportPermanentFolderNameUsed;
                   
                    addRunset.AddRunsetOperations.Add(dynamicReport);
                }
            }
            dynamicExecution.AddRunsets.Add(addRunset);

            //Serilize to XML String
            XmlSerializer writer = new XmlSerializer(typeof(DynamicGingerExecution));
            StringWriter stringWriter = new StringWriter();
            writer.Serialize(stringWriter, dynamicExecution);
            stringWriter.Close();
            return stringWriter.GetStringBuilder().ToString();
        }

19 Source : Page.cs
with MIT License
from hishamco

private async Task<HtmlDoreplacedent> RenderControlNodes()
        {
            var controlRendering = new ControlRendering();
            var doc = new HtmlDoreplacedent();

            doc.LoadHtml(_content);
            var nodes = doc.DoreplacedentNode.SelectNodes($"//*[starts-with(name(),'{Control.TagPrefix}')]");

            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    using (var sw = new StringWriter(new StringBuilder()))
                    {
                        await controlRendering.RenderAsync(this, node.OuterHtml, sw);
                        var newNode = new HtmlDoreplacedent();
                        newNode.LoadHtml(sw.GetStringBuilder().ToString());
                        node.ParentNode.ReplaceChild(newNode.DoreplacedentNode, node);
                    }
                }
            }

            return doc;
        }

19 Source : ControlRenderingTest.cs
with MIT License
from hishamco

[Fact]
        public async Task RenderControl()
        {
            // Arrange
            var controlRendering = new ControlRendering();
            var page = new TestPage();
            var markup = "<asp:Literal Name=\"litPostBack\" Text=\"IsPostBack: False\"></asp:Literal>";
            var writer = new StringWriter(new StringBuilder());
            
            // Act
            await controlRendering.RenderAsync(page, markup, writer);

            // replacedert
            replacedert.Equal("IsPostBack: False", writer.GetStringBuilder().ToString());
        }

19 Source : ControlRenderingTest.cs
with MIT License
from hishamco

[Fact]
        public async Task ControlWithoutNameShouldNotBeRendered()
        {
            // Arrange
            var controlRendering = new ControlRendering();
            var page = new TestPage();
            var markup = "<asp:Literal Text=\"IsPostBack: False\"></asp:Literal>";
            var writer = new StringWriter(new StringBuilder());

            // Act
            await controlRendering.RenderAsync(page, markup, writer);

            // replacedert
            replacedert.Equal(string.Empty, writer.GetStringBuilder().ToString());
        }

19 Source : ControlRenderingTest.cs
with MIT License
from hishamco

[Fact]
        public async Task NonExistControlShouldNotBeRendered()
        {
            // Arrange
            var controlRendering = new ControlRendering();
            var page = new TestPage();
            var markup = "<asp:Literal Name=\"litPostBack1\" Text=\"IsPostBack: False\"></asp:Literal>";
            var writer = new StringWriter(new StringBuilder());

            // Act
            await controlRendering.RenderAsync(page, markup, writer);

            // replacedert
            replacedert.Equal(string.Empty, writer.GetStringBuilder().ToString());
        }

See More Examples