Flush() public method

public Flush ( ) : void
return void
Example #1
1
        // Creates XmlDocument from html content and return it with rootitem "<root>".
        public static XmlDocument ParseHtml(string sContent)
        {
            StringReader sr = new StringReader("<root>" + sContent + "</root>");
            SgmlReader reader = new SgmlReader();
            reader.WhitespaceHandling = WhitespaceHandling.All;
            reader.CaseFolding = Sgml.CaseFolding.ToLower;
            reader.InputStream = sr;

            StringWriter sw = new StringWriter();
            XmlTextWriter w = new XmlTextWriter(sw);
            w.Formatting = Formatting.Indented;
            w.WriteStartDocument();
            reader.Read();
            while (!reader.EOF)
            {
                w.WriteNode(reader, true);
            }
            w.Flush();
            w.Close();

            sw.Flush();

            // create document
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.XmlResolver = null;
            doc.LoadXml(sw.ToString());

            reader.Close();

            return doc;
        }
Example #2
1
        private bool SaveRegister(string RegisterKey)
        {
            try
            {
                
                Encryption enc = new Encryption();
                FileStream fs = new FileStream("reqlkd.dll", FileMode.Create);
                XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);

                // Khởi động tài liệu.
                w.WriteStartDocument();
                w.WriteStartElement("QLCV");

                // Ghi một product.
                w.WriteStartElement("Register");
                w.WriteAttributeString("GuiNumber", enc.EncryptData(sGuiID));
                w.WriteAttributeString("Serialnumber", enc.EncryptData(sSerial));
                w.WriteAttributeString("KeyRegister", enc.EncryptData(RegisterKey, sSerial + sGuiID));
                w.WriteEndElement();

                // Kết thúc tài liệu.
                w.WriteEndElement();
                w.WriteEndDocument();
                w.Flush();
                w.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }
Example #3
1
        /// <summary>
        /// Define o valor de uma configuração
        /// </summary>
        /// <param name="file">Caminho do arquivo (ex: c:\program.exe.config)</param>
        /// <param name="key">Nome da configuração</param>
        /// <param name="value">Valor a ser salvo</param>
        /// <returns></returns>
        public static bool SetValue(string file, string key, string value)
        {
            var fileDocument = new XmlDocument();
            fileDocument.Load(file);
            var nodes = fileDocument.GetElementsByTagName(AddElementName);

            if (nodes.Count == 0)
            {
                return false;
            }

            for (var i = 0; i < nodes.Count; i++)
            {
                var node = nodes.Item(i);
                if (node == null || node.Attributes == null || node.Attributes.GetNamedItem(KeyPropertyName) == null)
                    continue;
                
                if (node.Attributes.GetNamedItem(KeyPropertyName).Value == key)
                {
                    node.Attributes.GetNamedItem(ValuePropertyName).Value = value;
                }
            }

            var writer = new XmlTextWriter(file, null) { Formatting = Formatting.Indented };
            fileDocument.WriteTo(writer);
            writer.Flush();
            writer.Close();
            return true;
        }
Example #4
0
        public override string ToString()
        {
            string doc;

            using (var sw = new StringWriter()) {
                using (var writer = new XmlTextWriter(sw)) {
                    writer.Formatting = Formatting.Indented;
                    //writer.WriteStartDocument();
                    writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
                    writer.WriteStartElement("D", "multistatus", "DAV:");
                    for (int i = 0; i < _nameSpaceList.Count; i++) {
                        string tag = string.Format("ns{0}", i);
                        writer.WriteAttributeString("xmlns", tag, null, _nameSpaceList[i]);
                    }

                    foreach (var oneResponse in _ar) {
                        oneResponse.Xml(writer);
                    }
                    writer.WriteEndElement();
                    //writer.WriteEndDocument();
                    writer.Flush();
                    writer.Close();
                    doc = sw.ToString();
                    writer.Flush();
                    writer.Close();
                }
                sw.Flush();
                sw.Close();
            }
            return doc;
        }
    /// <summary>Handle an HTTP request containing an XML-RPC request.</summary>
    /// <remarks>This method deserializes the XML-RPC request, invokes the 
    /// described method, serializes the response (or fault) and sends the XML-RPC response
    /// back as a valid HTTP page.
    /// </remarks>
    /// <param name="httpReq"><c>SimpleHttpRequest</c> containing the request.</param>
    public void Respond(SimpleHttpRequest httpReq)
      {
	XmlRpcRequest xmlRpcReq = (XmlRpcRequest)_deserializer.Deserialize(httpReq.Input);
	XmlRpcResponse xmlRpcResp = new XmlRpcResponse();

	try
	  {
	    xmlRpcResp.Value = _server.Invoke(xmlRpcReq);
	  }
	catch (XmlRpcException e)
	  {
	    xmlRpcResp.SetFault(e.FaultCode, e.FaultString);
	  }
	catch (Exception e2)
	  {
	    xmlRpcResp.SetFault(XmlRpcErrorCodes.APPLICATION_ERROR, 
			  XmlRpcErrorCodes.APPLICATION_ERROR_MSG + ": " + e2.Message);
	  }

	if (Logger.Delegate != null)
	  Logger.WriteEntry(xmlRpcResp.ToString(), LogLevel.Information);

	XmlRpcServer.HttpHeader(httpReq.Protocol, "text/xml", 0, " 200 OK", httpReq.Output);
	httpReq.Output.Flush();
	XmlTextWriter xml = new XmlTextWriter(httpReq.Output);
	_serializer.Serialize(xml, xmlRpcResp);
	xml.Flush();
	httpReq.Output.Flush();
      }
Example #6
0
        /// <summary>
        /// Saves settings to an XML file
        /// </summary>
        /// <param name="file">The file to save to</param>
        internal static void SaveSettings(string file)
        {
            try
            {
                // Open writer
                System.Xml.XmlTextWriter xmlwriter = new System.Xml.XmlTextWriter(file, System.Text.Encoding.Default);
                xmlwriter.Formatting = System.Xml.Formatting.Indented;

                // Start document
                xmlwriter.WriteStartDocument();
                xmlwriter.WriteStartElement("KMLImporter");

                // ShowAllLabels
                xmlwriter.WriteStartElement("ShowAllLabels");
                xmlwriter.WriteString(ShowAllLabels.ToString(CultureInfo.InvariantCulture));
                xmlwriter.WriteEndElement();

                // End document
                xmlwriter.WriteEndElement();
                xmlwriter.WriteEndDocument();

                // Close writer
                xmlwriter.Flush();
                xmlwriter.Close();
            }
            catch (System.IO.IOException)
            { }
            catch (System.Xml.XmlException)
            { }
        }
        private static string PrepareComponentUpdateXml(string xmlpath, IDictionary<string, string> paths)
        {
            string xml = File.ReadAllText(xmlpath);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("avm", "avm");
            manager.AddNamespace("cad", "cad");

            XPathNavigator navigator = doc.CreateNavigator();
            var resourceDependencies = navigator.Select("/avm:Component/avm:ResourceDependency", manager).Cast<XPathNavigator>()
                .Concat(navigator.Select("/avm:Component/ResourceDependency", manager).Cast<XPathNavigator>());
            
            foreach (XPathNavigator node in resourceDependencies)
            {
                string path = node.GetAttribute("Path", "avm");
                if (String.IsNullOrWhiteSpace(path))
                {
                    path = node.GetAttribute("Path", "");
                }
                string newpath;
                if (paths.TryGetValue(node.GetAttribute("Name", ""), out newpath))
                {
                    node.MoveToAttribute("Path", "");
                    node.SetValue(newpath);
                }
            }
            StringBuilder sb = new StringBuilder();
            XmlTextWriter w = new XmlTextWriter(new StringWriter(sb));
            doc.WriteContentTo(w);
            w.Flush();
            return sb.ToString();
        }
 /// <summary>
 /// Creates an instance of the given type from the specified Internet resource.
 /// </summary>
 /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
 /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
 /// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param>
 /// <param name="type">The requested type.</param>
 /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
 /// <returns>An newly created instance.</returns>
 public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type,
                              string xmlPath)
 {
     StringWriter sw = new StringWriter();
     XmlTextWriter writer = new XmlTextWriter(sw);
     if (xsltUrl == null)
     {
         LoadHtmlAsXml(htmlUrl, writer);
     }
     else
     {
         if (xmlPath == null)
         {
             LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer);
         }
         else
         {
             LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath);
         }
     }
     writer.Flush();
     StringReader sr = new StringReader(sw.ToString());
     XmlTextReader reader = new XmlTextReader(sr);
     XmlSerializer serializer = new XmlSerializer(type);
     object o;
     try
     {
         o = serializer.Deserialize(reader);
     }
     catch (InvalidOperationException ex)
     {
         throw new Exception(ex + ", --- xml:" + sw);
     }
     return o;
 }
Example #9
0
        private void GenerateDescription(string host = null)
        {
            MemoryStream memStream = new MemoryStream();
            using (XmlTextWriter descWriter = new XmlTextWriter(memStream, new UTF8Encoding(false)))
            {
                descWriter.Formatting = Formatting.Indented;
                descWriter.WriteRaw("<?xml version=\"1.0\"?>");

                descWriter.WriteStartElement("root", "urn:schemas-upnp-org:device-1-0");

                descWriter.WriteStartElement("specVersion");
                descWriter.WriteElementString("major", "1");
                descWriter.WriteElementString("minor", "0");
                descWriter.WriteEndElement();

                descWriter.WriteStartElement("device");
                rootDevice.WriteDescription(descWriter, host);
                descWriter.WriteEndElement();

                descWriter.WriteEndElement();

                descWriter.Flush();
                descArray = memStream.ToArray();
            }
        }
Example #10
0
        private void WriteFeed(IEnumerable<DonaldEpisode> episodes, Stream responseStream, string url)
        {
            XmlTextWriter objX = new XmlTextWriter(responseStream, Encoding.UTF8);
            objX.WriteStartDocument();
            objX.WriteStartElement("rss");
            objX.WriteAttributeString("version", "2.0");
            objX.WriteStartElement("channel");
            objX.WriteElementString("title", "Donald Inc.");
            objX.WriteElementString("link", url);
            objX.WriteElementString("description",
                                    "Your custom donald feed!");
            objX.WriteElementString("copyright", "(c) 2011, Chuck Norris.");
            objX.WriteElementString("ttl", "5");
            foreach (var episode in episodes)
            {
                objX.WriteStartElement("item");
                objX.WriteElementString("title", episode.Title);
                objX.WriteElementString("description", episode.Content);
                objX.WriteElementString("link",
                                        Configuration.ApiUri + "/" + episode.Id);
                objX.WriteElementString("pubDate", episode.ReleaseDate.Value.ToString("R"));
                objX.WriteStartElement("enclosure");
                objX.WriteAttributeString("url", Configuration.ApiUri + "/" + episode.Id + "/jpg");
                objX.WriteAttributeString("type", "application/jpg");
                objX.WriteEndElement();
                objX.WriteEndElement();
            }

            objX.WriteEndElement();
            objX.WriteEndElement();
            objX.WriteEndDocument();
            objX.Flush();
        }
Example #11
0
        public static string ConvertToXml(string pXmlString)
        {
            string Result = "";
            MemoryStream mStream = null;
            XmlTextWriter writer = null;
            XmlDocument document = new XmlDocument();;

            try
            {
                document.LoadXml(pXmlString);
                mStream = new MemoryStream();
                writer = new XmlTextWriter(mStream, Encoding.Unicode);
                writer.Formatting = Formatting.Indented;

                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();
                mStream.Position = 0;

                StreamReader sReader = new StreamReader(mStream);
                String FormattedXML = sReader.ReadToEnd();
                Result = FormattedXML;
            }
            catch { }

            if (mStream != null)
                mStream.Close();
            if (writer != null)
                writer.Close();

            return Result;
        }
Example #12
0
        static void ImportXMLfile(int popMember)
        {
            string filename = "";

            filename = GlobalVar.jobName + GlobalVar.popIndex.ToString() + popMember.ToString();

            XmlTextWriter xml = null;

            xml = new XmlTextWriter(filename, null);

            xml.WriteStartDocument();
            xml.WriteStartElement("Features");
            xml.WriteWhitespace("\n");

            for (int i = 0; i < GlobalVar.featureCount; i++)
            {
                xml.WriteElementString("Index", i.ToString());
                xml.WriteElementString("Value", GlobalVar.features[i].ToString());
                xml.WriteWhitespace("\n  ");
            }

            xml.WriteEndElement();
            xml.WriteWhitespace("\n");

            xml.WriteEndDocument();

            //Write the XML to file and close the writer.
            xml.Flush();
            xml.Close();
        }
Example #13
0
        protected internal virtual string SerializeSection(ConfigurationElement parentElement, string name,
            ConfigurationSaveMode saveMode)
        {
            if ((CurrentConfiguration != null) &&
                (CurrentConfiguration.TargetFramework != null) &&
                !ShouldSerializeSectionInTargetVersion(CurrentConfiguration.TargetFramework))
                return string.Empty;

            ValidateElement(this, null, true);

            ConfigurationElement tempElement = CreateElement(GetType());
            tempElement.Unmerge(this, parentElement, saveMode);

            StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture);
            XmlTextWriter writer = new XmlTextWriter(strWriter)
            {
                Formatting = Formatting.Indented,
                Indentation = 4,
                IndentChar = ' '
            };

            tempElement.DataToWriteInternal = saveMode != ConfigurationSaveMode.Minimal;

            if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null))
                _configRecord.SectionsStack.Push(this);

            tempElement.SerializeToXmlElement(writer, name);

            if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null))
                _configRecord.SectionsStack.Pop();

            writer.Flush();
            return strWriter.ToString();
        }
        public static String FormatXml(String value)
        {
            using (var mStream = new MemoryStream())
            {
                using (var writer = new XmlTextWriter(mStream, Encoding.Unicode) { Formatting = System.Xml.Formatting.Indented})
                {
                    var document = new XmlDocument();
                    try
                    {
                        document.LoadXml(value);

                        document.WriteContentTo(writer);
                        writer.Flush();
                        mStream.Flush();

                        mStream.Position = 0;
                        var sReader = new StreamReader(mStream);

                        return sReader.ReadToEnd();
                    }
                    catch (XmlException)
                    {
                    }
                }
            }
            return value;
        }
        public void WriteResponseToStream(LegacyResponse legacyResponse, Stream writeStream)
        {
            var request = legacyResponse.Request;

            var body = request.GetSoapBody();
            var operationElement = _legacyMessageParser.GetOperationElement(body);
            var operationElementName = operationElement.Name;
            var namespaceName = operationElementName.NamespaceName;
            var operationName = operationElementName.LocalName;

            var operationResultInnerElement = new XElement(
                string.Concat("{", namespaceName, "}", operationName, "Result"));

            var processResult = legacyResponse.ProcessingResult;
            if (processResult != null)
            {
                operationResultInnerElement.Add(processResult);
            }

            var operationResultOuterElement = new XElement(
                string.Concat("{", namespaceName, "}", operationName, "Response"));
            operationResultOuterElement.Add(operationResultInnerElement);

            operationElement.ReplaceWith(operationResultOuterElement);

            using (var outWriter = new XmlTextWriter(writeStream, Encoding.UTF8))
            {
                request.WriteTo(outWriter);
                outWriter.Flush();
            }
        }
        public object Search(queryrequest xml)
        {
            SemWeb.Query.Query query = null;

            string q = string.Empty;

            try
            {
                query = new SparqlEngine(new StringReader(xml.query));
            }
            catch (QueryFormatException ex)
            {
                var malformed = new malformedquery();

                malformed.faultdetails = ex.Message;

                return malformed;
            }

            // Load the data from sql server
            SemWeb.Stores.SQLStore store;

            string connstr = ConfigurationManager.ConnectionStrings["SemWebDB"].ConnectionString;

            DebugLogging.Log(connstr);

            store = (SemWeb.Stores.SQLStore)SemWeb.Store.CreateForInput(connstr);

            //Create a Sink for the results to be writen once the query is run.
            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
            QueryResultSink sink = new SparqlXmlQuerySink(writer);

            try
            {
                // Run the query.
                query.Run(store, sink);

            }
            catch (Exception ex)
            {
                // Run the query.
                query.Run(store, sink);
                DebugLogging.Log("Run the query a second time");
                DebugLogging.Log(ex.Message);

            }
            //flush the writer then  load the memory stream
            writer.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            //Write the memory stream out to the response.
            ASCIIEncoding ascii = new ASCIIEncoding();
            DebugLogging.Log(ascii.GetString(ms.ToArray()).Replace("???", ""));
            writer.Close();

            DebugLogging.Log("End of Processing");

            return SerializeXML.DeserializeObject(ascii.GetString(ms.ToArray()).Replace("???", ""), typeof(sparql)) as sparql;
        }
Example #17
0
        /// <summary>
        /// Attempt to get the list of character types.
        /// </summary>
        public bool GetCharacterTypes()
        {
            omaeSoapClient objService = _objOmaeHelper.GetOmaeService();

            try
            {
                MemoryStream objStream = new MemoryStream();
                XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

                objService.GetCharacterTypes().WriteTo(objWriter);
                // Flush the output.
                objWriter.Flush();
                objStream.Flush();

                XmlDocument objXmlDocument = _objOmaeHelper.XmlDocumentFromStream(objStream);

                // Close everything now that we're done.
                objWriter.Close();
                objStream.Close();

                // Stuff all of the items into a ListItem List.
                foreach (XmlNode objNode in objXmlDocument.SelectNodes("/types/type"))
                {
                    ListItem objItem = new ListItem();
                    objItem.Value = objNode["id"].InnerText;
                    objItem.Name = objNode["name"].InnerText;
                    _lstCharacterTypes.Add(objItem);
                }

                // Add an item for Official NPCs.
                ListItem objNPC = new ListItem();
                objNPC.Value = "4";
                objNPC.Name = "Official NPC Packs";
                _lstCharacterTypes.Add(objNPC);

                // Add an item for Custom Data.
                ListItem objData = new ListItem();
                objData.Value = "data";
                objData.Name = "Data";
                _lstCharacterTypes.Add(objData);

                // Add an item for Character Sheets.
                ListItem objSheets = new ListItem();
                objSheets.Value = "sheets";
                objSheets.Name = "Character Sheets";
                _lstCharacterTypes.Add(objSheets);

                cboCharacterTypes.Items.Clear();
                cboCharacterTypes.DataSource = _lstCharacterTypes;
                cboCharacterTypes.ValueMember = "Value";
                cboCharacterTypes.DisplayMember = "Name";
            }
            catch (EndpointNotFoundException)
            {
                MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            objService.Close();

            return false;
        }
Example #18
0
        public static void SerializeToFile(string filename, object attribute)
        {
            XmlSerializer serializer = new XmlSerializer(attribute.GetType());
            XmlTextWriter textWriter = null;

            try
            {
                textWriter = new XmlTextWriter(filename, Encoding.UTF8);

                // we want the output formatted
                textWriter.Formatting = Formatting.Indented;

                serializer.Serialize(textWriter, attribute);
            }
            catch (Exception e)
            {
                LogFactory.WriteWarning(e.ToString());
            }
            finally
            {
                if (textWriter != null)
                {
                    textWriter.Flush();
                    textWriter.Close();
                }
            }
        }
        /// <summary>
        /// Ensures the notification types data have been intialized.
        /// </summary>
        private static void EnsureInitialized()
        {
            if (s_isLoaded)
                return;

            // Read the resource file
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(Properties.Resources.NotificationRefTypeIDs);
            
            // Read the nodes
            using (XmlNodeReader reader = new XmlNodeReader(xmlDoc))
            {
                // Create a memory stream to transform the xml 
                using (MemoryStream stream = new MemoryStream())
                {
                    // Write the xml output to the stream
                    using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
                    {
                        // Apply the XSL transform
                        XslCompiledTransform transform = Util.LoadXSLT(Properties.Resources.RowsetsXSLT);
                        writer.Formatting = Formatting.Indented;
                        transform.Transform(reader, writer);
                        writer.Flush();

                        // Deserialize from the given stream
                        stream.Seek(0, SeekOrigin.Begin);
                        XmlSerializer xs = new XmlSerializer(typeof(SerializableNotificationRefTypeIDs));
                        s_notificationTypes = (SerializableNotificationRefTypeIDs)xs.Deserialize(stream);
                    }
                }
            }

            s_isLoaded = true;
        }
Example #20
0
        public bool GenerateReport(string fileName)
        {
            bool retCode = false;
            ResetReportViwer();

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(rptXslPath);

            if ( File.Exists(fileName) == true)
            {
                XPathDocument myXPathDoc = new XPathDocument(fileName);
                StringWriter sw = new StringWriter();
                XmlWriter xmlWriter = new XmlTextWriter(sw);

                // using makes sure that we flush the writer at the end
                xslt.Transform(myXPathDoc, null, xmlWriter);
                xmlWriter.Flush();
                xmlWriter.Close();

                string xml = sw.ToString();

                HtmlDocument htmlDoc = axBrowser.Document;
                htmlDoc.Write(xml);
                retCode = true;
            }
            else
            {

                retCode = false;
            }

            return retCode;
        }
        public ActionResult Index()
        {
            var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));

            var indexElement = new XElement(SitemapXmlNamespace + "sitemapindex");

            foreach (var sitemapData in _sitemapRepository.GetAllSitemapData())
            {
                var sitemapElement = new XElement(
                    SitemapXmlNamespace + "sitemap",
                    new XElement(SitemapXmlNamespace + "loc", _sitemapRepository.GetSitemapUrl(sitemapData))
                );

                indexElement.Add(sitemapElement);
            }

            doc.Add(indexElement);

            Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
            Response.AppendHeader("Content-Encoding", "gzip");

            byte[] sitemapIndexData;

            using (var ms = new MemoryStream())
            {
                var xtw = new XmlTextWriter(ms, Encoding.UTF8);
                doc.Save(xtw);
                xtw.Flush();
                sitemapIndexData = ms.ToArray();
            }

            return new FileContentResult(sitemapIndexData, "text/xml");
        }
Example #22
0
        /// <summary>
        /// Opens this shelf view.
        /// </summary>
        public override void Open()
        {
            IApplicationComponentView componentView = (IApplicationComponentView)ViewFactory.CreateAssociatedView(_shelf.Component.GetType());
            componentView.SetComponent((IApplicationComponent)_shelf.Component);

        	XmlDocument restoreDocument;
        	if (DesktopViewSettings.Default.GetShelfState(_desktopView.DesktopWindowName, _shelf.Name, out restoreDocument))
			{
				using (MemoryStream memoryStream = new MemoryStream())
				{
					using (XmlTextWriter writer = new XmlTextWriter(memoryStream, Encoding.UTF8))
					{
						restoreDocument.WriteContentTo(writer);
						writer.Flush();
						memoryStream.Position = 0;

						_content = _desktopView.AddShelfView(this, (Control) componentView.GuiElement, _shelf.Title, _shelf.DisplayHint, memoryStream);

						writer.Close();
						memoryStream.Close();
					}
				}
			}
			else
			{
				_content = _desktopView.AddShelfView(this, (Control)componentView.GuiElement, _shelf.Title, _shelf.DisplayHint, null);
			}
		}
        // Accumulation format is now called Victory.
        private static void Upgrades0210()
        {
            var xml = new XmlDocument();
            if (Config.Settings.SeparateEventFiles)
            {
                var targetPath = Path.Combine(Program.BasePath, "Tournaments");
                if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath);
                var files = new List<string>(Directory.GetFiles(targetPath, "*.tournament.dat",
                    SearchOption.TopDirectoryOnly));
                files.AddRange(Directory.GetFiles(targetPath, "*.league.dat",
                    SearchOption.TopDirectoryOnly));
                foreach (string filename in files)
                {
                    xml.Load(filename);
                    var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']");
                    if (oldNodes != null)
                        foreach (XmlNode oldNode in oldNodes)
                            oldNode.InnerText = "Victory";
                    oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']");
                    if (oldNodes != null)
                        foreach (XmlNode oldNode in oldNodes)
                            oldNode.InnerText = "Victory";

                    var writer = new XmlTextWriter(new FileStream(filename, FileMode.Create), null)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 1,
                            IndentChar = '\t'
                        };

                    xml.WriteTo(writer);
                    writer.Flush();
                    writer.Close();
                }
            }
            else if (File.Exists(Path.Combine(Program.BasePath, "Events.dat")))
            {
                xml.Load(Path.Combine(Program.BasePath, "Events.dat"));
                var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']");
                if (oldNodes != null)
                    foreach (XmlNode oldNode in oldNodes)
                        oldNode.InnerText = "Victory";
                oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']");
                if (oldNodes != null)
                    foreach (XmlNode oldNode in oldNodes)
                        oldNode.InnerText = "Victory";

                var writer = new XmlTextWriter(new FileStream(Path.Combine(Program.BasePath,
                                                                           "Events.dat"), FileMode.Create), null)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 1,
                    IndentChar = '\t'
                };

                xml.WriteTo(writer);
                writer.Flush();
                writer.Close();
            }
        }
Example #24
0
		/// <summary>
		/// Executes the syndication result on the given context.
		/// </summary>
		/// <param name="context">The current context.</param>
		public virtual void Write(IStreamResponse response) {
			var writer = new XmlTextWriter(response.OutputStream, Encoding.UTF8);
			var ui = new Client.Helpers.UIHelper();

			// Write headers
			response.ContentType = ContentType;
			response.ContentEncoding = Encoding.UTF8;

			var feed = new SyndicationFeed() { 
				Title = new TextSyndicationContent(Config.Site.Title),
				LastUpdatedTime = Posts.First().Published.Value,
				Description = new TextSyndicationContent(Config.Site.Description),
			};
			feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(App.Env.AbsoluteUrl("~/"))));

			var items = new List<SyndicationItem>();
			foreach (var post in Posts) {
				var item = new SyndicationItem() { 
					Title = SyndicationContent.CreatePlaintextContent(post.Title),
					PublishDate = post.Published.Value,
					Summary = SyndicationContent.CreateHtmlContent(post.Body)
				};
				item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(App.Env.AbsoluteUrl("~/" + post.Type.Slug + "/" + post.Slug))));
				items.Add(item);
			}
			feed.Items = items;

			var formatter = GetFormatter(feed);
			formatter.WriteTo(writer);

			writer.Flush();
			writer.Close();
		}
Example #25
0
 public static XmlDocument Serialize(
   string testName,
   object obj, 
   Encoding encoding,
   MappingAction action)
 {
   Stream stm = new MemoryStream();
   XmlTextWriter xtw = new XmlTextWriter(stm, Encoding.UTF8);
   xtw.Formatting = Formatting.Indented;
   xtw.Indentation = 2;
   xtw.WriteStartDocument();      
   XmlRpcSerializer ser = new XmlRpcSerializer();
   ser.Serialize(xtw, obj, action); 
   xtw.Flush();
   //Console.WriteLine(testName);
   stm.Position = 0;    
   TextReader trdr = new StreamReader(stm, new UTF8Encoding(), true, 4096);
   String s = trdr.ReadLine();
   while (s != null)
   {
     //Console.WriteLine(s);
     s = trdr.ReadLine();
   }            
   stm.Position = 0;    
   XmlDocument xdoc = new XmlDocument();
   xdoc.PreserveWhitespace = true;
   xdoc.Load(stm);
   return xdoc;
 }
Example #26
0
        public static String XMLPrint(this String xml){
            if (string.IsNullOrEmpty(xml))
                return xml;
            String result = "";

            var mStream = new MemoryStream();
            var writer = new XmlTextWriter(mStream, Encoding.Unicode);
            var document = new XmlDocument();

            try{
                document.LoadXml(xml);
                writer.Formatting = Formatting.Indented;
                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();
                mStream.Position = 0;
                var sReader = new StreamReader(mStream);
                String formattedXML = sReader.ReadToEnd();

                result = formattedXML;
            }
            catch (XmlException){
            }

            mStream.Close();
            writer.Close();

            return result;
        }
Example #27
0
        /// <summary>
        /// Generates a xml sitemap about pages on site
        /// </summary>
        /// <param name="sitemapData">SitemapData object containing configuration info for sitemap</param>
        /// <param name="entryCount">out count of site entries in generated sitemap</param>
        /// <returns>True if sitemap generation successful, false if error encountered</returns>
        public bool Generate(SitemapData sitemapData, out int entryCount)
        {
            try
            {
                XElement sitemap = SitemapContentHelper.CreateSitemapXmlContents(sitemapData, out entryCount);

                var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
                doc.Add(sitemap);

                using (var ms = new MemoryStream())
                {
                    var xtw = new XmlTextWriter(ms, Encoding.UTF8);
                    doc.Save(xtw);
                    xtw.Flush();
                    sitemapData.Data = ms.ToArray();
                }

                sitemapRepository.Save(sitemapData);
                return true;
            }
            catch (Exception e)
            {
                Log.Error("Error on generating xml sitemap" + Environment.NewLine + e);
                entryCount = 0;
                return false;
            }
        }
Example #28
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// builds XML access key for UPS requests
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[mmcconnell]	11/1/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string BuildAccessKey(UpsSettings settings)
        {
            string sXML = "";
            StringWriter strWriter = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(strWriter);

            xw.Formatting = Formatting.Indented;
            xw.Indentation = 3;

            xw.WriteStartDocument();

            //--------------------------------------------            
            // Agreement Request
            xw.WriteStartElement("AccessRequest");

            xw.WriteElementString("AccessLicenseNumber", settings.License);
            xw.WriteElementString("UserId", settings.UserID);
            xw.WriteElementString("Password", settings.Password);

            xw.WriteEndElement();
            // End Agreement Request
            //--------------------------------------------

            xw.WriteEndDocument();
            xw.Flush();
            xw.Close();

            sXML = strWriter.GetStringBuilder().ToString();

            xw = null;

            //HttpContext.Current.Trace.Write("AccessRequest=" & sXML)

            return sXML;
        }
        public override void Save(object value, string sectionName, string fileName)
        {
            XmlNode xmlNode = this.Serialize(value);
            XmlDocument document = new XmlDocument();
            document.AppendChild(document.ImportNode(xmlNode,true));

            // Encrypt xml
            EncryptXml enc = new EncryptXml(document);
            enc.AddKeyNameMapping("db", ReadServerEncryptionKey());

            XmlNodeList list = document.SelectNodes("//Password");

            foreach ( XmlNode n in list )
            {
                XmlElement el = (XmlElement)n;
                EncryptedData data = enc.Encrypt(el, "db");
                enc.ReplaceElement(el, data);
            }

            XmlTextWriter writer = new XmlTextWriter(fileName, null);
            writer.Formatting = Formatting.Indented;
            document.WriteTo(writer);
            writer.Flush();
            writer.Close();
        }
Example #30
0
        /// <summary>
        /// Method to convert a custom Object to XML string. You can specify the encoding (eg UTF-8 or UTF-16).
        /// </summary>
        /// <param name="obj">Object that is to be serialized to XML. Note this must be a serializable object.</param>
        /// <param name="encoding">An encoding like System.Text.Encoding.UTF8</param>
        /// <returns>XML string</returns>
        public static String SerializeObject(Object obj, Encoding encoding)
        {
            var serializer = new XmlSerializer(obj.GetType());

            // create a MemoryStream here, we are just working
            // exclusively in memory
            System.IO.Stream stream = new System.IO.MemoryStream();

            // The XmlTextWriter takes a stream and encoding
            // as one of its constructors
            System.Xml.XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, encoding);

            serializer.Serialize(xtWriter, obj);

            xtWriter.Flush();

            // go back to the beginning of the Stream to read its contents
            stream.Seek(0, System.IO.SeekOrigin.Begin);

            // read back the contents of the stream and supply the encoding
            System.IO.StreamReader reader = new System.IO.StreamReader(stream, encoding);

            string result = reader.ReadToEnd();

            return(result);
        }
        // This function generates the XML request body
        // for the FolderSync request.
        protected override void GenerateXMLPayload()
        {
            // If WBXML was explicitly set, use that
            if (WbxmlBytes != null)
                return;

            // Otherwise, use the properties to build the XML and then WBXML encode it
            XmlDocument folderSyncXML = new XmlDocument();

            XmlDeclaration xmlDeclaration = folderSyncXML.CreateXmlDeclaration("1.0", "utf-8", null);
            folderSyncXML.InsertBefore(xmlDeclaration, null);

            XmlNode folderSyncNode = folderSyncXML.CreateElement(Xmlns.folderHierarchyXmlns, "FolderSync", Namespaces.folderHierarchyNamespace);
            folderSyncNode.Prefix = Xmlns.folderHierarchyXmlns;
            folderSyncXML.AppendChild(folderSyncNode);

            if (syncKey == "")
                syncKey = "0";

            XmlNode syncKeyNode = folderSyncXML.CreateElement(Xmlns.folderHierarchyXmlns, "SyncKey", Namespaces.folderHierarchyNamespace);
            syncKeyNode.Prefix = Xmlns.folderHierarchyXmlns;
            syncKeyNode.InnerText = syncKey;
            folderSyncNode.AppendChild(syncKeyNode);

            StringWriter sw = new StringWriter();
            XmlTextWriter xmlw = new XmlTextWriter(sw);
            xmlw.Formatting = Formatting.Indented;
            folderSyncXML.WriteTo(xmlw);
            xmlw.Flush();

            XmlString = sw.ToString();
        }
Example #32
0
        public static void Serialize(object obj, TextWriter output)
        {
            Debug.Assert(obj != null);
            Debug.Assert(output != null);

            #if !NET_1_0 && !NET_1_1
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;
            settings.CheckCharacters = false;
            settings.OmitXmlDeclaration = true;
            XmlWriter writer = XmlWriter.Create(output, settings);
            #else
            XmlTextWriter writer = new XmlTextWriter(output);
            writer.Formatting = Formatting.Indented;
            #endif

            try
            {
                SystemXmlSerializer serializer = new SystemXmlSerializer(obj.GetType());
                serializer.Serialize(writer, obj);
                writer.Flush();
            }
            finally
            {
                writer.Close();
            }
        }
Example #33
0
        private void SavePluginListToXMLFile(string filename)
        {
            try
            {
                Console.WriteLine("Saving plugins entries to " + (string)MediaNET.Config["Interface/plugins.xml"]);
                XmlTextWriter writer = new System.Xml.XmlTextWriter((string)MediaNET.Config["Interface/plugins.xml"], null);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("plugins");

                TreeModel model = pluginList.Model;
                TreeIter  iter;
                if (pluginStore.GetIterFirst(out iter))
                {
                    do
                    {
                        writer.WriteStartElement("plugin");
                        writer.WriteElementString("extension", (string)model.GetValue(iter, 0));
                        // Second field ignored -> found using reflection
                        writer.WriteElementString("player", (string)model.GetValue(iter, 2));
                        writer.WriteElementString("path", (string)model.GetValue(iter, 3));
                        writer.WriteEndElement();
                    }while (pluginStore.IterNext(ref iter));
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
            catch (Exception e)
            {
                throw new Exception("Save settings failed: " + e.Message);
            }
        }
Example #34
0
        public dynamic EnviarDadosTiny(DadosTiny dadosEnviarTiny)
        {
            Console.WriteLine("Enviando pedido: {0} na Tiny", dadosEnviarTiny.numero_pedido_ecommerce);
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(DadosTiny));

                // create a MemoryStream here, we are just working
                // exclusively in memory
                System.IO.Stream stream = new System.IO.MemoryStream();

                // The XmlTextWriter takes a stream and encoding
                // as one of its constructors
                System.Xml.XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, Encoding.UTF8);

                serializer.Serialize(xtWriter, dadosEnviarTiny);

                xtWriter.Flush();

                // go back to the beginning of the Stream to read its contents
                stream.Seek(0, System.IO.SeekOrigin.Begin);

                // read back the contents of the stream and supply the encoding
                System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);

                var xmlEnvio = reader.ReadToEnd();

                var client = new TinyService.tinywsdlPortTypeClient();
                //var ret = client.incluirPedidoServiceAsync(TokenTiny, dadosEnviarTiny, "JSON");
                var ret = client.incluirPedidoService(TokenTiny, xmlEnvio, "XML");
                client.Close();

                return(ObjectToXML(ret, typeof(Retorno)));
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }


            /*
             * XmlSerializer serializer = new XmlSerializer(typeof(DadosTiny));
             *
             * System.IO.StringWriter sWriter = new System.IO.StringWriter();
             *
             * serializer.Serialize(sWriter, dadosEnviarTiny);
             * sWriter.Flush();
             *
             * string xmlEnvio = sWriter.ToString();
             *
             * //var xmlEnvio = GetXMLFromObject(dadosEnviarTiny);
             * var client = new TinyService.tinywsdlPortTypeClient();
             * //var ret = client.incluirPedidoServiceAsync(TokenTiny, dadosEnviarTiny, "JSON");
             * var ret = client.incluirPedidoService(TokenTiny, xmlEnvio, "XML");
             * return ret;
             */
        }
Example #35
0
        private void SaveSetting()
        {
            //throw new System.NotImplementedException();

            #region zhucebiao
            //RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("SoftWare", true);
            //RegistryKey SQKey = softwareKey.CreateSubKey("SQPress");
            //RegistryKey selfWindowsKey = SQKey.CreateSubKey("selfWindowsKey");
            //selfWindowsKey.SetValue("BackColor", (object)BackColor.ToKnownColor());
            //selfWindowsKey.SetValue("Red", (object)(int)BackColor.R);
            //selfWindowsKey.SetValue("Green", (object)(int)BackColor.G);
            //selfWindowsKey.SetValue("Blue", (object)(int)BackColor.B);
            //selfWindowsKey.SetValue("Width", (object)Width);
            //selfWindowsKey.SetValue("Height", (object)Height);
            //selfWindowsKey.SetValue("X", (object)DesktopLocation.X);
            //selfWindowsKey.SetValue("Y", (object)DesktopLocation.Y);
            //selfWindowsKey.SetValue("WindowState", (object)WindowState.ToString());

            //softwareKey.Close();
            //SQKey.Close();
            //selfWindowsKey.Close();
            #endregion

            #region ISO
            IsolatedStorageFile iso         = IsolatedStorageFile.GetUserStoreForDomain();
            var isoStream                   = new IsolatedStorageFileStream("SelfPlace.xml", FileMode.Create, FileAccess.ReadWrite);
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(isoStream, Encoding.Default);
            writer.Formatting = System.Xml.Formatting.Indented;


            writer.WriteStartDocument();
            writer.WriteStartElement("Settings");

            writer.WriteStartElement("Width");
            writer.WriteValue(this.Width);
            writer.WriteEndElement();

            writer.WriteStartElement("Height");
            writer.WriteValue(this.Height);
            writer.WriteEndElement();

            writer.WriteStartElement("X");
            writer.WriteValue(this.DesktopLocation.X);
            writer.WriteEndElement();

            writer.WriteStartElement("Y");
            writer.WriteValue(this.DesktopLocation.Y);
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.Flush();
            writer.Close();

            isoStream.Close();
            iso.Close();
            #endregion
        }
Example #36
0
        /// <summary>
        /// Convierte un objeto en un string
        /// </summary>
        /// <param name="obj">el objeto a convertir</param>
        /// <returns>el string que representa al objeto</returns>
        public string serialize(Object obj)
        {
            StringWriter  sw     = new StringWriter();
            XmlTextWriter writer = new System.Xml.XmlTextWriter(sw);

            serializer.Serialize(writer, obj);
            writer.Flush();
            writer.Close();
            return(sw.ToString());
        }
Example #37
0
        public static string XmlSerialize <T>(this T value)
        {
            if (value == null)
            {
                return(string.Empty);
            }
            try
            {
                XmlWriterSettings settings = new XmlWriterSettings()
                {
                    Encoding            = Encoding.UTF8,
                    Indent              = true,
                    NewLineOnAttributes = true,
                };

                //var xmlserializer = new XmlSerializer(typeof(T));
                //var stringWriter = new XmlTextWriter();
                //using (var writer = XmlWriter.Create(stringWriter, settings))
                //{
                //    xmlserializer.Serialize(writer, value);
                //    return stringWriter.ToString();
                //}


                XmlSerializer serializer = new XmlSerializer(typeof(T));

                // create a MemoryStream here, we are just working
                // exclusively in memory
                System.IO.Stream stream = new System.IO.MemoryStream();

                // The XmlTextWriter takes a stream and encoding
                // as one of its constructors
                System.Xml.XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, Encoding.UTF8);

                serializer.Serialize(xtWriter, value);

                xtWriter.Flush();

                // go back to the beginning of the Stream to read its contents
                stream.Seek(0, System.IO.SeekOrigin.Begin);

                // read back the contents of the stream and supply the encoding
                System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);

                string result = reader.ReadToEnd();
                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred", ex);
            }
        }
Example #38
0
        /// <summary>
        /// 从DataTable和对应的GroupBox中的内容得到XML串
        /// </summary>
        /// <param name="p_objclsElementAttributeArr">p_dtbTable列数 ==p_objclsElementAttributeArr的长度(GroupBox中各项+签名+时间,每项对应一个clsElementAttribute对象)</param>
        /// <param name="p_dtbTable">记录对应的DataTable</param>
        /// <param name="p_objXmlMemStream"></param>
        /// <param name="p_xmlWriter"></param>
        /// <returns>若参数错误返回null</returns>
        public string m_strGetXMLFromDataTable(clsElementAttribute[] p_objclsElementAttributeArr, System.Data.DataTable p_dtbTable, ref System.IO.MemoryStream p_objXmlMemStream, ref System.Xml.XmlTextWriter p_xmlWriter)
        {
            if (p_objclsElementAttributeArr == null || p_dtbTable.Columns.Count != p_objclsElementAttributeArr.Length)
            {
                return(null);
            }

            p_objXmlMemStream.SetLength(0);
            p_xmlWriter.WriteStartDocument();
            p_xmlWriter.WriteStartElement("Main");

            clsElementAttribute objclsElementAttribute = new clsElementAttribute();

            bool blnIsModified = m_blnIsModified(p_objclsElementAttributeArr, p_dtbTable);

            if (blnIsModified == true)         //如果被修改,添加当前值
            {
                p_xmlWriter.WriteStartElement("Sub");
                for (int j0 = 0; j0 < p_objclsElementAttributeArr.Length; j0++)
                {
                    m_mthAddElementAttibute(p_objclsElementAttributeArr[j0], ref p_xmlWriter);
                }
                p_xmlWriter.WriteEndElement();
            }
            for (int i1 = 0; i1 < p_dtbTable.Rows.Count; i1++)     //重写原来的痕迹
            {
                p_xmlWriter.WriteStartElement("Sub");
                for (int j2 = 0; j2 < p_objclsElementAttributeArr.Length; j2++)
                {
                    objclsElementAttribute.m_blnIsDST       = p_objclsElementAttributeArr[j2].m_blnIsDST;            //默认为非DST格式,即为bool类型
                    objclsElementAttribute.m_strElementName = p_objclsElementAttributeArr[j2].m_strElementName;
                    if (objclsElementAttribute.m_blnIsDST == false)
                    {
                        objclsElementAttribute.m_strValue = p_dtbTable.Rows[i1][j2].ToString();
                    }
                    else
                    {
                        objclsElementAttribute.m_strValue    = ((clsDSTRichTextBoxValue)(p_dtbTable.Rows[i1][j2])).m_strText;
                        objclsElementAttribute.m_strValueXML = ((clsDSTRichTextBoxValue)(p_dtbTable.Rows[i1][j2])).m_strDSTXml;
                    }

                    m_mthAddElementAttibute(objclsElementAttribute, ref p_xmlWriter);
                }
                p_xmlWriter.WriteEndElement();
            }

            p_xmlWriter.WriteEndElement();
            p_xmlWriter.WriteEndDocument();
            p_xmlWriter.Flush();
            return(System.Text.Encoding.Unicode.GetString(p_objXmlMemStream.ToArray(), 39 * 2, (int)p_objXmlMemStream.Length - 39 * 2));
        }
        private static string XmlToString(XmlDocument sLogData)
        {
            StringBuilder            strBuilder = new StringBuilder();
            StringWriterWithEncoding strWriter  = new StringWriterWithEncoding(strBuilder, System.Text.Encoding.UTF8);

            System.Xml.XmlTextWriter objXMLWriter = new System.Xml.XmlTextWriter(strWriter);
            objXMLWriter.Formatting  = Formatting.Indented;
            objXMLWriter.IndentChar  = (char)9;
            objXMLWriter.Indentation = 1;
            sLogData.Save(objXMLWriter);
            objXMLWriter.Flush();
            objXMLWriter.Close();
            objXMLWriter = null;
            return(strBuilder.ToString());
        }
Example #40
0
        /// <summary>
        /// 生成XML
        /// </summary>
        /// <param name="root">根结点</param>
        /// <returns></returns>
        public static String ToXml(XmlTreeNode root, Encoding encoding)
        {
            MemoryStream ms = new MemoryStream();
            XmlWriter    xw = new System.Xml.XmlTextWriter(ms, encoding);

            xw.WriteStartDocument();
            _WriteTreeNode(root, xw);
            xw.WriteEndDocument();

            xw.Flush();
            xw.Close();

            var xml = encoding.GetString(ms.ToArray());

            return(xml);
        }
Example #41
0
        public void WriteValue(string strSection, string strKey, string strValue)
        {
            //XmlNodeList mNode = mXml.GetElementsByTagName(strSection);
            XmlTextWriter mXmlWrite = new System.Xml.XmlTextWriter(this.strPathOfXml, System.Text.UTF8Encoding.UTF8);

            mXmlWrite.Formatting = Formatting.Indented;
            mXmlWrite.WriteStartDocument();
            mXmlWrite.WriteStartElement("property");
            mXmlWrite.WriteStartElement(strSection);
            mXmlWrite.WriteElementString(strKey, strValue);
            mXmlWrite.WriteEndElement();
            mXmlWrite.WriteEndElement();
            mXmlWrite.WriteEndDocument();
            mXmlWrite.Flush();
            mXmlWrite.Close();
        }
Example #42
0
        static int vipID; // = 0;

        static void SerializeVisual(Visual visual, double width, double height, String filename)
        {
            FileStream    stream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
            XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);

            writer.Formatting  = System.Xml.Formatting.Indented;
            writer.Indentation = 4;
            writer.WriteStartElement("FixedDocument");
            writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            writer.WriteAttributeString("xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml");

            writer.WriteStartElement("PageContent");
            writer.WriteStartElement("FixedPage");
            writer.WriteAttributeString("Width", width.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString("Height", height.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString("Background", "White");
            writer.WriteStartElement("Canvas");

            System.IO.StringWriter resString = new StringWriter(CultureInfo.InvariantCulture);

            System.Xml.XmlTextWriter resWriter = new System.Xml.XmlTextWriter(resString);
            resWriter.Formatting  = System.Xml.Formatting.Indented;
            resWriter.Indentation = 4;

            System.IO.StringWriter bodyString = new StringWriter(CultureInfo.InvariantCulture);

            System.Xml.XmlTextWriter bodyWriter = new System.Xml.XmlTextWriter(bodyString);
            bodyWriter.Formatting  = System.Xml.Formatting.Indented;
            bodyWriter.Indentation = 4;

            VisualTreeFlattener.SaveAsXml(visual, resWriter, bodyWriter, filename);

            resWriter.Close();
            bodyWriter.Close();

            writer.Flush();
            writer.WriteRaw(resString.ToString());
            writer.WriteRaw(bodyString.ToString());

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteEndElement(); // FixedDocument
            writer.Close();
            stream.Close();
        }
        private string Pretty(string Message)
        {
            System.Xml.XmlDocument   Doc       = new System.Xml.XmlDocument();
            System.IO.MemoryStream   MemStr    = new System.IO.MemoryStream();
            System.Xml.XmlTextWriter XmlWriter = new System.Xml.XmlTextWriter(MemStr, System.Text.Encoding.Unicode);
            XmlWriter.Formatting = System.Xml.Formatting.Indented;
            Doc.LoadXml(Message);
            Doc.WriteContentTo(XmlWriter);
            XmlWriter.Flush();
            MemStr.Flush();
            MemStr.Position = 0;
            string Ret = new System.IO.StreamReader(MemStr).ReadToEnd();

            MemStr.Close();
            XmlWriter.Close();
            return(Ret);
        }
        public static string GenerateEntityXml(string outputPath, EntityInfo entity)
        {
            string ret = String.Empty;

            if (entity == null || !Directory.Exists(outputPath))
            {
                return(ret);
            }

            Log4Helper.Write("GenerateEntityXml", String.Format("Process of entity {0} starts at {1}.", entity.ClassName, System.DateTime.Now.ToString("s")), LogSeverity.Info);

            using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(System.IO.Path.Combine(outputPath, String.Concat(entity.ClassName, ".xml")), System.Text.Encoding.UTF8))
            {
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");

                //generate entity calss
                xtw.WriteStartElement("entity");
                xtw.WriteAttributeString("namespace", entity.NameSpace);
                xtw.WriteAttributeString("name", entity.ClassName);

                #region columns/properties
                //generate property node
                xtw.WriteStartElement("fields");
                foreach (FieldInfo field in entity.Fileds)
                {
                    xtw.WriteStartElement("property");
                    xtw.WriteAttributeString("type", field.Type);
                    xtw.WriteAttributeString("name", field.Name);
                    xtw.WriteAttributeString("privateFieldName", field.PrivateFieldName);
                    xtw.WriteAttributeString("paramName", field.ParamName);
                    xtw.WriteAttributeString("propetyName", field.PropertyName);
                    xtw.WriteAttributeString("csharpType", field.CSharpType);
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion
                ret = xtw.ToString();
                xtw.WriteEndElement();
                xtw.Flush();
                xtw.Close();
            }

            Log4Helper.Write("GenerateEntityXmlFromTable", String.Format("Process of table {0} ends at {1}.", entity.ClassName, System.DateTime.Now.ToString("s")), LogSeverity.Info);
            return(ret);
        }
Example #45
0
        public string TransformXML(string xml, string xsl)
        {
            System.IO.StringReader          stringReader        = null;
            System.Xml.Xsl.XslTransform     xslTransform        = null;
            System.Xml.XmlTextReader        xmlTextReader       = null;
            System.IO.MemoryStream          xmlTextWriterStream = null;
            System.Xml.XmlTextWriter        xmlTextWriter       = null;
            System.Xml.XmlDocument          xmlDocument         = null;
            System.IO.StreamReader          streamReader        = null;
            System.Security.Policy.Evidence evidence            = null;
            try
            {
                stringReader        = new System.IO.StringReader(xsl);
                xslTransform        = new System.Xml.Xsl.XslTransform();
                xmlTextReader       = new System.Xml.XmlTextReader(stringReader);
                xmlTextWriterStream = new System.IO.MemoryStream();
                xmlTextWriter       = new System.Xml.XmlTextWriter(xmlTextWriterStream, System.Text.Encoding.Default);
                xmlDocument         = new System.Xml.XmlDocument();

                evidence = new System.Security.Policy.Evidence();
                evidence.AddAssembly(this);
                xmlDocument.LoadXml(xml);
                xslTransform.Load(xmlTextReader, null, evidence);
                xslTransform.Transform(xmlDocument, null, xmlTextWriter, null);
                xmlTextWriter.Flush();

                xmlTextWriterStream.Position = 0;
                streamReader = new System.IO.StreamReader(xmlTextWriterStream);
                return(streamReader.ReadToEnd());
            }
            catch (Exception exc)
            {
                LogEvent(exc.Source, "TransformXML()", exc.ToString(), 4);
                return("");
            }
            finally
            {
                streamReader.Close();
                xmlTextWriter.Close();
                xmlTextWriterStream.Close();
                xmlTextReader.Close();
                stringReader.Close();
                GC.Collect();
            }
        }
        }//end main

        public static void SerializeExpandableObject(ExpandableObject obj)
        {
            var    serializer = new DataContractSerializer(typeof(ExpandableObject));
            string xmlString;

            using (var sw = new StringWriter())
            {
                using (var writer = new System.Xml.XmlTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented; // indent the Xml so it's human readable
                    serializer.WriteObject(writer, obj);
                    writer.Flush();
                    xmlString = sw.ToString();
                }
            }

            Console.WriteLine(xmlString);
        } //end method
Example #47
0
 /// <summary>
 /// Serializes the object.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="inObject">The input object.</param>
 /// <returns></returns>
 public static string SerializeObject <T>(T inObject, Encoding encodeType)
 {
     if (encodeType == null)
     {
         encodeType = Encoding.UTF8;
     }
     // create a MemoryStream here, we are just working exclusively in memory
     using (Stream stream = new System.IO.MemoryStream())
     {
         // The XmlTextWriter takes a stream and encoding as one of its constructors
         using (XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, encodeType))
         {
             try
             {
                 XmlSerializer serializer = new XmlSerializer(typeof(T));
                 serializer.Serialize(xtWriter, inObject);
                 xtWriter.Flush();
                 // go back to the beginning of the Stream to read its contents
                 stream.Seek(0, System.IO.SeekOrigin.Begin);
                 // read back the contents of the stream and supply the encoding
                 using (StreamReader reader = new System.IO.StreamReader(stream, encodeType))
                 {
                     string result = reader.ReadToEnd();
                     return(result);
                 }
             }
             catch (Exception e)
             {
                 return(e.Message);
             }
             finally
             {
                 if (stream != null)
                 {
                     stream.Close();
                 }
                 if (xtWriter != null)
                 {
                     xtWriter.Close();
                 }
             }
         }
     }
 }
Example #48
0
        public static string IdentXML(string xml)
        {
            string result = "";

            MemoryStream mStream = new MemoryStream();

            System.Xml.XmlTextWriter writer   = new System.Xml.XmlTextWriter(mStream, Encoding.Unicode);
            System.Xml.XmlDocument   document = new System.Xml.XmlDocument();

            try
            {
                // Load the XmlDocument with the XML.
                document.LoadXml(xml);

                writer.Formatting = System.Xml.Formatting.Indented;

                // Write the XML into a formatting XmlTextWriter
                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();

                // Have to rewind the MemoryStream in order to read
                // its contents.
                mStream.Position = 0;

                // Read MemoryStream contents into a StreamReader.
                StreamReader sReader = new StreamReader(mStream);

                // Extract the text from the StreamReader.
                string formattedXml = sReader.ReadToEnd();

                result = formattedXml;
            }
            catch (System.Xml.XmlException)
            {
                // Handle the exception
            }

            mStream.Close();
            writer.Close();

            return(result);
        }
Example #49
0
        ///<summary>
        /// SyggestSync is a goodies to ask a proper sync of what's
        /// present in RAM, and what's present in the XML file.
        ///</summary>
        public void SuggestSync()
        {
            XmlTextWriter writer = new System.Xml.XmlTextWriter("configuration.xml", null);

            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("entries");

            foreach (string key in m_Matches.Keys)
            {
                writer.WriteStartElement("entry");
                writer.WriteElementString("key", key);
                writer.WriteElementString("value", (string)m_Matches[key]);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
        }
Example #50
0
        /// <summary>
        /// GenerateEntityXmlFromTable generates a xml file basing on the information of the table passed in.
        /// </summary>
        public static void GenerateEntityXmlFromTable(Table table, ArrayList columns, ArrayList extSettings, string outputFile)
        {
            if (table != null && System.IO.File.Exists(outputFile))
            {
                System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(outputFile, System.Text.Encoding.UTF8);
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");

                //generate entity calss
                xtw.WriteStartElement("entity");
                xtw.WriteAttributeString("tableName", table.TableName);
                xtw.WriteAttributeString("tableSchema", table.TableSchema);
                if (extSettings != null)
                {
                    foreach (ExtSetting e in extSettings)
                    {
                        xtw.WriteAttributeString(e.Name, e.Value);
                    }
                }
//					xtw.WriteAttributeString("namespace", codeNamespace);
//                    xtw.WriteAttributeString("author", Utility.GetCurrentIdentityName());
//                    xtw.WriteAttributeString("createdDateTime", System.DateTime.Now.ToString("s"));
                xtw.WriteAttributeString("BuildProject", BUILDPROJECT_VERSION);

                #region columns/properties
                //generate property node
                xtw.WriteStartElement("columns");
                for (int i = 0; i < columns.Count; i++)
                {
                    GenerateXmlElementFromColumn((Column)columns[i], xtw);
                }
                xtw.WriteEndElement();
                #endregion

                xtw.WriteEndElement();
                xtw.Flush();
                xtw.Close();
            }
        }
Example #51
0
        private static string IndentXMLString(string xml)
        {
            string outXml = string.Empty;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            // Create a XMLTextWriter that will send its output to a memory stream (file)
            System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.Unicode);
            System.Xml.XmlDocument   doc = new System.Xml.XmlDocument();

            try
            {
                // Load the unformatted XML text string into an instance
                // of the XML Document Object Model (DOM)
                doc.LoadXml(xml);

                // Set the formatting property of the XML Text Writer to indented
                // the text writer is where the indenting will be performed
                xtw.Formatting  = System.Xml.Formatting.Indented;
                xtw.Indentation = 4;

                // write dom xml to the xmltextwriter
                doc.WriteContentTo(xtw);
                // Flush the contents of the text writer
                // to the memory stream, which is simply a memory file
                xtw.Flush();

                // set to start of the memory stream (file)
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                // create a reader to read the contents of
                // the memory stream (file)
                System.IO.StreamReader sr = new System.IO.StreamReader(ms);
                // return the formatted string to caller
                return(sr.ReadToEnd());
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Example #52
0
            public void SaveResources()
            {
                using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Controller.ResourcesFile, Encoding.UTF8))
                {
                    writer.Formatting = System.Xml.Formatting.Indented;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("resources");

                    foreach (Resource resource in _resourceList.Values)
                    {
                        if (resource != Root)
                        {
                            resource.WriteXML(writer);
                        }
                    }

                    writer.WriteEndElement();
                    writer.WriteEndDocument();

                    writer.Flush();
                    writer.Close();
                }
            }
Example #53
0
        /// <summary>
        /// Turn the treeview into XML
        /// </summary>
        /// <returns></returns>
        protected override object SaveViewState()
        {
            //turn the treeview into XML
            System.IO.MemoryStream   stream = new System.IO.MemoryStream();
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Default);

            writer.WriteStartElement("treeview", "");
            //write out all the child nodes
            foreach (TreeNode n in this.Controls)
            {
                n.WriteXml(writer);
            }
            writer.WriteEndElement();
            writer.Flush();
            //writing the XML is done, read it back out
            stream.Position = 0;
            System.IO.StreamReader reader = new System.IO.StreamReader(stream);
            string xml = reader.ReadToEnd();

            writer.Close();
            stream.Close();
            return(xml);
        }
        public static void GenerateTextXmlFromTable(TableInfo table, string outputPath)
        {
            if (table == null || !Directory.Exists(outputPath))
            {
                return;
            }

            Log4Helper.Write("GenerateTextXmlFromTable", String.Format("Process of table {0} starts at {1}.", table.TableName, System.DateTime.Now.ToString("s")), LogSeverity.Info);

            string entityName = GetModelName(table.TableName);

            using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(System.IO.Path.Combine(outputPath, String.Concat(entityName, ".xml")), System.Text.Encoding.UTF8))
            {
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");

                //generate entity calss
                xtw.WriteStartElement("modeltext");

                #region columns/properties
                foreach (ColumnInfo c in table.Columns)
                {
                    xtw.WriteStartElement("field");
                    xtw.WriteAttributeString("key", entityName + "_" + c.ColumnName);
                    xtw.WriteAttributeString("value", c.ColumnDescription);
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                xtw.Flush();
                xtw.Close();
            }

            Log4Helper.Write("GenerateTextXmlFromTable", String.Format("Process of table {0} ends at {1}.", table.TableName, System.DateTime.Now.ToString("s")), LogSeverity.Info);
        }
        private void GeneraXML(System.Xml.XmlTextWriter writer) // As System.Xml.XmlTextWriter
        {
            try
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("FacturaElectronica");

                writer.WriteAttributeString("xmlns", "https://tribunet.hacienda.go.cr/docs/esquemas/2017/v4.2/facturaElectronica");
                writer.WriteAttributeString("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
                writer.WriteAttributeString("xmlns:vc", "http://www.w3.org/2007/XMLSchema-versioning");
                writer.WriteAttributeString("xmlns:xs", "http://www.w3.org/2001/XMLSchema");

                // La clave se crea con la función CreaClave de la clase Datos
                writer.WriteElementString("Clave", _numeroClave);

                // 'El numero de secuencia es de 20 caracteres,
                // 'Se debe de crear con la función CreaNumeroSecuencia de la clase Datos
                writer.WriteElementString("NumeroConsecutivo", _numeroConsecutivo);

                // 'El formato de la fecha es yyyy-MM-ddTHH:mm:sszzz
                writer.WriteElementString("FechaEmision", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz"));

                writer.WriteStartElement("Emisor");

                writer.WriteElementString("Nombre", _emisor.Nombre);
                writer.WriteStartElement("Identificacion");
                writer.WriteElementString("Tipo", _emisor.Identificacion_Tipo);
                writer.WriteElementString("Numero", _emisor.Identificacion_Numero);
                writer.WriteEndElement(); // 'Identificacion

                // '-----------------------------------
                // 'Los datos de las ubicaciones los puede tomar de las tablas de datos,
                // 'Debe ser exacto al que hacienda tiene registrado para su compañia
                writer.WriteStartElement("Ubicacion");
                writer.WriteElementString("Provincia", _emisor.Ubicacion_Provincia);
                writer.WriteElementString("Canton", _emisor.Ubicacion_Canton);
                writer.WriteElementString("Distrito", _emisor.Ubicacion_Distrito);
                writer.WriteElementString("Barrio", _emisor.Ubicacion_Barrio);
                writer.WriteElementString("OtrasSenas", _emisor.Ubicacion_OtrasSenas);
                writer.WriteEndElement(); // 'Ubicacion

                writer.WriteStartElement("Telefono");
                writer.WriteElementString("CodigoPais", _emisor.Telefono_CodigoPais);
                writer.WriteElementString("NumTelefono", _emisor.Telefono_Numero.ToString());
                writer.WriteEndElement(); // 'Telefono

                writer.WriteElementString("CorreoElectronico", _emisor.CorreoElectronico);

                writer.WriteEndElement(); // Emisor
                                          // '------------------------------------
                                          // 'Receptor es similar con emisor, los datos opcionales siempre siempre siempre omitirlos.
                                          // 'La ubicacion para el receptor es opcional por ejemplo
                writer.WriteStartElement("Receptor");
                writer.WriteElementString("Nombre", _receptor.Nombre);
                writer.WriteStartElement("Identificacion");
                // 'Los tipos de identificacion los puede ver en la tabla de datos
                writer.WriteElementString("Tipo", _receptor.Identificacion_Tipo);
                writer.WriteElementString("Numero", _receptor.Identificacion_Numero);
                writer.WriteEndElement(); // 'Identificacion

                writer.WriteStartElement("Telefono");
                writer.WriteElementString("CodigoPais", _receptor.Telefono_CodigoPais);
                writer.WriteElementString("NumTelefono", _receptor.Telefono_Numero.ToString());
                writer.WriteEndElement(); // 'Telefono

                writer.WriteElementString("CorreoElectronico", _receptor.CorreoElectronico);

                writer.WriteEndElement(); // Receptor
                                          // '------------------------------------

                // 'Loa datos estan en la tabla correspondiente
                writer.WriteElementString("CondicionVenta", _condicionVenta);
                // '01: Contado
                // '02: Credito
                // '03: Consignación
                // '04: Apartado
                // '05: Arrendamiento con opcion de compra
                // '06: Arrendamiento con función financiera
                // '99: Otros

                // 'Este dato se muestra si la condicion venta es credito
                writer.WriteElementString("PlazoCredito", _plazoCredito);

                writer.WriteElementString("MedioPago", _medioPago);
                // '01: Efectivo
                // '02: Tarjeta
                // '03: Cheque
                // '04: Transferecia - deposito bancario
                // '05: Recaudado por terceros
                // '99: Otros

                writer.WriteStartElement("DetalleServicio");

                // '-------------------------------------
                foreach (var xt in _dsDetalle)
                {
                    writer.WriteStartElement("LineaDetalle");

                    writer.WriteElementString("NumeroLinea", xt.numeroDeLinea.ToString());

                    writer.WriteStartElement("Codigo");

                    writer.WriteElementString("Tipo", xt.tipoDeArticulo.ToString());
                    writer.WriteElementString("Codigo", xt.codigoArticulo.ToString());
                    writer.WriteEndElement(); // 'Codigo

                    writer.WriteElementString("Cantidad", xt.cantidad.ToString());
                    // 'Para las unidades de medida ver la tabla correspondiente
                    writer.WriteElementString("UnidadMedida", xt.unidadDeMedida.ToString());
                    writer.WriteElementString("Detalle", xt.detalle.ToString());
                    writer.WriteElementString("PrecioUnitario", String.Format("{0:N3}", xt.precioUnitario.ToString()));
                    writer.WriteElementString("MontoTotal", String.Format("{0:N3}", xt.montoTotal.ToString()));
                    writer.WriteElementString("MontoDescuento", String.Format("{0:N3}", xt.montoDescuento.ToString()));
                    writer.WriteElementString("NaturalezaDescuento", xt.NaturalezaDescuento.ToString());
                    writer.WriteElementString("SubTotal", String.Format("{0:N3}", xt.subtotal.ToString()));

                    writer.WriteStartElement("Impuesto");
                    writer.WriteElementString("Codigo", xt.codigoImpuesto.ToString());
                    writer.WriteElementString("Tarifa", xt.impuestoTarifa.ToString());
                    writer.WriteElementString("Monto", xt.impuestoMonto.ToString());
                    writer.WriteEndElement(); // Impuesto

                    writer.WriteElementString("MontoTotalLinea", String.Format("{0:N3}", xt.montoTotalLinea.ToString()));

                    writer.WriteEndElement(); // LineaDetalle
                }
                // '-------------------------------------

                writer.WriteEndElement(); // DetalleServicio


                writer.WriteStartElement("ResumenFactura");

                // Estos campos son opcionales, solo fin desea facturar en dólares
                writer.WriteElementString("CodigoMoneda", _codigoMoneda);
                writer.WriteElementString("TipoCambio", "1.00000");
                // =================

                //SACAR CALCULOS PARA FACTURA



                double totalComprobante = 0;

                double montoTotalImpuesto = 0;

                foreach (var y in _dsDetalle)
                {
                    montoTotalImpuesto = montoTotalImpuesto + y.impuestoMonto;
                }

                totalComprobante = 0 + montoTotalImpuesto;



                // 'En esta parte los totales se pueden ir sumando linea a linea cuando se carga el detalle
                // 'ó se pasa como parametros al inicio
                writer.WriteElementString("TotalServGravados", "0.00000");
                writer.WriteElementString("TotalServExentos", "0.00000");


                writer.WriteElementString("TotalMercanciasGravadas", "0.00000");
                writer.WriteElementString("TotalMercanciasExentas", "0.00000");

                writer.WriteElementString("TotalGravado", "0.00000");
                writer.WriteElementString("TotalExento", "0.00000");

                writer.WriteElementString("TotalVenta", "0.00000");
                writer.WriteElementString("TotalDescuentos", "0.00000");
                writer.WriteElementString("TotalVentaNeta", "0.00000");
                writer.WriteElementString("TotalImpuesto", String.Format("{0:N3}", montoTotalImpuesto.ToString()));
                writer.WriteElementString("TotalComprobante", String.Format("{0:N3}", totalComprobante.ToString()));
                writer.WriteEndElement(); // ResumenFactura

                // 'Estos datos te los tiene que brindar los encargados del area financiera
                writer.WriteStartElement("Normativa");
                writer.WriteElementString("NumeroResolucion", "DGT-R-48-2016");
                writer.WriteElementString("FechaResolucion", "07-10-2016 01:00:00");
                writer.WriteEndElement(); // Normativa

                // 'Aqui va la firma, despues la agregamos.

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #56
0
        public string CriarXmlRequisicao(string strMatricSistema, string usuarioSistema, string ipusuario, string usuariorede, string strAutenticacaoCriptografada = "", string strCaminhoCPR = "", string pSenha = "")
        {
            //Rotina que Gera a string de Requisição da Autenticação
            string        strRetorno        = "";
            string        strNomeArquivoXML = "";
            XmlTextWriter xmlRequisicao     = default(XmlTextWriter);
            XmlDocument   docXML            = default(XmlDocument);
            StreamReader  SR = default(StreamReader);

            try
            {
                if (!System.IO.Directory.Exists(ConfigurationSettings.AppSettings["CaminhoXML"].ToString() + "\\XML\\"))
                {
                    System.IO.Directory.CreateDirectory(ConfigurationSettings.AppSettings["CaminhoXML"].ToString() + "\\XML\\");
                }

                //Procura por um nome de arquivo que ainda não exista
                //strNomeArquivoXML = AppDomain.CurrentDomain.BaseDirectory + "\\XML\\XML_REQ_AUT_" + String.Format(DateTime.Now, "ddMMyyyyhhmmss") + ".xml";
                strNomeArquivoXML = ConfigurationSettings.AppSettings["CaminhoXML"].ToString() + "\\XML\\XML_REQ_AUT_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
                while (System.IO.File.Exists(strNomeArquivoXML))
                {
                    strNomeArquivoXML = AppDomain.CurrentDomain.BaseDirectory + "\\XML\\XML_REQ_AUT_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
                }

                xmlRequisicao = new System.Xml.XmlTextWriter(strNomeArquivoXML, System.Text.Encoding.UTF8);

                //INÍCIO DO DOCUMENTO XML
                xmlRequisicao.WriteStartDocument();

                //INÍCIO DA TAG 'REQUISICAO'
                xmlRequisicao.WriteStartElement("requisicao");
                xmlRequisicao.WriteAttributeString("xmlns", "http://ntconsult.com.br/webservices/");
                xmlRequisicao.WriteAttributeString("versao", "0.10");

                //Caso a Autenticação seja criptografia RSA então este elemento deverá ser criado: AutenticacaoCriptografada
                //Caso o parâmetro tenha sido informado e não esteja em branco efetua a autenticação através de RSA
                if ((strAutenticacaoCriptografada != null))
                {
                    if (!string.IsNullOrEmpty(strAutenticacaoCriptografada.Trim()))
                    {
                        xmlRequisicao.WriteElementString("AutenticacaoCriptografada", strAutenticacaoCriptografada);
                    }
                }
                else
                {
                    xmlRequisicao.WriteElementString("usr", usuarioSistema);
                    xmlRequisicao.WriteElementString("senha", pSenha);
                }
                xmlRequisicao.WriteElementString("matricsistema", strMatricSistema);
                xmlRequisicao.WriteElementString("usuariorede", usuariorede);
                xmlRequisicao.WriteElementString("ipusuario", ipusuario);



                //FIM DA TAG 'REQUISICAO'
                xmlRequisicao.WriteEndElement();

                //FIM DO DOCUMENTO XML
                xmlRequisicao.WriteEndDocument();
                xmlRequisicao.Flush();
                xmlRequisicao.Close();


                docXML = new XmlDocument();
                docXML.PreserveWhitespace = false;

                SR = File.OpenText(strNomeArquivoXML);
                docXML.LoadXml(SR.ReadToEnd());
                SR.Close();

                strRetorno = docXML.InnerXml.ToString();

                //apos usar o arquivo, apaga-lo
                File.Delete(strNomeArquivoXML);

                return(strRetorno);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #57
0
        // Constructor
        public Hxc(string name, string title, string langId, string version, string copyright, string outputDirectory, Encoding encoding)
        {
            if (!Directory.Exists(outputDirectory))
            {
                try
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            try
            {
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Path.Combine(outputDirectory, name + ".hxc"), null);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteDocType("HelpCollection", null, "MS-Help://Hx/Resources/HelpCollection.dtd", null);

                writer.WriteStartElement("HelpCollection");
                writer.WriteAttributeString("DTDVersion", "1.0");
                writer.WriteAttributeString("FileVersion", version);
                writer.WriteAttributeString("LangId", langId);
                writer.WriteAttributeString("Title", title);
                writer.WriteAttributeString("Copyright", copyright);

                writer.WriteStartElement("CompilerOptions");
                writer.WriteAttributeString("OutputFile", string.Format("{0}{1}", name, ".HxS"));
                writer.WriteAttributeString("CreateFullTextIndex", "Yes");
                writer.WriteAttributeString("CompileResult", "Hxs");
                writer.WriteAttributeString("StopWordFile", "msdnFTSstop_Unicode.stp");

                writer.WriteStartElement("IncludeFile");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, ".HxF"));
                writer.WriteEndElement();

                writer.WriteEndElement();

                writer.WriteStartElement("TOCDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, ".HxT"));
                writer.WriteEndElement();

                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "K.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "F.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "N.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "A.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "S.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "B.HxK"));
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultTOC" ProgId="HxDs.HxHierarchy" InitData="AnyString" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultTOC");
                writer.WriteAttributeString("ProgId", "HxDs.HxHierarchy");
                writer.WriteAttributeString("InitData", "AnyString");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultFullTextSearch" ProgId="HxDs.HxFullTextSearch" InitData="AnyString" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultFullTextSearch");
                writer.WriteAttributeString("ProgId", "HxDs.HxFullTextSearch");
                writer.WriteAttributeString("InitData", "AnyString");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultAssociativeIndex" ProgId="HxDs.HxIndex" InitData="A" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultAssociativeIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "A");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultKeywordIndex" ProgId="HxDs.HxIndex" InitData="K" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultKeywordIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "K");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultContextWindowIndex" ProgId="HxDs.HxIndex" InitData="F" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultContextWindowIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "F");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultNamedUrlIndex" ProgId="HxDs.HxIndex" InitData="NamedUrl" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultNamedUrlIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "NamedUrl");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultSearchWindowIndex" ProgId="HxDs.HxIndex" InitData="S" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultSearchWindowIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "S");
                writer.WriteEndElement();


                //  <ItemMoniker Name="!DefaultDynamicLinkIndex" ProgId="HxDs.HxIndex" InitData="B" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultDynamicLinkIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "B");
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.Flush();
                writer.Close();
                writer = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #58
0
        private void WriteFile_Click(object sender, System.EventArgs e)
        {
            string XmlFile;

            System.IO.DirectoryInfo directoryInfo;
            System.IO.DirectoryInfo directoryXML;

            //Get the applications startup path
            directoryInfo = System.IO.Directory.GetParent(Application.StartupPath);

            //Set the output path
            if (directoryInfo.Name.ToString() == "bin")
            {
                directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName);
                XmlFile      = directoryXML.FullName + "\\" + OutputFileName.Text;
            }
            else
            {
                XmlFile = directoryInfo.FullName + "\\" + OutputFileName.Text;
            }

            //create the xml text writer object by providing the filename to write to
            //and the desired encoding.  If the encoding is left null, then the writer
            //assumes UTF-8.
            XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter(XmlFile, null);

            //set the formatting option of the xml file. The default indentation is 2 character spaces.
            //To change the default, use the Indentation property to set the number of IndentChars to use
            //and use the IndentChar property to set the character to use for indentation, such as the
            //tab character. Here the default is used.
            XmlWtr.Formatting = Formatting.Indented;

            //begin to write the xml document. This creates the xml declaration with the version attribute
            //set to "1.0".
            XmlWtr.WriteStartDocument();

            //start the first element.
            XmlWtr.WriteStartElement("customers");

            //create our first customer element.
            //this is a child element of the customers element.
            XmlWtr.WriteStartElement("customer");

            //writes the entire element with the specified element name and
            //string value respectively.
            XmlWtr.WriteElementString("name", "Kevin Anders");
            XmlWtr.WriteElementString("phone", "555.555.5555");

            //end the customer element.
            XmlWtr.WriteEndElement();

            //create another customer.
            XmlWtr.WriteStartElement("customer");
            XmlWtr.WriteElementString("name", "Staci Richard");
            XmlWtr.WriteElementString("phone", "555.122.1552");
            //end the second customer element.
            XmlWtr.WriteEndElement();

            //end the customers element.
            XmlWtr.WriteEndElement();

            //now end the document.
            XmlWtr.WriteEndDocument();

            //now flush the contents of the stream.
            XmlWtr.Flush();

            //close the text writerj and write the xml file.
            XmlWtr.Close();

            statusBar1.Text = "Output file has been written";
        }
Example #59
0
        private void Write_XML()
        {
            XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter("..\\..\\..\\xml\\lh_giostt.xml", null);           //XmlFile

            XmlWtr.Formatting = Formatting.Indented;
            XmlWtr.WriteStartDocument();
            XmlWtr.WriteStartElement("Import");

            h_start = int.Parse(cmbgbd.Text.Substring(0, 2));
            m_start = int.Parse(cmbpbd.Text.Substring(0, 2));
            h_end   = int.Parse(cmbgkt.Text.Substring(0, 2));
            m_end   = int.Parse(cmbpkt.Text.Substring(0, 2));
            int khoangcachthoigian;

            if (rdob10.Checked)
            {
                khoangcachthoigian = 10;
            }
            else
            {
                if (rdob5.Checked)
                {
                    khoangcachthoigian = 5;
                }
                else
                {
                    khoangcachthoigian = 7;
                }
            }

            for (hours = h_start; hours <= h_end; hours++)
            {
                counts++;
                if (counts == 1)
                {
                    //pbd=int.Parse(cmbpbd.Text.Substring(0,2));
                    m_start = int.Parse("00");
                    //pkt=55;
                    m_end = 59;
                }
                else
                {
                    m_start = 0;
                    //pkt=55;
                    m_end = 59;
                }
                if ((counts + h_start) == (h_end + 1))
                {
                    m_start = 0;
                    //pkt=int.Parse(cmbpkt.Text.Substring(0,2));
                    m_end = int.Parse("30");
                }
                for (minutes = m_start; minutes <= m_end; minutes = minutes + 1)
                {
                    lan++;

                    if (hours.ToString().Length == 1)
                    {
                        wss = "0" + hours.ToString();
                    }
                    else
                    {
                        wss = hours.ToString();
                    }
                    if (minutes.ToString().Length == 1)
                    {
                        qss = "0" + minutes.ToString();
                    }
                    else
                    {
                        qss = minutes.ToString();
                    }
                    ass = wss + ":" + qss;
                    XmlWtr.WriteStartElement("Giolam");
                    XmlWtr.WriteElementString("Gio", ass);
                    XmlWtr.WriteElementString("Sothutu", stt.ToString());
                    XmlWtr.WriteElementString("Thoigiantb", khoangcachthoigian.ToString());
                    if (lan == khoangcachthoigian)
                    {
                        stt++;
                        lan = 0;
                    }
                    XmlWtr.WriteEndElement();
                }
            }
            XmlWtr.Flush();
            XmlWtr.Close();
        }
Example #60
0
        private void WriteXML()
        {
//			string XmlFile;
//			System.IO.DirectoryInfo directoryInfo;
//			System.IO.DirectoryInfo directoryXML;
//			directoryInfo = System.IO.Directory.GetParent(Application.StartupPath);
//			if (directoryInfo.Name.ToString() == "bin")
//			{
//				directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName);
//				XmlFile = directoryXML.FullName + "\\" + "gio.xml";
//			}
//			else
//				XmlFile = directoryInfo.FullName + "\\" + "gio.xml";

            XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter("..\\..\\..\\xml\\lh_gio.xml", null);           //XmlFile

            XmlWtr.Formatting = Formatting.Indented;
            XmlWtr.WriteStartDocument();
            XmlWtr.WriteStartElement("Import");

            gbd = int.Parse(cmbgbd.Text.Substring(0, 2));
            pbd = int.Parse(cmbpbd.Text.Substring(0, 2));
            gkt = int.Parse(cmbgkt.Text.Substring(0, 2));
            pkt = int.Parse(cmbpkt.Text.Substring(0, 2));

            for (gio = gbd; gio <= gkt; gio++)
            {
                count++;
                if (count == 1)
                {
                    pbd = int.Parse(cmbpbd.Text.Substring(0, 2));
                    pkt = 55;
                }
                else
                {
                    pbd = 0;
                    pkt = 55;
                }
                if ((count + gbd) == (gkt + 1))
                {
                    pbd = 0;
                    pkt = int.Parse(cmbpkt.Text.Substring(0, 2));
                }
                for (phut = pbd; phut <= pkt; phut = phut + 5)
                {
                    if (gio.ToString().Length == 1)
                    {
                        w = "0" + gio.ToString();
                    }
                    else
                    {
                        w = gio.ToString();
                    }
                    if (phut.ToString().Length == 1)
                    {
                        q = "0" + phut.ToString();
                    }
                    else
                    {
                        q = phut.ToString();
                    }
                    a = w + ":" + q;
                    //cmb.Items.Add(a);

                    XmlWtr.WriteStartElement("Giolam");
                    XmlWtr.WriteElementString("Gio", a);
                    XmlWtr.WriteEndElement();
                }
            }
            XmlWtr.Flush();
            XmlWtr.Close();
        }