Search Results

Search found 145 results on 6 pages for 'stringwriter'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • DataContractSerializer truncated string when used with MemoryStream,but works with StringWriter

    - by Michael Freidgeim
    We've used the following DataContractSerializeToXml method for a long time, but recently noticed, that it doesn't return full XML for a long object, but  truncated it and returns XML string with the length of  multiple-of-1024 , but the reminder is not included. internal static string DataContractSerializeToXml<T>(T obj) { string strXml = ""; Type type= obj.GetType();//typeof(T) DataContractSerializer serializer = new DataContractSerializer(type); System.IO.MemoryStream aMemStr = new System.IO.MemoryStream(); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(aMemStr, null); serializer.WriteObject(writer, obj); strXml = System.Text.Encoding.UTF8.GetString(aMemStr.ToArray()); return strXml; }   I tried to debug and searched Google for similar problems, but didn't find explanation of the error. The most closed http://forums.codeguru.com/showthread.php?309479-MemoryStream-allocates-size-multiple-of-1024-( talking about incorrect length, but not about truncated string.fortunately replacing MemoryStream to StringWriter according to http://billrob.com/archive/2010/02/09/datacontractserializer-converting-objects-to-xml-string.aspxfixed the issue.   1: var serializer = new DataContractSerializer(tempData.GetType());   2: using (var backing = new System.IO.StringWriter())   3: using (var writer = new System.Xml.XmlTextWriter(backing))   4: {   5:     serializer.WriteObject(writer, tempData);   6:     data.XmlData = backing.ToString();   7: }v

    Read the article

  • String assembly by StringBuilder vs StringWriter and PrintWriter

    - by CPerkins
    I recently encountered an idiom I haven't seen before: string assembly by StringWriter and PrintWriter. I mean, I know how to use them, but I've always used StringBuilder. Is there a concrete reason for preferring one over the other? The StringBuilder method seems much more natural to me, but is it just style? I've looked at several questions here (including this one which comes closest: http://stackoverflow.com/questions/602279/stringwriter-or-stringbuilder ), but none in which the answers actually address the question of whether there's a reason to prefer one over the other for simple string assembly. This is the idiom I've seen and used many many times: string assembly by StringBuilder: public static String newline = System.getProperty("line.separator"); public String viaStringBuilder () { StringBuilder builder = new StringBuilder(); builder.append("first thing" + newline); builder.append("second thing" + newline); // ... several things builder.append("last thing" + newline); return builder.toString(); } And this is the new idiom: string assembly by StringWriter and PrintWriter: public String viaWriters() { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.println("first thing"); printWriter.println("second thing"); // ... several things printWriter.println("last thing"); printWriter.flush(); printWriter.close(); return stringWriter.toString(); }

    Read the article

  • How do i return a StringWriter When I cant Clone it?

    - by acidzombie24
    My code looks like the below. Obviously i cant write 'ok' because the object has been disposed. I cant do return sw.Clone() bc clone doesnt exist. If i dont use a using then at any point between = new and return (like iterating and writing to the object as my example doesnt do) can have an exception and thus not disposing the object. Am i to define sw outside of a try block and check if its null then dispose in a catch block? That seems like a bit of excessive work. Is there a better way? is that the only way? static void func1() { using (var sw = func2()) { sw.WriteLine("Ok"); } } static StringWriter func2() { using (var sw = new StringWriter()) { return sw; } }

    Read the article

  • Why StringWriter.ToString return `System.Byte[]` and not the data?

    - by theateist
    UnZipFile method writes the data from inputStream to outputWriter. Why sr.ToString() returns System.Byte[] and not the data? using (var sr = new StringWriter()) { UnZipFile(response.GetResponseStream(), sr); var content = sr.ToString(); } public static void UnZipFile(Stream inputStream, TextWriter outputWriter) { using (var zipStream = new ZipInputStream(inputStream)) { ZipEntry currentEntry; if ((currentEntry = zipStream.GetNextEntry()) != null) { var size = 2048; var data = new byte[size]; while (true) { size = zipStream.Read(data, 0, size); if (size > 0) { outputWriter.Write(data); } else { break; } } } } }

    Read the article

  • How to serialize a data of type string without using StringWriter as input

    - by starz26
    I want to serialize a input data of type string, but do not want to use StringWriter and StringReader for for serializing/Deserializing. The reason for this is when a escapse chars are sent as part of the Input string for serializing, it is serialized but some Spl chars are inserted in the xml(eg:"").I'm getting an XMl error while deserializing this serialized data. void M1() { string str = 23 + "AC"+(char)1; StringWriter sw = new StringWriter(); XmlSerializer serializer = new XmlSerializer(typeof(String)); serializer.Serialize(sw, str); System.Console.WriteLine("String encoded to XML = \n{0} \n", sw.ToString()); StringReader sr = new StringReader(sw.ToString()); String s2 = (String)serializer.Deserialize(sr); System.Console.WriteLine("String decoded from XML = \n {0}", s2); }

    Read the article

  • JAXB marshals XML differently to OutputStream vs. StringWriter

    - by Andy
    I apologize if this has been answered, but the search terms I have been using (i.e. JAXB @XmlAttribute condensed or JAXB XML marshal to String different results) aren't coming up with anything. I am using JAXB to un/marshal objects annotated with @XmlElement and @XmlAttribute annotations. I have a formatter class which provides two methods -- one wraps the marshal method and accepts the object to marshal and an OutputStream, the other just accepts the object and returns the XML output as a String. Unfortunately, these methods do not provide the same output for the same objects. When marshaling to a file, simple object fields internally marked with @XmlAttribute are printed as: <element value="VALUE"></element> while when marshaling to a String, they are: <element value="VALUE"/> I would prefer the second format for both cases, but I am curious as to how to control the difference, and would settle for them being the same regardless. I even created one static marshaller that both methods use to eliminate different instance values. The formatting code follows: /** Marker interface for classes which are listed in jaxb.index */ public interface Marshalable {} /** Local exception class */ public class XMLMarshalException extends BaseException {} /** Class which un/marshals objects to XML */ public class XmlFormatter { private static Marshaller marshaller = null; private static Unmarshaller unmarshaller = null; static { try { JAXBContext context = JAXBContext.newInstance("path.to.package"); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); unmarshaller = context.createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException("There was a problem creating a JAXBContext object for formatting the object to XML."); } } public void marshal(Marshalable obj, OutputStream os) throws XMLMarshalException { try { marshaller.marshal(obj, os); } catch (JAXBException jaxbe) { throw new XMLMarshalException(jaxbe); } } public String marshalToString(Marshalable obj) throws XMLMarshalException { try { StringWriter sw = new StringWriter(); marshaller.marshal(obj, sw); } catch (JAXBException jaxbe) { throw new XMLMarshalException(jaxbe); } } } /** Example data */ @XmlType @XmlAccessorType(XmlAccessType.FIELD) public class Data { @XmlAttribute(name = value) private String internalString; } /** Example POJO */ @XmlType @XmlRootElement(namespace = "project/schema") @XmlAccessorType(XmlAccessType.FIELD) public class Container implements Marshalable { @XmlElement(required = false, nillable = true) private int number; @XmlElement(required = false, nillable = true) private String word; @XmlElement(required = false, nillable = true) private Data data; } The result of calling marshal(container, new FileOutputStream("output.xml")) and marshalToString(container) are as follows: Output to file <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:container xmlns:ns2="project/schema"> <number>1</number> <word>stackoverflow</word> <data value="This is internal"></data> </ns2:container> and Output to String <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:container xmlns:ns2="project/schema"> <number>1</number> <word>stackoverflow</word> <data value="This is internal"/> </ns2:container>

    Read the article

  • Android XmlSerializer limitation?

    - by Rexb
    Hi all, My task is just to get an xml string using XmlSerializer. Problem is that it seems like the serializer stops adding any new element and/or attribute to the xml document when it reaches certain length (perhaps 10,000 char?). My questions: have you experience this kind of problem? What could be possible solutions? Here is my sample test code: public void doSerialize() throws XmlPullParserException, IllegalArgumentException, IllegalStateException, IOException { StringWriter writer = new StringWriter(); XmlSerializer serializer = XmlPullParserFactory.newInstance().newSerializer(); serializer.setOutput(writer); serializer.startDocument(null, null); serializer.startTag(null, "START"); for (int i = 0; i < 20; i++) { serializer.attribute(null, "ATTR" + i, "VAL " + i); } serializer.startTag(null, "DATA"); for (int i = 0; i < 500; i++) { serializer.attribute(null, "attr" + i, "value " + i); } serializer.endTag(null, "DATA"); serializer.endTag(null, "START"); serializer.endDocument(); String xml = writer.toString(); // value: until 493rd attribute int n = xml.length(); // value: 10125 } Any help will be greatly appreciated.

    Read the article

  • Serialize plain clean XML in .NET

    - by Jon Canning
    public static string ToXml<T>(this T obj) where T : class         {             using (var stringWriter = new StringWriter())             {                 var xmlWriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true };                 using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))                 {                     var xmlSerializerNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });                     var xmlSerializer = new XmlSerializer(typeof(T));                     xmlSerializer.Serialize(xmlWriter, obj, xmlSerializerNamespaces);                 }                 return stringWriter.ToString();             }         }

    Read the article

  • c# asp.net How to return a usercontrol from a handeler ashx?

    - by Justin808
    I want to return the HTML output of the control from a handler. My code looks like this: <%@ WebHandler Language="C#" Class="PopupCalendar" % using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public class PopupCalendar : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; System.Web.UI.Page page = new System.Web.UI.Page(); UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); page.Form.Controls.Add(ctrl); StringWriter stringWriter = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(stringWriter); ctrl.RenderControl(tw); context.Response.Write(stringWriter.ToString()); } public bool IsReusable { get { return false; } } } I'm getting the error: Server Error in '/CMS' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 14: System.Web.UI.Page page = new System.Web.UI.Page(); Line 15: UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); Line 16: page.Form.Controls.Add(ctrl); Line 17: Line 18: StringWriter stringWriter = new StringWriter(); How can I return the output of a Usercontrol via a handler?

    Read the article

  • Convert XMLDocument to String

    - by mnh
    Here is how I'm currently converting XMLDocument to String StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); xmlDoc.WriteTo(xmlTextWriter); return stringWriter.ToString(); The problem with this method is that if I have " ((quotes) which I have in attributes) it escapes them. For Instance: <Campaign name="ABC"> </Campaign> Above is the expected XML. But it returns <Campaign name=\"ABC\"> </Campaign> I can do String.Replace "\" but is that method okay? Are there any side-effects? Will it work fine if the XML itself contains a "\"

    Read the article

  • How can I get the error/warning messages out of the parsed HTML using JTidy?

    - by chetu
    I am able to parse the HTML but I want to extract the warning messages from the parsed HTML and show them to the user. Here is my code: Tidy tidy = new Tidy(); StringBuffer StringBuffer1 = new StringBuffer("<b>Hello<u><b>I am tsting another one.....<i>another....."); InputStream in = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-8")); Writer stringWriter = new StringWriter(); tidy.setPrintBodyOnly(true); tidy.setQuiet(true); tidy.setShowWarnings(true); tidy.setTidyMark(false); tidy.setXHTML(true); tidy.setXmlTags(false); Node parsedNode = tidy.parse(in, stringWriter); System.out.print(stringWriter.toString());

    Read the article

  • Localization approach for XSLT + RESX in ASP.NET

    - by frankadelic
    I have an ASP.NET web app where the back end data (XML format) is transformed using XSLT, producing XHTML which is output into the page. Simplified code: XmlDocument xmlDoc = MyRepository.RetrieveXmlData(keyValue); XslCompiledTransform xsl = new XslCompiledTransform(); xsl.Load(pathToXsl, XsltSettings.TrustedXslt, null); StringWriter stringWriter = new StringWriter(); xsl.Transform(xmlDoc, null, stringWriter); myLiteral.Text = stringWriter.ToString(); Currently my XSL file contains the XHTML markup elements, as well as text labels, which are currently in English. for example: <p>Title:<br /> <xsl:value-of select="title"/> </p> <p>Description:<br /> <xsl:value-of select="desc"/> </p> I would like the text labels (Title and Description above) to be localized. I was thinking of using .NET resource files (.resx), but I don't know how the resx string resources would get pulled in to the XSLT when the transformation takes place. I would prefer not to have locale-specific copies of the XSLT file, since that means a lot of duplicate transformation logic. (NOTE: the XML data is already localized, so I don't need to change that)

    Read the article

  • C# - File Encoding Problem.

    - by user301330
    Hello, I'm have a StringBuilder that is writing content to a file. Towards the end of each file, I'm writing the copyright symbol. Oddly, I have noticed that whenever the copyright symbol is written, it is preceeded by a "Â". My code that generates the content of the file looks like this: using (StringWriter stringWriter = new StringWriter()) { stringWriter = GetFileContent(); string targetPath = ConfigurationManager.AppSettings["TargetPath"]; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { StringBuilder sb = new StringBuilder(stringWriter.ToString()); // Attempted fix string content = sb.ToString(); content = content.Replace("Â", ""); streamWriter.Write(content); } } As you can tell, I tried to do a find-and-replace. In the process, I noticed that a "Â" was not in the content itself. This makes me believe there is something occurring in the streamWriter. However, I'm not sure what it could be. Can someone please tell me why a "Â" would be popping up before the "©" symbol and how to fix it? I believe it has something to do with encoding, but I'm not sure Thank you!

    Read the article

  • WCF and ASP.NET - Server.Execute throwing object reference not set to an instance of an object

    - by user208662
    Hello, I have an ASP.NET page that calls to a WCF service. This WCF service uses a BackgroundWorker to asynchronously create an ASP.NET page on my server. Oddly, when I execute the WCF Service [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public void PostRequest(string comments) { // Do stuff // If everything went o.k. asynchronously render a page on the server. I do not want to // block the caller while this is occurring. BackgroundWorker myWorker = new BackgroundWorker(); myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork); myWorker.RunWorkerAsync(HttpContext.Current); } private void myWorker_DoWork(object sender, DoWorkEventArgs e) { // Set the current context so we can render the page via Server.Execute HttpContext context = (HttpContext)(e.Argument); HttpContext.Current = context; // Retrieve the url to the page string applicationPath = context.Request.ApplicationPath; string sourceUrl = applicationPath + "/log.aspx"; string targetDirectory = currentContext.Server.MapPath("/logs/"); // Execute the other page and load its contents using (StringWriter stringWriter = new StringWriter()) { // Write the contents out to the target url // NOTE: THIS IS WHERE MY ERROR OCCURS currentContext.Server.Execute(sourceUrl, stringWriter); // Prepare to write out the result of the log targetPath = targetDirectory + "/" + DateTime.Now.ToShortDateString() + ".aspx"; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { // Write out the content to the file sb.Append(stringWriter.ToString()); streamWriter.Write(sb.ToString()); } } } Oddly, when the currentContext.Server.Execute method is executed, it throws an "object reference not set to an instance of an object" error. The reason this is so strange is because I can look at the currentContext properties in the watch window. In addition, Server is not null. Because of this, I have no idea where this error is coming from. Can someone point me in the correct direction of what the cause of this could be? Thank you!

    Read the article

  • How do I change the base class at runtime in C#?

    - by MatthewMartin
    I may be working on mission impossible here, but I seem to be getting close. I want to extend a ASP.NET control, and I want my code to be unit testable. Also, I'd like to be able to fake behaviors of a real Label (namely things like ID generation, etc), which a real Label can't do in an nUnit host. Here a working example that makes assertions on something that depends on a real base class and something that doesn't-- in a more realistic unit test, the test would depend on both --i.e. an ID existing and some custom behavior. Anyhow the code says it better than I can: public class LabelWrapper : Label //Runtime //public class LabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } //Ugh, now I have to test FakeLabelWrapper public class FakeLabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } [TestFixture] public class UnitTest { [Test] public void Test() { //Wish this was LabelWrapper label = new LabelWrapper(new FakeBase()) LabelWrapper label = new LabelWrapper(); //FakeLabelWrapper label = new FakeLabelWrapper(); label.Text = "ToUpper"; Assert.AreEqual("TOUPPER",label.Text); StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); label.RenderControl(writer); Assert.AreEqual(1,label.ID); Assert.AreEqual("<span>TOUPPER</span>", stringWriter.ToString()); } } public class FakeLabel { virtual public string Text { get; set; } public void RenderControl(TextWriter writer) { writer.Write("<span>" + Text + "</span>"); } } //System Under Test internal class LabelLogic { internal string ProcessGetText(string value) { return value.ToUpper(); } internal string ProcessSetText(string value) { return value.ToUpper(); } }

    Read the article

  • ASP.NET: Page HTML head rendering

    - by Fabian
    I've been trying to figure out the best way to custom render the <head> element of a pag to get rid of the extra line breaks which is caused by <head runat="server">, so its properly formatted. So far the only thing i've found which works is the following: protected override void Render(HtmlTextWriter writer) { StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); base.Render(htmlTextWriter); htmlTextWriter.Close(); string html = stringWriter.ToString(); string newHTML = html.Replace("\r\n\r\n<!DOCTYPE", "<!DOCTYPE") .Replace("\r\n<html", "<html") .Replace("<title>\r\n\t", "<title>") .Replace("\r\n</title>", "</title>") .Replace("</head>", "\n</head>"); writer.Write(newHTML); } I define my had tag like Now i have 2 questions: How does the above code affect the performance (so is this viable in an production environment)? Is there a better way to do this, for example a method which i can override to just custom render the <head>? Oh yeah ASP.NET MVC is not an option.

    Read the article

  • I have a custom type which i want to serialize, this custom type accepts input which might consists

    - by starz26
    I have a custom type which i want to serialize, this custom type accepts input which might consists of escape chars. M1_Serilizer(MyCustomType customTypeObj) {XmlSerializer serializer = new XmlSerializer(typeof(MyCustomType)); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); serializer.Serialize(sw, customTypeObj); string str= sw.ToString(); M2_Deserializer(str); } M2_Deserializer(string str) { XmlSerializer serializer = new XmlSerializer(typeof(MyCustomType)); StringReader sr = new StringReader(str); MyCustomType customTypeObj = (MyCustomType)serializer.Deserialize(sr); } when escape type chars are part of the CustomTypeObj, on deserialization it throws an exception. Q1)How do i overcome this?, Q2)I should use StringReader and StringWriter and not memorystream or other thing ways. StringWriter/reader will only serve my internal functionality Q3)How can these escape chars be handled?

    Read the article

  • HTML Tidy in NetBeans IDE (Part 2)

    - by Geertjan
    This is what I was aiming for in the previous blog entry: What you can see above (especially if you click to enlarge it) is that I have HTML Tidy integrated into the NetBeans analyzer functionality, which is pluggable from 7.2 onwards. Well, if you set an implementation dependency on "Static Analysis Core", since it's not an official API yet. Also, the scopes of the analyzer functionality are not pluggable. That means you can 'only' set the analyzer's scope to one or more projects, one or more packages, or one or more files. Not one or more folders, which means you can't have a bunch off HTML files in a folder that you access via the Favorites window and then run the analyzer on that folder (or on multiple folders). Thus, to try out my new code, I had to put some HTML files into a package inside a Java application. Then I chose that package as the scope of the analyzer. Then I ran all the analyzers (i.e., standard NetBeans Java hints, FindBugs, as well as my HTML Tidy extension) on that package. The screenshot above is the result. Here's all the code for the above, which is a port of the Action code from the previous blog entry into a new Analyzer implementation: import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.JComponent; import javax.swing.text.Document; import org.netbeans.api.fileinfo.NonRecursiveFolder; import org.netbeans.modules.analysis.spi.Analyzer; import org.netbeans.modules.analysis.spi.Analyzer.AnalyzerFactory; import org.netbeans.modules.analysis.spi.Analyzer.Context; import org.netbeans.modules.analysis.spi.Analyzer.CustomizerProvider; import org.netbeans.modules.analysis.spi.Analyzer.WarningDescription; import org.netbeans.spi.editor.hints.ErrorDescription; import org.netbeans.spi.editor.hints.ErrorDescriptionFactory; import org.netbeans.spi.editor.hints.Severity; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.util.Exceptions; import org.openide.util.lookup.ServiceProvider; import org.w3c.tidy.Tidy; public class TidyAnalyzer implements Analyzer {     private final Context ctx;     private TidyAnalyzer(Context cntxt) {         this.ctx = cntxt;     }     @Override     public Iterable<? extends ErrorDescription> analyze() {         List<ErrorDescription> result = new ArrayList<ErrorDescription>();         for (NonRecursiveFolder sr : ctx.getScope().getFolders()) {             FileObject folder = sr.getFolder();             for (FileObject fo : folder.getChildren()) {                 for (ErrorDescription ed : doRunHTMLTidy(fo)) {                     if (fo.getMIMEType().equals("text/html")) {                         result.add(ed);                     }                 }             }         }         return result;     }     private List<ErrorDescription> doRunHTMLTidy(FileObject sr) {         final List<ErrorDescription> result = new ArrayList<ErrorDescription>();         Tidy tidy = new Tidy();         StringWriter stringWriter = new StringWriter();         PrintWriter errorWriter = new PrintWriter(stringWriter);         tidy.setErrout(errorWriter);         try {             Document doc = DataObject.find(sr).getLookup().lookup(EditorCookie.class).openDocument();             tidy.parse(sr.getInputStream(), System.out);             String[] split = stringWriter.toString().split("\n");             for (String string : split) {                 //Bit of ugly string parsing coming up:                 if (string.startsWith("line")) {                     final int end = string.indexOf(" c");                     int lineNumber = Integer.parseInt(string.substring(0, end).replace("line ", ""));                     string = string.substring(string.indexOf(": ")).replace(":", "");                     result.add(ErrorDescriptionFactory.createErrorDescription(                             Severity.WARNING,                             string,                             doc,                             lineNumber));                 }             }         } catch (IOException ex) {             Exceptions.printStackTrace(ex);         }         return result;     }     @Override     public boolean cancel() {         return true;     }     @ServiceProvider(service = AnalyzerFactory.class)     public static final class MyAnalyzerFactory extends AnalyzerFactory {         public MyAnalyzerFactory() {             super("htmltidy", "HTML Tidy", "org/jtidy/format_misc.gif");         }         public Iterable<? extends WarningDescription> getWarnings() {             return Collections.EMPTY_LIST;         }         @Override         public <D, C extends JComponent> CustomizerProvider<D, C> getCustomizerProvider() {             return null;         }         @Override         public Analyzer createAnalyzer(Context cntxt) {             return new TidyAnalyzer(cntxt);         }     } } The above only works on packages, not on projects and not on individual files.

    Read the article

  • HTML Tidy in NetBeans IDE

    - by Geertjan
    First step in integrating HTML Tidy (via its JTidy implementation) into NetBeans IDE: The reason why I started doing this is because I want to integrate this into the pluggable analyzer functionality of NetBeans IDE that I recently blogged about, i.e., where the FindBugs functionality is found. So a logical first step is to get it working in an Action class, after which I can port it into the analyzer infrastructure: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.cookies.EditorCookie; import org.openide.cookies.LineCookie; import org.openide.loaders.DataObject; import org.openide.text.Line; import org.openide.text.Line.ShowOpenType; import org.openide.util.Exceptions; import org.openide.util.NbBundle.Messages; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; import org.openide.windows.OutputEvent; import org.openide.windows.OutputListener; import org.openide.windows.OutputWriter; import org.w3c.tidy.Tidy; @ActionID(     category = "Tools", id = "org.jtidy.TidyAction") @ActionRegistration(     displayName = "#CTL_TidyAction") @ActionReferences({     @ActionReference(path = "Loaders/text/html/Actions", position = 150),     @ActionReference(path = "Editors/text/html/Popup", position = 750) }) @Messages("CTL_TidyAction=Run HTML Tidy") public final class TidyAction implements ActionListener {     private final DataObject context;     private final OutputWriter writer;     private EditorCookie ec = null;     public TidyAction(DataObject context) {         this.context = context;         ec = context.getLookup().lookup(org.openide.cookies.EditorCookie.class);         InputOutput io = IOProvider.getDefault().getIO("HTML Tidy", false);         io.select();         writer = io.getOut();     }     @Override     public void actionPerformed(ActionEvent ev) {         Tidy tidy = new Tidy();         try {             writer.reset();             StringWriter stringWriter = new StringWriter();             PrintWriter errorWriter = new PrintWriter(stringWriter);             tidy.setErrout(errorWriter);             tidy.parse(context.getPrimaryFile().getInputStream(), System.out);             String[] split = stringWriter.toString().split("\n");             for (final String string : split) {                 final int end = string.indexOf(" c");                 if (string.startsWith("line")) {                     writer.println(string, new OutputListener() {                         @Override                         public void outputLineAction(OutputEvent oe) {                             LineCookie lc = context.getLookup().lookup(LineCookie.class);                             int lineNumber = Integer.parseInt(string.substring(0, end).replace("line ", ""));                             Line line = lc.getLineSet().getOriginal(lineNumber - 1);                             line.show(ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);                         }                         @Override                         public void outputLineSelected(OutputEvent oe) {}                         @Override                         public void outputLineCleared(OutputEvent oe) {}                     });                 }             }         } catch (IOException ex) {             Exceptions.printStackTrace(ex);         }     } } The string parsing above is ugly but gets the job done for now. A problem integrating this into the pluggable analyzer functionality is the limitation of its scope. The analyzer lets you select one or more projects, or individual files, but not a folder. So it doesn't work on folders in the Favorites window, for example, which is where I'd like to apply HTML Tidy, across multiple folders via the analyzer functionality. That's a bit of a bummer that I'm hoping to get around somehow.

    Read the article

  • How do I mock/fake/replace/stub a base class at unit-test time in C#?

    - by MatthewMartin
    UPDATE: I've changed the wording of the question. Previously it was a yes/no question about if a base class could be changed at runtime. I may be working on mission impossible here, but I seem to be getting close. I want to extend a ASP.NET control, and I want my code to be unit testable. Also, I'd like to be able to fake behaviors of a real Label (namely things like ID generation, etc), which a real Label can't do in an nUnit host. Here a working example that makes assertions on something that depends on a real base class and something that doesn't-- in a more realistic unit test, the test would depend on both --i.e. an ID existing and some custom behavior. Anyhow the code says it better than I can: public class LabelWrapper : Label //Runtime //public class LabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } //Ugh, now I have to test FakeLabelWrapper public class FakeLabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } [TestFixture] public class UnitTest { [Test] public void Test() { //Wish this was LabelWrapper label = new LabelWrapper(new FakeBase()) LabelWrapper label = new LabelWrapper(); //FakeLabelWrapper label = new FakeLabelWrapper(); label.Text = "ToUpper"; Assert.AreEqual("TOUPPER",label.Text); StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); label.RenderControl(writer); Assert.AreEqual(1,label.ID); Assert.AreEqual("<span>TOUPPER</span>", stringWriter.ToString()); } } public class FakeLabel { virtual public string Text { get; set; } public void RenderControl(TextWriter writer) { writer.Write("<span>" + Text + "</span>"); } } //System Under Test internal class LabelLogic { internal string ProcessGetText(string value) { return value.ToUpper(); } internal string ProcessSetText(string value) { return value.ToUpper(); } }

    Read the article

  • Export to Excel from ASP.NET produces files unreadable with Excel Viewer

    - by MainMa
    Hi, I want to output some dynamic data from an ASP.NET website to Excel. I found that the easiest way which does not require to use Excel XML or to install Excel on server machine is to output data as a table and specify application/vnd.ms-excel type. The problem is when I do so and try to open the file in Excel Viewer, I receive the following error message: Microsoft Excel Viewer cannot open files of this type. Then nothing is opened. Even an easiest code such as: protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Example.xls"); Response.ContentType = "application/vnd.ms-excel"; StringWriter stringWriter = new System.IO.StringWriter(); HtmlTextWriter htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter); dataGrid.RenderControl(htmlTextWriter); Response.Write("<html><body><table><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table></body></html>"); Response.End(); } produces the same error. What can cause such behavior? Is it because the Viewer cannot read such files, but full Excel version can?

    Read the article

  • Strongly Typed DataSet column requires custom type to implement IXmlSerializable?

    - by Phil
    I have a strongly typed Dataset with a single table with three columns. These columns all contain custom types. DataColumn1 is of type Parent DataColumn2 is of type Child1 DataColumn3 is of type Child2 Here is what these classes look like: [Serializable] [XmlInclude(typeof(Child1)), XmlInclude(typeof(Child2))] public abstract class Parent { public int p1; } [Serializable] public class Child1 :Parent { public int c1; } [Serializable] public class Child2 : Parent { public int c1; } now, if I add a row with DataColumn1 being null, and DataColumns 2 and 3 populated and try to serialize it, it works: DataSet1 ds = new DataSet1(); ds.DataTable1.AddDataTable1Row(null, new Child1(), new Child2()); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { ds.WriteXml(writer);//Works! } However, if I try to add a value to DataColumn1, it fails: DataSet1 ds = new DataSet1(); ds.DataTable1.AddDataTable1Row(new Child1(), new Child1(), new Child2()); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { ds.WriteXml(writer);//Fails! } Here is the Exception: "Type 'WindowsFormsApplication4.Child1, WindowsFormsApplication4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not implement IXmlSerializable interface therefore can not proceed with serialization." I have also tried using the XmlSerializer to serialize the dataset, but I get the same exception. Does anyone know of a way to get around this where I don't have to implement IXmlSerializable on all the Child classes? Alternatively, is there a way to implement IXmlSerializable keeping all default behavior the same (ie not having any class specific code in the ReadXml and WriteXml methods)

    Read the article

  • Render a user control ascx

    - by Jeremy
    I want to use an ascx as a template, and render it programatically, using the resulting html as the return value of an ajax method. Page pageHolder = new Page(); MyUserControl ctlRender = (MyUserControl)pageHolder.LoadControl(typeof(MyUserControl),null); pageHolder.Controls.Add(ctlRender); System.IO.StringWriter swOutput = new System.IO.StringWriter(); HttpContext.Current.Server.Execute(pageHolder, swOutput, false); return swOutput.ToString(); This all executes, and the Page Load event of the user control fires, but the StringWriter is always empty. I've seen similar code to this in other examples, what am I missing?

    Read the article

  • Server Controls in ASP.NET MVC without ViewState

    - by imran_ku07
      Introduction :           ASP.NET Web Forms provides a development environment just like GUI or windows application and try to hide statelessness nature of HTTP protocol. For accomplishing this target, Web Forms uses ViewState (a hidden field) to remove the gap between HTTP statelessness and GUI applications. But the problem with this technique is that ViewState size which grows quickly and also go back and forth with every request, as a result it will degrade application performance. In this article i will try to use existing ASP.NET server controls without ViewState.   Description :           When you add a server control which needs viewstate, in the presentation view in ASP.NET MVC application without a form tag, for example,            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>            It will shows the following exception,            Control 'TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server             When you place this textbox inside a form tag with runat=server, this will add the following ViewState even when you disable ViewState by using EnableViewState="false"            <input type="hidden" value="/wEPDwUJMjgzMDgzOTgzZGQ6u9CwikhHEW39ObrHyLTPFSboPA==" id="__VIEWSTATE" name="__VIEWSTATE"/>             The solution to this problem is to use the RenderControl method of server control which is simply renders HTML without any ViewState hidden field.         <% TextBox txt = new TextBox();          txt.Text = "abc";          StringBuilder sb = new StringBuilder();          System.IO.StringWriter textwriter = new System.IO.StringWriter(sb);          HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);          txt.RenderControl(htmlwriter);  %>        <%= sb.ToString() %>             This will render <input type="text" > without any View State. This technique become very useful when you are using rich server controls like GridView. For example, let's say you have List of Recalls in Model.Recalls, then you will show your tabular data as,     <%  GridView gv = new GridView();          gv.AutoGenerateColumns = true;          gv.DataSource = Model.Recalls;          gv.DataBind();         StringBuilder sb = new StringBuilder();         System.IO.StringWriter textwriter = new System.IO.StringWriter(sb);         HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);         gv.RenderControl(htmlwriter);%>            <%= sb.ToString() %>             This code might looks odd in your presentation view. A more better approach is to create a HTML Helper method which contains the above code. Summary :        In some cases you might needs to use existing ASP.NET Web Forms server controls but also dislikes ViewState. In this article i try to solve this gap by using the RenderControl method of Control class. Hopefully you enjoyed and become ready to create HTML helpers for many of the existing server controls.

    Read the article

  • Why does Javascript use JSON.stringify instead of JSON.serialize?

    - by Chase Florell
    I'm just wondering about "stringify" vs "serialize". To me they're the same thing (though I could be wrong), but in my past experience (mostly with asp.net) I use Serialize() and never use Stringify(). I know I can create a simple alias in Javascript, // either JSON.serialize = function(input) { return JSON.stringify(input); }; // or JSON.serialize = JSON.stringify; http://jsfiddle.net/HKKUb/ but I'm just wondering about the difference between the two and why stringify was chosen. for comparison purpose, here's how you serialize XML to a String in C# public static string SerializeObject<T>(this T toSerialize) { XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()); StringWriter textWriter = new StringWriter(); xmlSerializer.Serialize(textWriter, toSerialize); return textWriter.ToString(); }

    Read the article

1 2 3 4 5 6  | Next Page >