public static string GetWellFormedHTML(string html, string xpathNavPath) { // StreamReader sReader = null; StringWriter sw = null; SgmlReader reader = null; XmlTextWriter writer = null; try { // if (uri == String.Empty) uri = "http://www.XMLforASP.NET"; // HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); // HttpWebResponse res = (HttpWebResponse)req.GetResponse(); // sReader = new StreamReader(res.GetResponseStream()); reader = new SgmlReader(); reader.DocType = "HTML"; reader.InputStream = new StringReader(html); sw = new StringWriter(); writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; //writer.WriteStartElement("Test"); while (reader.Read()) { if (reader.NodeType != XmlNodeType.Whitespace) { writer.WriteNode(reader, true); } } //writer.WriteEndElement(); if (xpathNavPath == null) { string sr = sw.ToString(); sr = sr.Replace("\r", "\n"); sr = sr.Replace("\n\n", "\n"); return sr; } else { //Filter out nodes from HTML StringBuilder sb = new StringBuilder(); XPathDocument doc = new XPathDocument(new StringReader(sw.ToString())); XPathNavigator nav = doc.CreateNavigator(); XPathNodeIterator nodes = nav.Select(xpathNavPath); while (nodes.MoveNext()) { sb.Append(nodes.Current.Value + "\n"); } string sr = sb.ToString(); sr = sr.Replace("\r", "\n"); sr = sr.Replace("\n\n", "\n"); return sr; } } catch (Exception exp) { writer.Close(); reader.Close(); sw.Close(); // sReader.Close(); return exp.Message; } }
public void add_dividers_and_jagged_columns() { var report = new TextReport(); report.AddDivider('='); report.StartColumns(3); report.AddText("This is the header"); report.AddDivider('='); report.AddColumnData("a1***", "b1", "c1"); report.AddColumnData("a2", "b2***", "c2"); report.AddColumnData("a3", "b3", "c3***"); report.AddDivider('='); var writer = new StringWriter(); report.Write(writer); Debug.WriteLine(writer.ToString()); writer.ToString().ShouldEqualWithLineEndings(@" ========================= This is the header ========================= a1*** b1 c1 a2 b2*** c2 a3 b3 c3*** ========================= "); }
public override void Specify() { var trace = new StringWriter(); when("the user types in input which is rejected by NDesk.Options", delegate { var lastError = arrange(() => ConsoleCommandDispatcher.DispatchCommand( new ConsoleCommand[] { new SomeCommandWithAParameter() }, new[] { "some", "/a" }, trace)); then("the error output gives the error message and typical help", delegate { expect(() => lastError != 0); expect(() => trace.ToString().Contains("Missing required value for option '/a'")); expect(() => trace.ToString().Contains(TextWithinExpectedUsageHelp)); expect(() => !trace.ToString().ToLower().Contains("ndesk.options")); expect(() => !trace.ToString().ToLower().Contains("exception")); }); }); when("a command causes other unexpected errors", delegate { then("the exception passes through", delegate { Assert.Throws<InvalidAsynchronousStateException>(() => ConsoleCommandDispatcher.DispatchCommand( new ConsoleCommand[] { new SomeCommandThrowingAnException(), }, new string[0], trace)); }); }); }
protected override void SendBuffer(LoggingEvent[] events) { if (crashReportSender == null || events == null || events.Length == 0) return; try { using (var writer = new StringWriter(CultureInfo.InvariantCulture)) { for (int index = 0; index < events.Length; ++index) RenderLoggingEvent(writer, events[index]); LoggingEvent le = events[events.Length - 1]; string crashMessage = le.ExceptionObject == null ? string.Format("MSG - {0}", le.MessageObject) : string.Format("EXC - {0} : {1}", le.ExceptionObject.GetType().Name, le.ExceptionObject.Message); if (SendAsync) { Action<string, string> action = crashReportSender.Send; action.BeginInvoke(writer.ToString(), crashMessage, Sent, action); } else { crashReportSender.Send(writer.ToString(), crashMessage); } } } catch (Exception ex) { ErrorHandler.Error("Error occurred while sending crash report to the web.", ex); } }
public ActionResult Index([Diagnostics.NotNull] string route) { var actionResult = this.AuthenticateUser(); if (actionResult != null) { return actionResult; } var output = new StringWriter(); Console.SetOut(output); var projectDirectory = WebUtil.GetQueryString("pd"); var toolsDirectory = WebUtil.GetQueryString("td"); var binDirectory = FileUtil.MapPath("/bin"); var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).WithExtensionsDirectory(binDirectory).Start(); if (app == null) { return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, output.ToString()); } var instance = ((CompositionContainer)app.CompositionService).GetExportedValue<IWebApi>(route); if (instance == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Route not found: " + route); } var result = instance.Execute(app); return result ?? Content(output.ToString(), "text/plain"); }
public void TestWrite() { StringWriter writer = new StringWriter(); Assert.AreEqual (String.Empty, writer.ToString()); writer.Write( 'A' ); Assert.AreEqual ("A", writer.ToString()); writer.Write( " foo" ); Assert.AreEqual ("A foo", writer.ToString()); char[] testBuffer = "Test String".ToCharArray(); writer.Write( testBuffer, 0, 4 ); Assert.AreEqual ("A fooTest", writer.ToString()); writer.Write( testBuffer, 5, 6 ); Assert.AreEqual ("A fooTestString", writer.ToString()); writer = new StringWriter (); writer.Write(null as string); Assert.AreEqual ("", writer.ToString()); }
public void OpmlWriter_WithTwoBlogs_RendersCorrectIndentedOpml() { //arrange var blogs = new[] { new Blog {Id = 1, Host = "example.com", Subfolder = "blog1", Title = "example blog"}, new Blog {Id = 2, Host = "haacked.com", Title = "You've Been Haacked"} }; var writer = new StringWriter(); var urlHelper = new Mock<BlogUrlHelper>(); urlHelper.Setup(u => u.RssUrl(blogs[0])).Returns(new Uri("http://example.com/blog1/Rss.aspx")); urlHelper.Setup(u => u.RssUrl(blogs[1])).Returns(new Uri("http://haacked.com/Rss.aspx")); var opml = new OpmlWriter(); //act opml.Write(blogs, writer, urlHelper.Object); //assert const string expected = @"<opml version=""1.0""> <head> <title>A Subtext Community</title> </head> <body> <outline text=""A Subtext Community Feeds""> <outline type=""rss"" text=""example blog"" xmlUrl=""http://example.com/blog1/Rss.aspx"" /> <outline type=""rss"" text=""You've Been Haacked"" xmlUrl=""http://haacked.com/Rss.aspx"" /> </outline> </body> </opml>"; UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, writer.ToString()); Assert.AreEqual(expected, writer.ToString()); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { Layout.Format(sw, loggingEvent); //The textbox may not be ready at this point, so cache the appended //entries into a temp buffer until a textbox is ready. When it is //write the contents of the buffer first before writing the most //recent event if (_TextBox != null && !_TextBox.IsDisposed) { string content = sw.ToString(); string level = loggingEvent.Level.Name; if (_TextBox.InvokeRequired) { _TextBox.BeginInvoke(new WriteContentHandler(this.WriteContent), content, level); } else { WriteContent(content, level); } } else if (_buffer != null) { _buffer.Append(sw.ToString()); } } }
public void AppenderMetricDatum() { var t = new StringWriter(); new MetricDatumRenderer().RenderObject(null, new MetricDatum("A tick!") .WithMetricName("TheMetricName") .WithDimensions(new[]{new Dimension { Name = "dim1", Value = "v1" }, new Dimension { Name = "dim2", Value = "v2" } }) .WithUnit("Seconds") .WithValue(5.1) .WithTimestamp(DateTime.Parse("2012-09-11 11:11")), t); Assert.Contains(t.ToString(), "MetricName: TheMetricName"); Assert.Contains(t.ToString(), "Unit: Seconds"); Assert.Contains(t.ToString(), "Value: 5.1"); Assert.Contains(t.ToString(), "Timestamp: 2012-09-11 11:11"); Assert.Contains(t.ToString(), "Dimensions: dim1: v1, dim2: v2"); Assert.Contains(t.ToString(), "A tick!"); }
protected void bt_Export_Click(object sender, EventArgs e) { BindGrid(true, false); string filename = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(lb_ReportTitle.Text.Trim() == "" ? "Export" : lb_ReportTitle.Text.Trim())); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.ContentType = "application/ms-excel"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); Page.EnableViewState = false; StringWriter tw = new System.IO.StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); GridView1.RenderControl(hw); try { string tmp0 = "<tr align=\"left\" valign=\"middle\" OnMouseOver=\"this.style.cursor='hand';this.originalcolor=this.style.backgroundColor;this.style.backgroundColor='#FFCC66';\" OnMouseOut=\"this.style.backgroundColor=this.originalcolor;\" style=\"height:18px;\">"; string tmp1 = "<tr align=\"left\" valign=\"middle\" OnMouseOver=\"this.style.cursor='hand';this.originalcolor=this.style.backgroundColor;this.style.backgroundColor='#FFCC66';\" OnMouseOut=\"this.style.backgroundColor=this.originalcolor;\" style=\"background-color:White;height:18px;\">"; StringBuilder outhtml = new StringBuilder(tw.ToString()); outhtml = outhtml.Replace(tmp0, "<tr>"); outhtml = outhtml.Replace(tmp1, "<tr>"); outhtml = outhtml.Replace(" ", ""); Response.Write(outhtml.ToString()); } catch { Response.Write(tw.ToString()); } Response.End(); BindGrid(false, false); }
public void AmazonMetricDatum() { var t = new StringWriter(); new MetricDatumRenderer().RenderObject(null, new Amazon.CloudWatch.Model.MetricDatum { MetricName = "TheMetricName", Unit = "Seconds", Value = 5.1, Timestamp = DateTime.Parse("2012-09-11 11:11"), Dimensions = new List<Dimension> { new Dimension { Name = "dim1", Value = "v1" }, new Dimension { Name = "dim2", Value = "v2" } } }, t); Assert.That(t.ToString(), Is.StringContaining("MetricName: TheMetricName")); Assert.That(t.ToString(), Is.StringContaining("Unit: Seconds")); Assert.That(t.ToString(), Is.StringContaining("Value: 5.1")); Assert.That(t.ToString(), Is.StringContaining("Timestamp: 9/11/2012 11:11")); Assert.That(t.ToString(), Is.StringContaining("Dimensions: dim1: v1, dim2: v2")); }
public void One_failed_test_should_generate_test_suite_result_as_failure() { var writer = new StringWriter(); var formatter = new NUnitTestResultsFormatter(writer); formatter.Format(new StatLightResult("test", DateTime.ParseExact("2011-04-09", "yyyy-MM-dd", null), new[] { new StatLightTestResult("test1", true, false, false, "", "", TimeSpan.Zero), new StatLightTestResult("test2", false, true, false, "", "", TimeSpan.Zero), new StatLightTestResult("test3", false, false, true, "test-failure", "test-stack", TimeSpan.Zero) })); Console.WriteLine(writer.ToString()); Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?> <test-results name=""test"" total=""3"" not-run=""1"" failures=""1"" date=""2011-04-09"" time=""00:00:00""> <test-suite type=""TestFixture"" name=""test"" executed=""True"" result=""Failure"" success=""False""> <results> <test-case name=""test1"" executed=""True"" time=""00:00:00.0000"" result=""Success"" success=""True"" /> <test-case name=""test2"" executed=""False"" time=""00:00:00.0000"" result=""Ignored"" /> <test-case name=""test3"" executed=""True"" time=""00:00:00.0000"" result=""Failure"" success=""False""> <failure> <message>test-failure</message> <stack-trace><![CDATA[test-stack]]></stack-trace> </failure> </test-case> </results> </test-suite> </test-results>", writer.ToString()); }
public void TestCultureInfoConstructor() { StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); Assert.IsNotNull (writer.GetStringBuilder()); Assert.AreEqual (String.Empty, writer.ToString()); writer.Write( 'A' ); Assert.AreEqual ("A", writer.ToString()); writer.Write( " foo" ); Assert.AreEqual ("A foo", writer.ToString()); char[] testBuffer = "Test String".ToCharArray(); writer.Write( testBuffer, 0, 4 ); Assert.AreEqual ("A fooTest", writer.ToString()); writer.Write( testBuffer, 5, 6 ); Assert.AreEqual ("A fooTestString", writer.ToString()); writer = new StringWriter(CultureInfo.InvariantCulture); writer.Write(null as string); Assert.AreEqual ("", writer.ToString()); }
public void CommandTest() { XmlSerializer serializer = new XmlSerializer(typeof(Command)); StringWriter stringWriter = new StringWriter(); XmlWriter xmlWriter = XmlWriter.Create(stringWriter); Command cmd = new Command(); // TODO: Initialize to an appropriate value cmd.Method = "RunLine";//RunLine(float length, float speed, float acceleration) cmd.Parameters.Add(1.0f); cmd.Parameters.Add(1.0f); cmd.Parameters.Add(1.0f); serializer.Serialize(xmlWriter, cmd); xmlWriter.Flush(); Debug.WriteLine(stringWriter.ToString()); //XmlSerializer serializer = new XmlSerializer(typeof(Command)); StringReader stringReader = new StringReader(stringWriter.ToString()); XmlReader xmlReader = XmlReader.Create(stringReader); if (serializer.CanDeserialize(xmlReader)) { object o = serializer.Deserialize(xmlReader); if (o is Command) { Command cmdDeserialized = (Command)o; Debug.WriteLine(cmdDeserialized.ToString()); } } }
public virtual void doit() { /* * make a dvsl */ NVelocity.Dvsl.Dvsl dvsl = new NVelocity.Dvsl.Dvsl(); /* * register the stylesheet */ dvsl.SetStylesheet(new StringReader(dvslstyle)); /* * render the document as a Reader */ StringWriter sw = new StringWriter(); dvsl.Transform(new StringReader(input), sw); if (!sw.ToString().Equals("Hello from element! Foo")) Assertion.Fail("Result of first test is wrong : " + sw.ToString()); /* * now test if we can pass it a Document */ XmlDocument document = new XmlDocument(); document.Load(new StringReader(input)); sw = new StringWriter(); dvsl.Transform(document, sw); if (!sw.ToString().Equals("Hello from element! Foo")) Assertion.Fail("Result of second test is wrong : " + sw.ToString()); }
public void StrippedHtmlIsSameAsInput() { var input = SampleFile.Load("csharp-sample.txt"); var tokens = new CSharpLexer() .GetTokens(input) .ToArray(); var subject = new HtmlFormatter(new HtmlFormatterOptions() { NoWrap = true }); var htmlOut = new StringWriter(); subject.Format(tokens, htmlOut); File.WriteAllText("output.html", htmlOut.ToString()); var txtOut = new StringWriter(); new NullFormatter().Format(tokens, txtOut); var strippedHtml = Regex.Replace(htmlOut.ToString(), @"<.*?>", "") .Trim(); var escapedText = HtmlFormatter.EscapeHtml(txtOut.ToString()).Trim(); Check.That(strippedHtml).IsEqualTo(escapedText); }
private static void CompareAssemblyAgainstCSharp(string expectedCSharpCode, string asmFilePath) { var module = Utils.OpenModule(asmFilePath); try { try { module.LoadPdb(); } catch { } AstBuilder decompiler = AstBuilder.CreateAstBuilderTestContext(module); decompiler.AddAssembly(module, false, true, true); new Helpers.RemoveCompilerAttribute().Run(decompiler.SyntaxTree); StringWriter output = new StringWriter(); // the F# assembly contains a namespace `<StartupCode$tmp6D55>` where the part after tmp is randomly generated. // remove this from the ast to simplify the diff var startupCodeNode = decompiler.SyntaxTree.Children.OfType<NamespaceDeclaration>().SingleOrDefault(d => d.Name.StartsWith("<StartupCode$", StringComparison.Ordinal)); if (startupCodeNode != null) startupCodeNode.Remove(); decompiler.GenerateCode(new PlainTextOutput(output)); var fullCSharpCode = output.ToString(); CodeAssert.AreEqual(expectedCSharpCode, output.ToString()); } finally { File.Delete(asmFilePath); File.Delete(Path.ChangeExtension(asmFilePath, ".pdb")); } }
void RunTest(string c_code, string expectedXml) { StringReader reader = null; StringWriter writer = null; try { reader = new StringReader(c_code); writer = new StringWriter(); var xWriter = new XmlnsHidingWriter(writer) { Formatting = Formatting.Indented }; var xc = new XmlConverter(reader, xWriter); xc.Convert(); writer.Flush(); Assert.AreEqual(expectedXml, writer.ToString()); } catch { Debug.WriteLine(writer.ToString()); throw; } finally { if (writer != null) writer.Dispose(); if (reader != null) reader.Dispose(); } }
public void CSharpVisitorSpecTest(string fullName, string haml, string html, string format, SpecLocal[] locals) { var output = new StringWriter(); var parser = new Core.Parser.Parser(); var document = parser.Parse(haml); var visitor = new DebugCompiler(document, format); output.WriteLine("Name: " + fullName); foreach (var local in locals) { output.WriteLine("Var: " + local.Name + "=" + local.Value); visitor.Locals.Add(local.Name, local.Value); } output.WriteLine("Form: " + format); output.WriteLine("Haml: " + haml); output.WriteLine("Exp: " + html.Replace(Environment.NewLine, @"\n")); try { var writer = visitor.Run(); output.WriteLine("Out: " + writer.ToString().Replace(Environment.NewLine, @"\n")); output.Flush(); Assert.True(writer.ToString().Equals(html), output.ToString()); Debug.Write(output); Debug.WriteLine("------------------------"); } catch (Exception exception) { throw new Exception(output.ToString(), exception); } }
public override SqlStatementKind BuildSql(StringBuilder b, SqlQueryContext context) { SqlStatementKind kind = Target.BuildSql(b, context); if (kind == SqlStatementKind.SelectOrderBy) WrapSqlIntoNestedStatement(b, context); b.Append(" ORDER BY "); for (int i = 0; i < arguments.Count; i++) { StringWriter w = new StringWriter(); ExpressionSqlWriter writer = new ExpressionSqlWriter(w, context, arguments[i].Argument.Parameters[0]); writer.Write(arguments[i].Argument.Body); if (i == 0) b.Append(w.ToString()); else b.Append(", " + w.ToString()); if (arguments[i].Descending) b.Append(" DESC"); else b.Append(" ASC"); } return SqlStatementKind.SelectOrderBy; }
static void Main(string[] args) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Newtonsoft.Json.Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("CPU"); writer.WriteValue("Intel"); writer.WritePropertyName("PSU"); writer.WriteValue("500W"); writer.WritePropertyName("Drives"); writer.WriteStartArray(); writer.WriteValue("DVD read/writer"); writer.WriteComment("(broken)"); writer.WriteValue("500 gigabyte hard drive"); writer.WriteValue("200 gigabype hard drive"); writer.WriteEnd(); writer.WriteEndObject(); } File.WriteAllText(Environment.CurrentDirectory + "/rhcdata.json", sw.ToString()); Console.WriteLine(sw.ToString()); Console.ReadLine(); }
/// <summary> /// Asserts that the specification is met. /// </summary> /// <param name="builder">The specification builder.</param> /// <param name="comparer">The result comparer.</param> public static void Assert(this IResultCentricAggregateQueryTestSpecificationBuilder builder, IResultComparer comparer) { if (builder == null) throw new ArgumentNullException("builder"); if (comparer == null) throw new ArgumentNullException("comparer"); var specification = builder.Build(); var runner = new ResultCentricAggregateQueryTestRunner(comparer); var result = runner.Run(specification); if (result.Failed) { if (result.ButException.HasValue) { using (var writer = new StringWriter()) { writer.WriteLine(" Expected: {0},", result.Specification.Then); writer.WriteLine(" But was: {0}", result.ButException.Value); #if NUNIT throw new NUnit.Framework.AssertionException(writer.ToString()); #elif XUNIT throw new Xunit.Sdk.AssertException(writer.ToString()); #endif } } if (result.ButResult.HasValue) { using (var writer = new StringWriter()) { writer.WriteLine(" Expected: {0},", result.Specification.Then); writer.WriteLine(" But was: {0}", result.ButResult.Value); #if NUNIT throw new NUnit.Framework.AssertionException(writer.ToString()); #elif XUNIT throw new Xunit.Sdk.AssertException(writer.ToString()); #endif } } if (result.ButEvents.HasValue) { using (var writer = new StringWriter()) { writer.WriteLine(" Expected: {0},", result.Specification.Then); writer.WriteLine(" But was: {0} event(s) ({1})", result.ButEvents.Value.Length, String.Join(",", result.ButEvents.Value.Select(_ => _.GetType().Name).ToArray())); #if NUNIT throw new NUnit.Framework.AssertionException(writer.ToString()); #elif XUNIT throw new Xunit.Sdk.AssertException(writer.ToString()); #endif } } } }
protected void Page_Load(object sender, EventArgs e) { var serializer = new Serializer(); var writer = new StringWriter(); // Additional Ip subnets var addSubnets = osm.ListSubnets() .Where<Subnet>(s => s.IpVersion == 4 && s.Name.StartsWith("add")); foreach (var s in addSubnets) { writer.Write("===================================\n"); var subnet = osm.GetSubnet(s.Id); serializer.Serialize(writer, subnet); } ltAddSubnets.Text = writer.ToString(); writer.GetStringBuilder().Clear(); // Local Network subnets var localSubnets = osm.ListSubnets() .Where<Subnet>(s => s.IpVersion == 4 && s.Name.StartsWith("local-")); foreach (var s in localSubnets) { writer.Write("===================================\n"); var subnet = osm.GetSubnet(s.Id); serializer.Serialize(writer, subnet); } ltLocalSubnets.Text = writer.ToString(); writer.GetStringBuilder().Clear(); // Ports var ports = osm.ListPorts(); foreach (var p in ports) { writer.Write("===================================\n"); var subnet = osm.GetPort(p.Id); serializer.Serialize(writer, subnet); } ltPorts.Text = writer.ToString(); writer.GetStringBuilder().Clear(); // Security Groups var groups = osm.ListNetworkSecurityGroups(); foreach (var g in groups) { writer.Write("===================================\n"); var group = osm.GetNetworkSecurityGroup(g.Id); serializer.Serialize(writer, group); } ltSecurityGroups.Text = writer.ToString(); writer.GetStringBuilder().Clear(); }
public void RunOnceMode() { var sw = new StringWriter(); new TestTask(sw) {WasRunOnce = true, RunOnce = true}.Execute(); Console.WriteLine(sw.ToString()); Assert.AreEqual(@" S:Pending S:SuccessOnce ".Trim(), sw.ToString().Trim()); }
private void AssertProgram(string sExp, Program program) { var sw = new StringWriter(); program.Procedures.Values.First().Write(false, sw); var sActual = sw.ToString(); if (sExp != sActual) Debug.WriteLine(sActual); Assert.AreEqual(sExp, sw.ToString()); }
public void Test() { var serializer = new XmlSerializer(typeof(Quiz)); var quiz = new Quiz { Title = "Title", Id = "Id", Blocks = new SlideBlock[] { new MdBlock {Markdown = "This is quiz!"}, new IsTrueBlock { Id = "1", Text = "Это утверждение ложно", }, new ChoiceBlock { Text = "What is the \nbest color?", Items = new[] { new ChoiceItem {Id="1", Description = "black", IsCorrect = true}, new ChoiceItem {Id="2", Description = "green"}, new ChoiceItem {Id="3", Description = "red"}, } }, new ChoiceBlock { Multiple = true, Text = "What does the fox say?", Items = new[] { new ChoiceItem {Description = "Apapapapa", IsCorrect = true}, new ChoiceItem {Description = "Ding ding ding", IsCorrect = true}, new ChoiceItem {Description = "Mew"}, } }, new FillInBlock { Text = "What does the fox say?", Regexes = new[] {new RegexInfo {Pattern = "([Dd]ing )+"}, new RegexInfo {Pattern = "Ap(ap)+"}}, Sample = "Apapap" }, } }; var w1 = new StringWriter(); var ns = new XmlSerializerNamespaces(); ns.Add("x", "http://www.w3.org/2001/XMLSchema-instance"); serializer.Serialize(w1, quiz, ns); ApprovalTests.Approvals.Verify(w1.ToString()); Console.WriteLine(w1.ToString()); Console.WriteLine(); var quiz2 = serializer.Deserialize(new StringReader(w1.ToString())); var w2 = new StringWriter(); serializer.Serialize(w2, quiz2, ns); Console.WriteLine(w2.ToString()); Assert.AreEqual(w1.ToString(), w2.ToString()); }
public override void Specify() { given("we have some commands", delegate { var firstcommand = new TestCommand().IsCommand("command-a", "oneline description a"); var secondCommand = new TestCommand().IsCommand("command-b", "oneline description b"); var commands = new ConsoleCommand[] { firstcommand, secondCommand }.ToList(); var writer = new StringWriter(); when("we dispatch the commands with no arguments", delegate { arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new string[0], writer)); then("the output contains a list of available commands", delegate { var output = writer.ToString(); Expect.That(output).ContainsInOrder( firstcommand.Command, firstcommand.OneLineDescription, secondCommand.Command, secondCommand.OneLineDescription); }); }); when("we call a command, asking for help", delegate { var commandC = new TestCommand() .IsCommand("command-c", "one line description for C") .HasAdditionalArguments(0, "<remaining> <args>") .HasOption("o|option=", "option description", v => { }); commands.Add(commandC); arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new string[] { commandC.Command, "/?" }, writer)); then("the output contains a all help available for that command", delegate { var output = writer.ToString(); Expect.That(output).ContainsInOrder( commandC.Command, commandC.OneLineDescription, commandC.RemainingArgumentsHelpText, "-o", "--option", "option description"); }); }); }); }
public void CanIgnoreErrorRun() { var sw = new StringWriter(); new TestTask(sw) {DoError = true, IgnoreErrors = true}.Execute(); Console.WriteLine(sw.ToString()); Assert.AreEqual(@" S:Pending S:Executing S:SuccessIgnoreErrors ".Trim(), sw.ToString().Trim()); }
public void ShouldWriteToTextWriter() { TextWriter writer = new StringWriter(); ILoggerFacade logger = new TextLogger(writer); logger.Log("Test", Category.Debug, Priority.Low); StringAssert.Contains(writer.ToString(), "Test"); StringAssert.Contains(writer.ToString(), "DEBUG"); StringAssert.Contains(writer.ToString(), "Low"); }
public void EnsureSerializationOnlyContainsObfuscatedPassword() { string plaintext = "secret"; Password pw = new Password(plaintext); XmlSerializer xmlSerializer = new XmlSerializer(pw.GetType()); StringWriter textWriter = new StringWriter(); xmlSerializer.Serialize(textWriter, pw); Assert.IsTrue(textWriter.ToString().Contains(pw.ObfuscatedPassword)); Assert.IsFalse(textWriter.ToString().Contains(plaintext)); }
private static void ParseArgs(IEnumerable <string> args) { if (!string.IsNullOrEmpty(Logging.EVELoginUserName) && !string.IsNullOrEmpty(Logging.EVELoginPassword) && !string.IsNullOrEmpty(Logging.MyCharacterName)) { return; } OptionSet p = new OptionSet { "Usage: questor [OPTIONS]", "Buy and sell stuff on the auction house.", "", "Options:", { "u|user="******"the {USER} we are logging in as.", v => Logging.EVELoginUserName = v }, { "p|password="******"the user's {PASSWORD}.", v => Logging.EVELoginPassword = v }, { "c|character=", "the {CHARACTER} to use.", v => Logging.MyCharacterName = v }, { "l|loginOnly", "login only and exit.", v => _loginOnly = v != null }, { "h|help", "show this message and exit", v => _showHelp = v != null }, { "f|logfile=", "log file name", v => Logging.ConsoleLogFile = v }, { "d|logdirectory=", "log file directory", v => Logging.ConsoleLogPath = v }, { "s|savelogfile=", "save the log file", v => Logging.SaveConsoleLog = v != null }, { "i|settingsini=", "the settings ini file", v => SettingsINI = v } }; try { OmniEveParamaters = p.Parse(args); //Logging.Log(string.Format("questor: extra = {0}", string.Join(" ", extra.ToArray()))); } catch (OptionException ex) { Logging.Log("Program:ParseArgs", "omnieve: ", Logging.White); Logging.Log("Program:ParseArgs", ex.Message, Logging.White); Logging.Log("Program:ParseArgs", "Try `omnieve --help' for more information.", Logging.White); return; } if (_showHelp) { System.IO.StringWriter sw = new System.IO.StringWriter(); p.WriteOptionDescriptions(sw); Logging.Log("Program:ParseArgs", sw.ToString(), Logging.White); return; } }
protected void btnExportExcel_Click(object sender, EventArgs e) { // Clear all content output from the buffer stream Response.ClearContent(); // Specify the default file name using "content-disposition" RESPONSE header Response.AppendHeader("content-disposition", "attachment; filename=FeedbackReply" + DateTime.Now + ".xls"); // Set excel as the HTTP MIME type Response.ContentType = "application/excel"; // Create an instance of stringWriter for writing information to a string System.IO.StringWriter stringWriter = new System.IO.StringWriter(); // Create an instance of HtmlTextWriter class for writing markup // characters and text to an ASP.NET server control output stream HtmlTextWriter htw = new HtmlTextWriter(stringWriter); // Set white color as the background color for gridview header row GrdFeedback.HeaderRow.Style.Add("background-color", "#FFFFFF"); // Hide Particular Header and Cell of gridview foreach (GridViewRow row in GrdFeedback.Rows) { GrdFeedback.HeaderRow.Cells[4].Visible = false; row.Cells[4].Visible = false; GrdFeedback.HeaderRow.Cells[7].Visible = false; row.Cells[7].Visible = false; GrdFeedback.HeaderRow.Cells[8].Visible = false; row.Cells[8].Visible = false; } // Set background color of each cell of GridView1 header row foreach (TableCell tableCell in GrdFeedback.HeaderRow.Cells) { tableCell.Style["background-color"] = "#2873F0"; } // Set background color of each cell of each data row of GridView1 foreach (GridViewRow gridViewRow in GrdFeedback.Rows) { gridViewRow.BackColor = System.Drawing.Color.White; foreach (TableCell gridViewRowTableCell in gridViewRow.Cells) { gridViewRowTableCell.Style["background-color"] = "#FFFFFF"; } } GrdFeedback.RenderControl(htw); Response.Write(stringWriter.ToString()); Response.End(); }
public static bool Prefix(ref string __result, ref string baseSkinsXmlPath) { Debug.Print(DebugString.ToString()); // Why do I have to clone and modify two separate methods? - Designer225 List <string> elementNameList = new List <string>(); List <Tuple <string, string> > toBeMerged = new List <Tuple <string, string> >(); List <string> xsltList = new List <string>(); List <MbObjectXmlInformation> mbprojXmlList = XmlResource.MbprojXmls.Where(x => x.Id == "soln_skins").ToList(); mbprojXmlList.Reverse(); // restored for compatibility reason with mods that modify skin.xml that load later. //for (int i = 0; i < mbprojXmlList.Count; i++) //{ // var mbproj = mbprojXmlList[i]; // if (mbproj.ModuleName == "Native") // { // mbprojXmlList.RemoveAt(i); // mbprojXmlList.Add(mbproj); // break; // } //} foreach (MbObjectXmlInformation mbprojXml in mbprojXmlList) { if (File.Exists(ModuleInfo.GetXmlPathForNative(mbprojXml.ModuleName, mbprojXml.Name))) { elementNameList.Add(mbprojXml.Name); toBeMerged.Add(Tuple.Create(ModuleInfo.GetXmlPathForNative(mbprojXml.ModuleName, mbprojXml.Name), string.Empty)); } string xsltPathForNative = ModuleInfo.GetXsltPathForNative(mbprojXml.ModuleName, mbprojXml.Name); xsltList.Add(File.Exists(xsltPathForNative) ? xsltPathForNative : string.Empty); } XmlDocument mergedXmlForNative = MBObjectManager.CreateMergedXmlFile(toBeMerged, xsltList, true); System.IO.StringWriter stringWriter = new System.IO.StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); mergedXmlForNative.WriteTo(xmlTextWriter); baseSkinsXmlPath = elementNameList.First(); __result = stringWriter.ToString(); return(false); }
void generateKey(int keylength) { #region Key generation and exchange var csp = new RSACryptoServiceProvider(keylength); var privKey = csp.ExportParameters(true); var pubKey = csp.ExportParameters(false); string pubKeyStringLocal; { //we need some buffer var sw = new System.IO.StringWriter(); //we need a serializer var xsw = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xsw.Serialize(sw, pubKey); //get the string from the stream pubKeyStringLocal = sw.ToString(); pubKeyString = pubKeyStringLocal; } string privKeyStringLocal; { //we need some buffer var sw = new System.IO.StringWriter(); //we need a serializer var xsx = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xsx.Serialize(sw, privKey); //get the string from the stream privKeyStringLocal = sw.ToString(); privKeyString = privKeyStringLocal; } csp = new RSACryptoServiceProvider(); csp.ImportParameters(pubKey); string keyToSend = "K" + pubKeyString; byte[] keydata = Encoding.ASCII.GetBytes(keyToSend); rtbChat.Text += "Sending public key to remote...\n"; sendingClient.Send(keydata, keydata.Length); #endregion }
public void ExportToExcel() { this.Page.Response.Clear(); this.Page.Response.AddHeader(C_HTTP_HEADER_CONTENT, C_HTTP_ATTACHMENT + ((this.DataMember != "")? this.DataMember : "list") + ".xls"); this.Page.Response.Charset = ""; // If you want the option to open the Excel file without saving than // comment out the line below // Response.Cache.SetCacheability(HttpCacheability.NoCache); this.Page.Response.ContentType = C_HTTP_CONTENT_TYPE_EXCEL; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); this.AllowMultiColumnSorting = false; this.EnableSortingAndPagingCallbacks = false; this.AllowPaging = false; this.AllowSorting = false; this.Style.Clear(); this.RowStyle.Reset(); this.HeaderStyle.Reset(); this.AlternatingRowStyle.Reset(); this.BackColor = Color.Transparent; this.BorderWidth = new Unit(0); this.ShowTotalRowCount = false; this._ExportMode = true; this.Columns.Clear(); this.AutoGenerateColumns = true; this.DataBind(); this.RenderControl(htmlWrite); this.Page.Response.Write(stringWrite.ToString()); this.Page.Response.End(); }
/// <summary> /// 返回传入的excel是不是正确的时刻表格式 /// </summary> /// <param name="absFileName">绝对路径文件名</param> /// <param name="htmStr">返回的HTML字符串用于生成Excel</param> /// <param name="excelDt">返回的DataTable 用于处理数据源</param> public static bool IsExcelFormatRight(string absFileName, out string htmStr, out DataTable excelDt) { // 时刻表 DataTable timedataTable = new DataTable(); // 用于输出的控件 System.Web.UI.WebControls.GridView GridView1 = new System.Web.UI.WebControls.GridView(); bool returnvalue = true; //把excel转成DataTable timedataTable = ExcelOperate.Import(absFileName); GridView1.DataSource = timedataTable; GridView1.DataBind(); //开始创建用于输出的对像 System.IO.StringWriter sW = new System.IO.StringWriter(); Html32TextWriter hW = new Html32TextWriter(sW); //看看是不是正确的格式 foreach (GridViewRow row in GridView1.Rows) { if (row.RowType == DataControlRowType.DataRow) { for (int i = 0; i < row.Cells.Count; i++) { if (i != 3 && i != 0)//3为地点 { try { row.Cells[i].Text = DateTime.Parse(row.Cells[i].Text).ToString("HH:mm"); } catch { row.Cells[i].Attributes.Add("style", "background:#ff0000;"); row.Attributes["title"] = "输入时间格式不正确"; returnvalue = false; } } } } } GridView1.RenderControl(hW); //输出参数 htmStr = sW.ToString(); excelDt = timedataTable; return(returnvalue); }
private void ExportExcel(GridView SeriesValuesDataGrid) { string filename = ""; string today_detail_char = DateTime.Now.AddDays(+0).ToString("yyyy/MM/ddHHmmss").Replace("/", ""); filename = "VpnHistory_" + today_detail_char + ".xls"; filename = "attachment;filename=" + filename; Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", filename); //Response.AddHeader("content-disposition", "attachment;filename=\"" + filename + "\";"); Response.Charset = "big5"; // If you want the option to open the Excel file without saving than // comment out the line below // Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); SeriesValuesDataGrid.AllowPaging = false; SeriesValuesDataGrid.DataBind(); SeriesValuesDataGrid.RenderControl(htmlWrite); string head = " <html> " + " <head><meta http-equiv='Content-Type' content='text/html; charset=big5'></head> " + " <body> "; string footer = " </body>" + " </html>"; Response.Write(head + stringWrite.ToString() + footer); Response.End(); SeriesValuesDataGrid.AllowPaging = true; SeriesValuesDataGrid.DataBind(); }
///////////////////////////////////////File Functions//////////////////////////////////////////// public void ExportGridToExcel(GridView grid, string filename, HttpResponse response) { response.Clear(); response.Charset = ""; response.ContentType = "application/vnd.ms-excel"; response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls"); StringWriter sw = new System.IO.StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.AllowPaging = false; grid.AllowSorting = false; grid.RenderControl(htw); response.Write(sw.ToString()); response.End(); }
protected void Button8_Click(object sender, EventArgs e) { try { Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename= '" + ddl_Plantname.SelectedItem.Text + "'.xls"); Response.ContentType = "application/excel"; System.IO.StringWriter sw = new System.IO.StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView2.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } catch { } }
public void ExporttoExcel(DataTable theDT, HttpResponse theRes) { DataGrid theDG = new DataGrid(); theDG.DataSource = theDT; theDG.DataBind(); theRes.Clear(); theRes.Buffer = true; theRes.AddHeader("Content-Disposition", "attachment; filename=frmHIVCareFacilityStatistics.xls"); theRes.ContentType = "application/vnd.ms-excel"; theRes.Charset = ""; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); theDG.RenderControl(oHtmlTextWriter); theRes.Write(oStringWriter.ToString()); theRes.End(); }
public static IEnumerable <string> ToRdf(JToken token, JsonLdProcessorOptions options) { var jsonLdParser = new JsonLdParser(options); var store = new TripleStore(); jsonLdParser.Load(store, new StringReader(token.ToString(Newtonsoft.Json.Formatting.None))); var nqWriter = new NQuadsWriter(NQuadsSyntax.Rdf11); using var expectedTextWriter = new System.IO.StringWriter(); nqWriter.Save(store, expectedTextWriter); return(expectedTextWriter.ToString() .Split(expectedTextWriter.NewLine) .Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x)) .OrderBy(x => x)); }
private void SaveChanges(object package) { string fileName = @"..\..\packages.config"; using (StringWriter stringwriter = new System.IO.StringWriter()) { var serializer = new XmlSerializer(package.GetType()); serializer.Serialize(stringwriter, package); var ret = stringwriter.ToString(); using (var sw = new StreamWriter(fileName)) { sw.Write(ret); sw.Flush(); } } }
public static string TransformToHtml(this object o, Stream xslt, Stream css = null, Stream js = null) { if (o == null) { return(string.Empty); } System.IO.StringWriter sw = new System.IO.StringWriter(); if (!o.GetType().IsSerializable) { throw new MissingMethodException("Given object is not serializable."); } o.GetType().GetMethod("Serialize").Invoke(o, new object[] { sw }); return(TransformToHtml(sw.ToString(), xslt, css, js)); }
protected void ExcelPrintButton_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=customer_recap_" + System.DateTime.Today.ToString("yyyy-MM-dd") + ".xls"); Response.Charset = ""; // If you want the option to open the Excel file without saving then // comment out the line below // Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); GridViewOutSort.RenderControl(htmlWrite); GridViewInSort.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); }
public void UpdateCompanyTag(DataTable dttest) { DataTable dt = new DataTable(); SqlParameter[] prms = new SqlParameter[1]; dttest.TableName = "Testing"; System.IO.StringWriter writer = new System.IO.StringWriter(); dttest.WriteXml(writer, XmlWriteMode.WriteSchema, false); string result = writer.ToString(); prms[0] = new SqlParameter("@xml", SqlDbType.Xml) { Value = result }; InsertUpdateDeleteData("M_Attandence_Insert", prms); }
public static List <ServiceTask> GetTasks() { List <ServiceTask> tasks = new List <ServiceTask>(); //tasks.Add(new ServiceTask { CurrentChannel = "x1", ExecuteAssembly = "2", ExecuteModule = "3", Frequency = 4, Name = "5" }); XmlSerializer serializer2 = new XmlSerializer(typeof(List <ServiceTask>)); var stringwriter = new System.IO.StringWriter(); serializer2.Serialize(stringwriter, tasks); string s = stringwriter.ToString(); using (StringReader sr = new StringReader(File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Config\\Tasks.config"))) { XmlSerializer serializer = new XmlSerializer(typeof(List <ServiceTask>)); tasks = (List <ServiceTask>)serializer.Deserialize(sr); } return(tasks); }
public void Save(GridView oGrid, string exportFile) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.ms-word"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename = MemberList_" + DateTime.Now.ToString("dd_MM_yyyy") + ".xls"); HttpContext.Current.Response.AddHeader("Content-Type", "application/Excel"); HttpContext.Current.Response.Charset = ""; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); oGrid.GridLines = GridLines.Both; oGrid.RenderControl(oHtmlTextWriter); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); }
public static void RepeaterToExcel(Repeater rep, string filename) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls"); HttpContext.Current.Response.Charset = ""; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); // Your Repeater Name Mine is "Rep" rep.RenderControl(htmlWrite); HttpContext.Current.Response.Write("<table>"); HttpContext.Current.Response.Write(stringWrite.ToString()); HttpContext.Current.Response.Write("</table>"); HttpContext.Current.Response.End(); }
public InnerFinallyTest() { // Create test writer object to hold expected output System.IO.StringWriter expectedOut = new System.IO.StringWriter(); // Write expected output to string writer object expectedOut.WriteLine(" try 1"); expectedOut.WriteLine("\t try 1.1"); expectedOut.WriteLine("\t finally 1.1"); expectedOut.WriteLine("\t\t try 1.1.1"); expectedOut.WriteLine("\t\t Throwing an exception here!"); expectedOut.WriteLine("\t\t finally 1.1.1"); expectedOut.WriteLine(" catch 1"); expectedOut.WriteLine(" finally 1"); _trace = new Trace("InnerFinallyTest", expectedOut.ToString()); }
/// <summary> /// Export Excel use GridView data /// </summary> /// <param name="Typename"></param> /// <param name="TempGrid"></param> public static void GenerateByGridView(string Typename, GridView TempGrid) { HttpContext.Current.Response.Clear(); //HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; string Filename = Typename + ".xls"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "online;filename=" + Filename); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); HttpContext.Current.Response.ContentType = "application/ms-excel"; //this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); TempGrid.RenderControl(oHtmlTextWriter); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); }
protected void Button1_Click(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("Content-Disposition", "attachment;filename=My List(" + DateTime.Now.ToString("g") + ").xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); rptList.RenderControl(oHtmlTextWriter); Response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>"); Response.Write(oStringWriter.ToString()); Response.Flush(); Response.End(); }
/// <summary> /// 获取 服务器控件生成的html /// </summary> /// <param name="pCtrl"></param> /// <returns></returns> public static string GetControlHtml(System.Web.UI.Control pCtrl) { string strHtml = string.Empty; using (System.IO.StringWriter sw = new System.IO.StringWriter()) { using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw)) { pCtrl.RenderControl(htw); strHtml = sw.ToString(); } } return(strHtml); }
private void saveKeys_Click(object sender, RoutedEventArgs e) { System.IO.File.WriteAllText(docpath + @"\pubkey.txt", string.Empty); string pubKeyString; { //we need some buffer var sw = new System.IO.StringWriter(); //we need a serializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xs.Serialize(sw, pubKey); //get the string from the stream pubKeyString = sw.ToString(); } System.IO.File.WriteAllText(docpath + @"\privkey.txt", string.Empty); string privKeyString; { //we need some buffer var sw = new System.IO.StringWriter(); //we need a serializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xs.Serialize(sw, privKey); //get the string from the stream privKeyString = sw.ToString(); } using (StreamWriter outputFile = new StreamWriter(docpath + @"\pubkey.txt", true)) { foreach (char line in pubKeyString) { outputFile.Write(line); } } using (StreamWriter outputFile = new StreamWriter(docpath + @"\privkey.txt", true)) { foreach (char line in privKeyString) { outputFile.Write(line); } } AppendLineToChatBox("-- Public and private keys saved --"); }
protected void btnExportar_Click(object sender, EventArgs e) { if (dgDados.Rows.Count > 0) { Response.Clear(); string sNomeArquivo = "Tabulare_VendasSintetico.xls"; Response.AddHeader("content-disposition", "attachment;filename=" + sNomeArquivo + ""); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter sWr = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hWr = new HtmlTextWriter(sWr); dgDados.RenderControl(hWr); Response.Write(sWr.ToString()); Response.End(); } }
private void SaveBtn_Click(object sender, RoutedEventArgs e) { using (var stringwriter = new System.IO.StringWriter()) { Type[] types = new Type[3]; types[0] = typeof(NN.NeuralNet); types[1] = typeof(NN.Neuron); types[2] = typeof(NN.Layer); var serializer = new XmlSerializer(aiGeneration.Players[0].GetType(), types); serializer.Serialize(stringwriter, aiGeneration.Players[0]); string writeString = stringwriter.ToString(); writeString = writeString.Replace("encoding=\"utf-16\"", ""); File.WriteAllText("bestPlayer.dat", writeString); } }
protected void btnExcel_Click(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=结算预审.xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 this.EnableViewState = false; Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">"); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); Show(); Panel2.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); }
public static string FormatXml(XmlNode node) { var settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.IndentChars = " "; using (var writer = new System.IO.StringWriter()) { using (var xml = XmlTextWriter.Create(writer, settings)) { node.WriteTo(xml); } return(writer.ToString()); } }
/// <summary> /// Serialize object to an Xml String for use in your code /// </summary> /// <param name="cryo">T instance to serialize</param> /// <returns><see cref="System.String"/> representation of T object</returns> public static string ToXmlString(T cryo) { XmlSerializer serializer = new XmlSerializer(typeof(T)); System.IO.TextWriter writer = new System.IO.StringWriter(); try { serializer.Serialize(writer, cryo); } finally { writer.Flush(); writer.Close(); } return(writer.ToString()); }
public static void ExportExcel(Control ctrl, string filename, HttpResponse _Response) { HttpResponse Response = HttpContext.Current.Response; Response.Clear(); Response.Charset = "utf-8"; Response.AddHeader("Content-Type", "application/octet-stream"); Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", filename)); System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); ctrl.RenderControl(htmlWrite); string Header = "<html><head><meta http-equiv=\"Content-Type\" content=\"application/octet-stream; charset=utf-8\"></head><body>"; string Footer = "</body></html>"; Response.Write(String.Concat(Header, stringWrite.ToString(), Footer)); Response.End(); }
public DataSet XMLDatasetXsd(string sInnerText, string sRutaScheme) { clsHttpZipper cConvert = new clsHttpZipper(); string sC1 = cConvert.Compress(sInnerText, Enum_Encoding.Unicode); string sC2 = cConvert.DeCompress(sC1, Enum_Encoding.UTF8); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(sInnerText); /*CREAMOS EL SERIALIZADOR DEL OBJETO*/ XmlSerializer xmlSerial = new XmlSerializer(typeof(XmlDocument)); StringWriter sWriter = new System.IO.StringWriter(); xmlSerial.Serialize(sWriter, xDoc); XmlDocument xmlDocumento = new XmlDocument(); /*AGREGAMOS EL STRING DEL OBJETO SERIALIZADO A UN DOCUMENTO XML */ xmlDocumento.LoadXml(sWriter.ToString()); DataSet dsDataset = new DataSet(); /*LEEMOS EL DOCUMENTO XML Y LO AGREGAMOS AL LECTOR XML*/ XmlTextReader txtReader = new XmlTextReader(new StringReader(xmlDocumento.OuterXml)); try { HttpServerUtility objServer = HttpContext.Current.Server; dsDataset.ReadXmlSchema(sRutaScheme); /*LEEMOS EL XML Y LO AGREGAMOS AL DATASET*/ dsDataset.ReadXml(txtReader); /*CERRAMO EL LECTOR DEL XML*/ txtReader.Close(); /*ACEPTAMOS L0S CAMBIOS EN EL DATASET*/ dsDataset.AcceptChanges(); /*RETORNAMOS EL DATASET*/ return(dsDataset); } catch (Exception) { txtReader.Close(); return(null); } }