Search Results

Search found 110 results on 5 pages for 'xmlwriter'.

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

  • C# XMLWriter + prevent "/" "<" "<" chars

    - by flurreh
    Hello, I have a xmlWriter and want to write String which containt chars of "/" "<" "" (which are part of the xml syntax and break the xml code). Here is my c# code: public Boolean Initialize(String path) { Boolean result = true; XmlWriterSettings settings = new XmlWriterSettings(); settings.CheckCharacters = true; settings.Encoding = Encoding.UTF8; settings.Indent = true; xmlWriter = XmlWriter.Create(path, settings); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("TestData"); isInitialized = true; return result; } public void WriteProducts(List<Product> productList) { if (isInitialized == true) { foreach (Product product in productList) { xmlWriter.WriteStartElement("Product"); xmlWriter.WriteElementString("Id", product.ProdId); xmlWriter.WriteElementString("Name", product.ProdName); xmlWriter.WriteElementString("GroupId", product.ProdGroup); xmlWriter.WriteElementString("Price", product.ProdPrice.ToString((Consts.FORMATTED_PRICE))); xmlWriter.WriteEndElement(); } } } public void Close() { xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); } The application runs without any errors, but if I look in the xml file, the xml is incomplete because the xmlwriter stops writing the product nodes when a product name contains one of the above mentioned characters. Is there a way to fix this problem?

    Read the article

  • Combining XmlWriter objects?

    - by Kevin
    The way my application is structured, each component generates output as XML and returns an XmlWriter object. Before rendering the final output to the page, I combine all XML and perform an XSL transformation on that object. Below, is a simplified code sample of the application structure. Does it make sense to combine XmlWriter objects like this? Is there a better way to structure my application? The optimal solution would be one where I didn't have to pass a single XmlWriter instance as a parameter to each component. function page1Xml() { $content = new XmlWriter(); $content->openMemory(); $content->startElement('content'); $content->text('Sample content'); $content->endElement(); return $content; } function generateSiteMap() { $sitemap = new XmlWriter(); $sitemap->openMemory(); $sitemap->startElement('sitemap'); $sitemap->startElement('page'); $sitemap->writeAttribute('href', 'page1.php'); $sitemap->text('Page 1'); $sitemap->endElement(); $sitemap->endElement(); return $sitemap; } function output($content) { $doc = new XmlWriter(); $doc->openMemory(); $doc->writePi('xml-stylesheet', 'type="text/xsl" href="template.xsl"'); $doc->startElement('document'); $doc->writeRaw( generateSiteMap()->outputMemory() ); $doc->writeRaw( $content->outputMemory() ); $doc->endElement(); $doc->endDocument(); $output = xslTransform($doc); return $output; } $content = page1Xml(); echo output($content); Update: I may abandon XmlWriter altogether and use DomDocument instead. It is more flexible and it also seemed to perform better (at least on the crude tests I created).

    Read the article

  • How to export computers from Active Directory to XML using Powershell?

    - by CoDeRs
    I am trying to create a powershell scripts for Remote Desktop Connection Manager using the active directory module. My first thought was get a list of computers in AD and parse them out into XML format similar to the OU structure that is in AD. I have no problem with that, the below code will work just but not how I wanted. EG # here is a the array $OUs Americas/Canada/Canada Computers/Desktops Americas/Canada/Canada Computers/Laptops Americas/Canada/Canada Computers/Virtual Computers Americas/USA/USA Computers/Laptops Computers Disabled Accounts Domain Controllers EMEA/UK/UK Computers/Desktops EMEA/UK/UK Computers/Laptops Outside Sales and Service/Laptops Servers I wanted to have the basic XML structured like this Americas Canada Canada Computers Desktops Laptops Virtual Computers USA USA Computers Laptops Computers Disabled Accounts Domain Controllers EMEA UK UK Computers Desktops Laptops Outside Sales and Service Laptops Servers However if you run the below it does not nest the next string in the array it only restarts the from the beginning and duplicating Americas Canada Canada Computers Desktops Americas Canada Canada Computers Laptops Americas Canada Canada Computers Virtual Computers Americas USA USA Computers Laptops RDCMGenerator.ps1 #Importing Microsoft`s PowerShell-module for administering ActiveDirectory Import-Module ActiveDirectory #Initial variables $OUs = @() $RDCMVer = "2.2" $userName = "domain\username" $password = "Hashed Password+" $Path = "$env:temp\test.xml" $allComputers = Get-ADComputer -LDAPFilter "(OperatingSystem=*)" -Properties Name,Description,CanonicalName | Sort-Object CanonicalName | select Name,Description,CanonicalName $allOUObjects = $allComputers | Foreach {"$($_.CanonicalName)"} Function Initialize-XML{ ##<RDCMan schemaVersion="1"> $xmlWriter.WriteStartElement('RDCMan') $XmlWriter.WriteAttributeString('schemaVersion', '1') $xmlWriter.WriteElementString('version',$RDCMVer) $xmlWriter.WriteStartElement('file') $xmlWriter.WriteStartElement('properties') $xmlWriter.WriteElementString('name',$env:userdomain) $xmlWriter.WriteElementString('expanded','true') $xmlWriter.WriteElementString('comment','') $xmlWriter.WriteStartElement('logonCredentials') $XmlWriter.WriteAttributeString('inherit', 'None') $xmlWriter.WriteElementString('userName',$userName) $xmlWriter.WriteElementString('domain',$env:userdomain) $xmlWriter.WriteStartElement('password') $XmlWriter.WriteAttributeString('storeAsClearText', 'false') $XmlWriter.WriteRaw($password) $xmlWriter.WriteEndElement() $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('connectionSettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('gatewaySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('remoteDesktop') $XmlWriter.WriteAttributeString('inherit', 'None') $xmlWriter.WriteElementString('size','1024 x 768') $xmlWriter.WriteElementString('sameSizeAsClientArea','True') $xmlWriter.WriteElementString('fullScreen','False') $xmlWriter.WriteElementString('colorDepth','32') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('localResources') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('securitySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('displaySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteEndElement() } Function Create-Group ($groupName){ #Start Group $xmlWriter.WriteStartElement('properties') $xmlWriter.WriteElementString('name',$groupName) $xmlWriter.WriteElementString('expanded','true') $xmlWriter.WriteElementString('comment','') $xmlWriter.WriteStartElement('logonCredentials') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('connectionSettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('gatewaySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('remoteDesktop') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('localResources') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('securitySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('displaySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteEndElement() } Function Create-Server ($computerName, $computerDescription) { #Start Server $xmlWriter.WriteStartElement('server') $xmlWriter.WriteElementString('name',$computerName) $xmlWriter.WriteElementString('displayName',$computerDescription) $xmlWriter.WriteElementString('comment','') $xmlWriter.WriteStartElement('logonCredentials') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('connectionSettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('gatewaySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('remoteDesktop') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('localResources') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('securitySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteStartElement('displaySettings') $XmlWriter.WriteAttributeString('inherit', 'FromParent') $xmlWriter.WriteEndElement() $xmlWriter.WriteEndElement() #Stop Server } Function Close-XML { $xmlWriter.WriteEndElement() $xmlWriter.WriteEndElement() # finalize the document: $xmlWriter.Flush() $xmlWriter.Close() notepad $path } #Strip out Domain and Computer Name from CanonicalName foreach($OU in $allOUObjects){ $newSplit = $OU.split("/") $rebildOU = "" for($i=1; $i -le ($newSplit.count - 2); $i++){ $rebildOU += $newSplit[$i] + "/" } $OUs += $rebildOU.substring(0,($rebildOU.length - 1)) } #Remove Duplicate OU's $OUs = $OUs | select -uniq #$OUs # get an XMLTextWriter to create the XML $XmlWriter = New-Object System.XMl.XmlTextWriter($Path,$UTF8) # choose a pretty formatting: $xmlWriter.Formatting = 'Indented' $xmlWriter.Indentation = 1 $XmlWriter.IndentChar = "`t" # write the header $xmlWriter.WriteStartDocument() # # 'encoding', 'utf-8' How? # # set XSL statements #Initialize Pre-Defined XML Initialize-XML ######################################################### # Start Loop for each OU-Path that has a computer in it ######################################################### foreach ($OU in $OUs){ $totalGroupName = "" #Create / Reset Total OU-Path Completed $OU.split("/") | foreach { #Split the OU-Path into individual OU's $groupName = "$_" #Current OU $totalGroupName += $groupName + "/" #Total OU-Path Completed $xmlWriter.WriteStartElement('group') #Start new XML Group Create-Group $groupName #Call function to create XML Group ################################################ # Start Loop for each Computer in $allComputers ################################################ foreach($computer in $allComputers){ $computerOU = $computer.CanonicalName #Set the computers OU-Path $OUSplit = $computerOU.split("/") #Create the Split for the OU-Path $rebiltOU = "" #Create / Reset the stripped OU-Path for($i=1; $i -le ($OUSplit.count - 2); $i++){ #Start Loop for OU-Path to strip out the Domain and Computer Name $rebiltOU += $OUSplit[$i] + "/" #Rebuild the stripped OU-Path } if ($rebiltOU -eq $totalGroupName){ #Compare the Current OU-Path with the computers stripped OU-Path $computerName = $computer.Name #Set the computer name $computerDescription = $computerName + " - " + $computer.Description #Set the computer Description Create-Server $computerName $computerDescription #Call function to create XML Server } } } ################################################### # Start Loop to close out XML Groups created above ################################################### $totalGroupName.split("/") | foreach { #Split the if ($_ -ne "" ){ $xmlWriter.WriteEndElement() #End Group } } } Close-XML

    Read the article

  • XmlWriter and lower ASCII characters

    - by Rick Strahl
    Ran into an interesting problem today on my CodePaste.net site: The main RSS and ATOM feeds on the site were broken because one code snippet on the site contained a lower ASCII character (CHR(3)). I don't think this was done on purpose but it was enough to make the feeds fail. After quite a bit of debugging and throwing in a custom error handler into my actual feed generation code that just spit out the raw error instead of running it through the ASP.NET MVC and my own error pipeline I found the actual error. The lovely base exception and error trace I got looked like this: Error: '', hexadecimal value 0x03, is an invalid character. at System.Xml.XmlUtf8RawTextWriter.InvalidXmlChar(Int32 ch, Byte* pDst, Boolean entitize)at System.Xml.XmlUtf8RawTextWriter.WriteElementTextBlock(Char* pSrc, Char* pSrcEnd)at System.Xml.XmlUtf8RawTextWriter.WriteString(String text)at System.Xml.XmlWellFormedWriter.WriteString(String text)at System.Xml.XmlWriter.WriteElementString(String localName, String ns, String value)at System.ServiceModel.Syndication.Rss20FeedFormatter.WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)at System.ServiceModel.Syndication.Rss20FeedFormatter.WriteItem(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)at System.ServiceModel.Syndication.Rss20FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri)at System.ServiceModel.Syndication.Rss20FeedFormatter.WriteFeed(XmlWriter writer)at System.ServiceModel.Syndication.Rss20FeedFormatter.WriteTo(XmlWriter writer)at CodePasteMvc.Controllers.ApiControllerBase.GetFeed(Object instance) in C:\Projects2010\CodePaste\CodePasteMvc\Controllers\ApiControllerBase.cs:line 131 XML doesn't like extended ASCII Characters It turns out the issue is that XML in general does not deal well with lower ASCII characters. According to the XML spec it looks like any characters below 0x09 are invalid. If you generate an XML document in .NET with an embedded &#x3; entity (as mine did to create the error above), you tend to get an XML document error when displaying it in a viewer. For example, here's what the result of my  feed output looks like with the invalid character embedded inside of Chrome which displays RSS feeds as raw XML by default: Other browsers show similar error messages. The nice thing about Chrome is that you can actually view source and jump down to see the line that causes the error which allowed me to track down the actual message that failed. If you create an XML document that contains a 0x03 character the XML writer fails outright with the error: '', hexadecimal value 0x03, is an invalid character. The good news is that this behavior is overridable so XML output can at least be created by using the XmlSettings object when configuring the XmlWriter instance. In my RSS configuration code this looks something like this:MemoryStream ms = new MemoryStream(); var settings = new XmlWriterSettings() { CheckCharacters = false }; XmlWriter writer = XmlWriter.Create(ms,settings); and voila the feed now generates. Now generally this is probably NOT a good idea, because as mentioned above these characters are illegal and if you view a raw XML document you'll get validation errors. Luckily though most RSS feed readers however don't care and happily accept and display the feed correctly, which is good because it got me over an embarrassing hump until I figured out a better solution. How to handle extended Characters? I was glad to get the feed fixed for the time being, but now I was still stuck with an interesting dilemma. CodePaste.net accepts user input for code snippets and those code snippets can contain just about anything. This means that ASP.NET's standard request filtering cannot be applied to this content. The code content displayed is encoded before display so for the HTML end the CHR(3) input is not really an issue. While invisible characters are hardly useful in user input it's not uncommon that odd characters show up in code snippets. You know the old fat fingering that happens when you're in the middle of a coding session and those invisible characters do end up sometimes in code editors and then end up pasted into the HTML textbox for pasting as a Codepaste.net snippet. The question is how to filter this text? Looking back at the XML Charset Spec it looks like all characters below 0x20 (space) except for 0x09 (tab), 0x0A (LF), 0x0D (CR) are illegal. So applying the following filter with a RegEx should work to remove invalid characters:string code = Regex.Replace(item.Code, @"[\u0000-\u0008,\u000B,\u000C,\u000E-\u001F]", ""); Applying this RegEx to the code snippet (and title) eliminates the problems and the feed renders cleanly.© Rick Strahl, West Wind Technologies, 2005-2012Posted in .NET  XML   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How is it that the abstract class XmlWriter can be instantiated using XmlWriter.Create(... ?

    - by Cognize
    Hi, Just looking to clarify my understanding of the workings of the XmlWriter and abstract classes in general. My thinking is (was) that an abstract class can not be instantiated, although it can contain base methods that can be used by an inheriting class. So, while investigating XmlWriter, I find that to instantiate the XmlWriter, you call XmlWriter.Create(.... , which returns an instance of... XmlWriter, which can then be used: FileStream fs = new FileStream("XML.xml", FileMode.Create); XmlWriter w = XmlWriter.Create(fs); XmlSerializer xmlSlr = new XmlSerializer(typeof(TestClass)); xmlSlr.Serialize(fs, tsIn); This clearly works, as tested. Can anyone help me understand what is going on here. As far as I can see there is or should be no 'instance' to work with here??

    Read the article

  • How to avoid avoid linebreaks and spaces for XmlWellFormedWriter

    - by user302670
    Hi, i am getting an XmlWriter of the AppendChild() method of a xPathNavigator. using (XmlWriter writer = xPathNavigator.AppendChild()) { writer.WriteStartAttribute("name"); writer.WriteEndElement(); } The AppendChild() method returns a instance of XmlWellFormedWriter. I want to avoid linebreaks and spaces in my output xml. But the XmlWriterSettings are readonly and using an wrapper does not help anything. I tried this, but the setting of nether the wrapper nor the writer changes: XmlWriterSettings settings = new XmlWriterSettings(); settings.IndentChars = ""; settings.NewLineChars = ""; using (XmlWriter wrapper = xPathNavigator.AppendChild()) { XmlWriter writer = XmlWriter.Create(writer, settings); writer.WriteStartAttribute("name"); writer.WriteEndElement(); } Does anybody has an idea what todo? Thanks!

    Read the article

  • Combining XmlSerializer and XmlWriter?

    - by num3ric
    In addition to a list of objects I am serializing to an xml file using C#'s XmlSerializer, I would like to store a few more independent elements (mainly strings from textboxes) in the same xml. public static void SaveBehaviors(ObservableCollection<Param> listParams) { XmlSerializer _paramsSerializer = new XmlSerializer(listParams.GetType()); string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); path += "\\test.xml"; using (TextWriter writeFileStream = new StreamWriter(path)) { _paramsSerializer.Serialize(writeFileStream, listParams); using (XmlWriter writer = XmlWriter.Create(writeFileStream)) { writer.WriteStartElement("Foo"); //test entry... writer.WriteAttributeString("Bar", "Some & value"); writer.WriteElementString("Nested", "data"); writer.WriteEndElement(); } } } However, deserializing "test.xml" results in an error because of the added element. I suppose writing in the serialized xml file is prohibited and should be avoided?

    Read the article

  • Prevent Character Escape When Calling XmlWriter.WriteElementString

    - by Ibrar Afzal
    I have a string <entry key="Provider">Comcast Cable Communications, Inc.</entry> <entry key="Challenged">No</entry> I need to call the using xmlwriter.WriteElementString I need to what the string mentioned earlier. Problem here is the xwriter.WriteElementString will escape all "<" and "" symbols with &lt and &gt. I have checked MSDN to see if there is a way to disable it, but have not found an answer. Is there a way to disable the auto-escape features?

    Read the article

  • Prevent Character Escape When Calling xmlwriter.xwriter.WriteElementString, C%

    - by Ibrar Afzal
    I have a string <entry key="Provider">Comcast Cable Communications, Inc.</entry> <entry key="Challenged">No</entry> I need to call the using xmlwriter..WriteElementString I need to what the string mentioned earler. Problem here is the xwriter.WriteElementString will escape all "<" and "" symbols with &lt and &gt. I have checked MSDN to see if there is a way to disable it, but have not found an answer. Is there a way to disable the auto-escape features?

    Read the article

  • Can anyone tell me why my XML writer is not writing attributes?

    - by user1632018
    I am writing a parsing tool to help me clean up a large VC++ project before I make .net bindings for it. I am using an XML writer to read an xml file and write out each element to a new file. If an element with a certain name is found, then it executes some code and writes an output value into the elements value. So far it is almost working, except for one thing: It is not copying the attributes. Can anyone tell me why this is happening? Here is a sample of what it is supposed to copy/modify(Includes the attributes): <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{57900E99-A405-49F4-83B2-0254117D041B}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>libproj</RootNamespace> </PropertyGroup> Here is the output I am getting(No Attributes): <?xml version="1.0" encoding="utf-8"?> <Project> <ItemGroup> <ProjectConfiguration> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup> <ProjectGuid>{57900E99-A405-49F4-83B2-0254117D041B}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>libproj</RootNamespace> Here is my code currently. I have tried every way I can come up with to write the attributes. string baseDir = (textBox2.Text + "\\" + safeFileName); string vcName = Path.GetFileName(textBox1.Text); string vcProj = Path.Combine(baseDir, vcName); using (XmlReader reader = XmlReader.Create(textBox1.Text)) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.Indent = true; settings.CloseOutput = false; using (XmlWriter writer = XmlWriter.Create(vcProj, settings)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "ClInclude") { string include = reader.GetAttribute("Include"); string dirPath = Path.GetDirectoryName(textBox1.Text); Directory.SetCurrentDirectory(dirPath); string fullPath = Path.GetFullPath(include); //string dirPath = Path.GetDirectoryName(fullPath); copyFile(fullPath, 3); string filename = Path.GetFileName(fullPath); writer.WriteStartElement(reader.Name); writer.WriteAttributeString("Include", "include/" + filename); writer.WriteEndElement(); } else if (reader.Name == "ClCompile" && reader.HasAttributes) { string include = reader.GetAttribute("Include"); string dirPath = Path.GetDirectoryName(textBox1.Text); Directory.SetCurrentDirectory(dirPath); string fullPath = Path.GetFullPath(include); copyFile(fullPath, 2); string filename = Path.GetFileName(fullPath); writer.WriteStartElement(reader.Name); writer.WriteAttributeString("Include", "src/" + filename); writer.WriteEndElement(); } else { writer.WriteStartElement(reader.Name); } break; case XmlNodeType.Text: writer.WriteString(reader.Value); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: writer.WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: writer.WriteComment(reader.Value); break; case XmlNodeType.Attribute: writer.WriteAttributes(reader, true); break; case XmlNodeType.EntityReference: writer.WriteEntityRef(reader.Value); break; case XmlNodeType.EndElement: writer.WriteFullEndElement(); break; } } } }

    Read the article

  • Is there any way that an export-to-Excel function can be scalable?

    - by MusiGenesis
    Summary: ASP.Net website with a couple hundred users. Data is exported to Excel files which can be relatively large (~5 MB). In the pilot phase (just a few users), we are already seeing occasional errors on the server in the exporting method. Here's the stack trace: System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. --- System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.IO.MemoryStream.set_Capacity(Int32 value) at System.IO.MemoryStream.EnsureCapacity(Int32 value) at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.TrackingMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.SparseMemoryStream.WriteAndCollapseBlocks(Byte[ ] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.SparseMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.CompressEmulationStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.CompressStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Write(Byte[] buffer, Int32 offset, Int32 count) at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.IO.StreamWriter.Write(String value) at System.Xml.XmlTextEncoder.Write(String text) at System.Xml.XmlTextWriter.WriteString(String text) at System.Xml.XmlText.WriteTo(XmlWriter w) at System.Xml.XmlAttribute.WriteContentTo(XmlWriter w) at System.Xml.XmlAttribute.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlDocument.WriteContentTo(XmlWriter xw) at System.Xml.XmlDocument.WriteTo(XmlWriter w) at System.Xml.XmlDocument.Save(Stream outStream) at OfficeOpenXml.ExcelWorksheet.Save() in C:\temp\XXXXXXXXXX\ExcelPackage\ExcelWorksheet.cs:line 605 at OfficeOpenXml.ExcelWorkbook.Save() in C:\temp\XXXXXXXXXX\ExcelPackage\ExcelWorkbook.cs:line 439 at OfficeOpenXml.ExcelPackage.Save() in C:\temp\XXXXXXXXXX\ExcelPackage\ExcelPackage.cs:line 348 at Framework.Exporting.Business.ExcelExport.BuildReport(HttpContext context) at WebUserControl.BtnXLS_Click(Object sender, EventArgs e) in C:\TEMP\XXXXXXXXXX\XXXXXXXXXX\OneList\UserControls\TicketReportExporter. ascx.cs:line 108 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.Rai sePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.XXXXXXXXXXX_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\XXXX\cdf32a52\d1a5eabd\App_Web_enxdwlks.1.cs:line 0 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpAppli cation.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Even aside from this particular problem, in general exporting to Excel requires the instantiation of huge Excel objects on the server for each request, which I've always assumed to mean disqualifies Excel for "serious" work on a highly-loaded server. Is there any general way to export to Excel in a "light-weight" manner? Would simply streaming the data into a CSV file work for this?

    Read the article

  • Best approach to write huge xml data to file?

    - by Kayes
    Hi. I'm currently exporting a database table with huge data (100000+ records) into an xml file using XmlTextWriter class and I'm writing directly to a file on the physical drive. _XmlTextWriterObject = new XmlTextWriter(_xmlFilePath, null); While my code runs ok, my question is that is it the best approach? Or should I write the whole xml in memory stream first and then write the xml document in physical file from memory stream? And what are the effects on memory/ performance in both cases?

    Read the article

  • File writing problem on Windows 7 Professional in c#

    - by Ummar
    I have an application in C# which I write some data to file. I am facing the problem on windows 7 professional that when I write data to C:\ProgramData, Access denied acception is thrown. If I login from an administrator account this issue vanishes, and if I login from some other account who have administrative previlages this issue comes up. This issue is only produces on windows 7 professional, it is working fine on all other flavors of windows 7 as well as windows vista. try { XmlTextWriter myXmlTextWriter = new XmlTextWriter("Configuration.xml", null); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartDocument(true); myXmlTextWriter.WriteDocType("ApplicationConfigurations", null, null, null); ////myXmlTextWriter.WriteComment("This file represents another fragment of a book store inventory database"); myXmlTextWriter.WriteStartElement("Configuration"); myXmlTextWriter.WriteElementString("firstElement", pe.ToString()); myXmlTextWriter.WriteEndElement(); myXmlTextWriter.WriteEndDocument(); myXmlTextWriter.Flush(); myXmlTextWriter.Close(); }catch(Exception e) { //Exception is thrown in Win7 professional }

    Read the article

  • A reasonable way to add attributes to an xml root element.

    - by DrLazer
    The function "WriteStartElement" does not return anything. I find this a little bizzare. So up until now I have been doing it like this. XmlDocument xmlDoc = new XmlDocument(); XmlTextWriter xmlWriter = new XmlTextWriter(m_targetFilePath, System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("client"); xmlWriter.Close(); xmlDoc.Load(m_targetFilePath); XmlElement root = xmlDoc.DocumentElement; Saving the doc, then reloading it to get hold of the start element so i can write attributes to it. Does anybody know the correct way of doing this because I'm pretty sure what I'm doing isn't right. I tried to use xmlWriter.AppendChild() but it doesnt seem to write out anything. :(

    Read the article

  • A reasonable way to add attributes to an xml root element in C#.

    - by DrLazer
    The function "WriteStartElement" does not return anything. I find this a little bizzare. So up until now I have been doing it like this. XmlDocument xmlDoc = new XmlDocument(); XmlTextWriter xmlWriter = new XmlTextWriter(m_targetFilePath, System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("client"); xmlWriter.Close(); xmlDoc.Load(m_targetFilePath); XmlElement root = xmlDoc.DocumentElement; Saving the doc, then reloading it to get hold of the start element so i can write attributes to it. Does anybody know the correct way of doing this because I'm pretty sure what I'm doing isn't right. I tried to use xmlWriter.AppendChild() but it doesnt seem to write out anything. :(

    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

  • handle null values for string when implementing IXmlSerializable interface

    - by user208081
    I have the following class that implements IXmlSerializable. When implementing WriteXml(), I need to handle the case where the string members of this class may be null values. What is the best way of handling this? Currently, I am using the default constructor in which all the string properties are initialized to empty string values. This way, when WriteXml() is called, the string will not be null. One other way I could do this is check using String.IsNullOrEmpty before writing each string in xml. Any suggestions on how I can improve this code? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Globalization; namespace TCS.Common.InformationObjects { public sealed class FaxSender : IXmlSerializable { #region Public Constants private const string DEFAULT_CLASS_NAME = "FaxSender"; #endregion Public Constants #region Public Properties public string Name { get; set; } public string Organization { get; set; } public string PhoneNumber { get; set; } public string FaxNumber { get; set; } public string EmailAddress { get; set; } #endregion Public Properties #region Public Methods #region Constructors public FaxSender() { Name = String.Empty; Organization = String.Empty; PhoneNumber = String.Empty; FaxNumber = String.Empty; EmailAddress = String.Empty; } public FaxSender(string name, string organization, string phoneNumber, string faxNumber, string emailAddress) { Name = name; Organization = organization; PhoneNumber = phoneNumber; FaxNumber = faxNumber; EmailAddress = emailAddress; } #endregion Constructors #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(System.Xml.XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(System.Xml.XmlWriter xmlWriter) { try { // <sender> xmlWriter.WriteStartElement("sender"); // Write the name of the sender as an element. xmlWriter.WriteElementString("name", this.Name.ToString(CultureInfo.CurrentCulture)); // Write the organization of the sender as an element. xmlWriter.WriteElementString("organization", this.Organization.ToString(CultureInfo.CurrentCulture)); // Write the phone number of the sender as an element. xmlWriter.WriteElementString("phone_number", this.PhoneNumber.ToString(CultureInfo.CurrentCulture)); // Write the fax number of the sender as an element. xmlWriter.WriteElementString("fax_number", this.FaxNumber.ToString(CultureInfo.CurrentCulture)); // Write the email address of the sender as an element. xmlWriter.WriteElementString("email_address", this.EmailAddress.ToString(CultureInfo.CurrentCulture)); // </sender> xmlWriter.WriteEndElement(); } catch { // Rethrow any exceptions. throw; } } #endregion IXmlSerializable Members #endregion Public Methods } }

    Read the article

  • WorkflowMarkupSerializer doesn't keep positions in a state machine workflow

    - by Khadaji
    I am using WorkflowMarkupSerializer to save a statemachine workflow - it saves the states OK, but does not keep their positions. The code to write the workflow is here: using (XmlWriter xmlWriter = XmlWriter.Create(fileName)) { WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer(); markupSerializer.Serialize(xmlWriter, workflow); } The code to read the workflow is: DesignerSerializationManager dsm = new DesignerSerializationManager(); using (dsm.CreateSession()) { using (XmlReader xmlReader = XmlReader.Create(fileName)) { //deserialize the workflow from the XmlReader WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer(); workflow = markupSerializer.Deserialize( dsm, xmlReader) as Activity; if (dsm.Errors.Count > 0) { WorkflowMarkupSerializationException error = dsm.Errors[0] as WorkflowMarkupSerializationException; throw error; } } }

    Read the article

  • Reading and writing XML over an SslStream

    - by Mark
    I want to read and write XML data over an SslStream. The data (written and read) consists of objects serialized by an XmlSerializer. I have tried the following; (left some details out for clarity!) TcpClient tcpClient = new TcpClient(server, port); SslStream sslStream = new SslStream(tcpClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(server); XmlReader xmlReader = XmlReader.Create(sslStream,readerSettings); XmlWriter xmlWriter = XmlWriter.Create(sslStream,writerSettings); myClass c = new myClass (); XmlSerializer serializer = new XmlSerializer(typeof(myClass)); serializer.Serialize(xmlWriter, c); myClass c2 = (myClass )serializer.Deserialize(xmlReader); First of all, it appears that writing to the stream succeeds. But the XmlSerializer throws an error because of invalid XML. It appears that the first character read from the stream is '00' or a null-character. (I have googled this problem, and see a million people with the same 'problem', but no viable solution.) I can work around this 'issue' by using a StreamReader, read everything into a string and then use that string as input for another stream that the serializer can use. (Very dirty, but it works.) Second problem is, that when I try to use the same SslStream to write a second request, I do not get a response from the Reader. (The server DOES send a valid XML response though!) So the serializer.Serialize(xmlWriter, c3) works, but reading from the stream yields no results. I have tried several different classes that implement Stream. (StreamReader, XmlTextReader, etc.) Anyone has an idea how reading and writing XML data to and from an SslStream is supposed to work? Thanks in advance!

    Read the article

  • Converting a C# DataTable instance to xml that contains HTML or binary data

    - by Wardy
    Hmmmm ... Although it works in most cases, one column has html data in it. It seems that doing this ... StringBuilder xmltarget = new StringBuilder(); XmlWriter xmlWriter = XmlWriter.Create(xmltarget); tableData.WriteXml(xmlWriter); ... doesn't identify where this html or binary data exists and wrap the data in cdata tags as it should ... Is there something i need to do to ensure the relevant checks are made and a working xml string is produced?

    Read the article

  • i m trying to return list<object> from webmethod but gives error

    - by girish
    System.InvalidOperationException: There was an error generating the XML document. --- System.InvalidOperationException: The type WebService.Property.Property_Users was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write8_ArrayOfAnyType(Object o) at Microsoft.Xml.Serialization.GeneratedAssembly.ListOfObjectSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer) at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) --- End of inner exception stack trace --- at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o) at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue) at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream) at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues) at System.Web.Services.Protocols.WebServiceHandler.Invoke() public List<object> GetDataByModuleName(string ModuleName) { List<Property_Users> obj_UserList = new List<Property_Users>(); // performing some operation that add data to obj_UserList List < Object > myList = new List<object>(); return ConvertToObjectList<Property_Users>(obj_UserList); } public List<Object> ConvertToObjectList<N>(List<N> sourceList) { List<Object> result = new List<Object>(); foreach (N item in sourceList) { result.Add(item as Object); } return result; } [WebMethod] public List<object> GetDataByModuleName(string ModuleName) { List<object> obj_list = new List<object>(); obj_list = BAL_GeneralService.GetDataByModuleName(ModuleName); return obj_list; }

    Read the article

  • Using LinqExtender to make OData feed fails

    - by BurningIce
    A pretty simple question, has anyone here tried to make a OData feed based on a IQueryable created with LinqExtender? I have created a simple Linq-provider that supports Where, Select, OrderBy and Take and wanted to expose it as an OData Feed. I keep getting an error though, and the Exception is a NullReference with the following StackTrace at System.Data.Services.Serializers.Serializer.GetObjectKey(Object resource, IDataServiceProvider provider, String containerName) at System.Data.Services.Serializers.Serializer.GetUri(Object resource, IDataServiceProvider provider, ResourceContainer container, Uri absoluteServiceUri) at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, Type expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target) at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__0.MoveNext() at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer) at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved) at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved) at System.Data.Services.ResponseBodyWriter.Write(Stream stream) I've kinda narrowed it down to a issue where LinqExtender wraps every returned object, so that my object actually inherits itself - thats at least how it looks like in the debugger. These two queries are basicly the same. The first is the legacy-api where the OrderBy and Select is regular Linq to Objects. The second query is a "real" linq-provider made with LinqExtender. var db = CalendarDataProvider.GetCalendarEntriesByDate(DateTime.Now, DateTime.Now.AddMonths(1), Guid.Empty) .OrderBy(o => o.Title) .Select(o => new ODataCalendarEntry(o)); var query = new ODataCalendarEntryQuery() .Where(o => o.Start > DateTime.Now && o.End < DateTime.Now.AddMonths(1)) .OrderBy(o => o.Title); When returning db for the OData feed everything is fine, but returning query throws a NullRefenceException. I've tried all kind of tricks and even tried to project all the data into a new object like this, but still the same error return query.Select(o => new ODataCalendarEntry { Title = o.Title, Start = o.Start, End = o.End, Name = o.Name });

    Read the article

1 2 3 4 5  | Next Page >