public void WriteGestureLog(Dictionary<String, Point3D> gestureDict, string timeStamp)
            {
                using (StringWriter sw = new StringWriter(_sBuilder))
                {
                    using (XmlWriter xmlWriter = new XmlTextWriter(sw))
                    {
                        //START MOVEMENT
                        xmlWriter.WriteStartElement("mov");
                        xmlWriter.WriteStartAttribute("time_stamp");
                        xmlWriter.WriteValue(timeStamp);
                        xmlWriter.WriteEndAttribute();
                        //PRINT ALL JOINTS
                        foreach (var point in gestureDict)
                        {
                            xmlWriter.WriteStartElement(point.Key);//START JOINT
                            xmlWriter.WriteStartElement("x");
                            xmlWriter.WriteValue(point.Value.X);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("Y");
                            xmlWriter.WriteValue(point.Value.Y);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("Z");
                            xmlWriter.WriteValue(point.Value.Z);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndElement();//END JOINT
                        }
                        xmlWriter.WriteEndElement();//END MOV
                    }

                }
                WriteToXMLLogFile();
            }
Exemple #2
0
 public static void Main() {
 StringWriter w = new StringWriter();
 XmlTextWriter x = new XmlTextWriter(w);
 x.Formatting = Formatting.Indented;
 x.WriteStartDocument();
 x.WriteComment("a simple test");
 x.WriteStartElement("message");
 x.WriteStartAttribute("project", "");
 x.WriteString("Rotor");
 x.WriteEndAttribute();
 x.WriteString("Hello world!");
 x.WriteEndElement();
 x.WriteEndDocument();
 x.Flush();
 Console.WriteLine(w.ToString());
 }
Exemple #3
0
        static void Main(string[] args)
        {
            XmlTextWriter xmlWriter = new XmlTextWriter("..//..//TelephoneBook.xml", null);

            xmlWriter.Formatting  = Formatting.Indented;
            xmlWriter.Indentation = 1;

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("MyContacts");

            xmlWriter.WriteStartElement("Contact");
            // Имя контакта
            xmlWriter.WriteStartAttribute("ContactName");
            xmlWriter.WriteString("Someone");
            // Номер телефона контакта
            xmlWriter.WriteStartAttribute("TelephoneNumber");
            xmlWriter.WriteString("111-11-11");

            xmlWriter.WriteEndAttribute();
            xmlWriter.WriteEndElement();

            xmlWriter.Close();
        }
Exemple #4
0
        public void Save()
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

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

                tw.WriteStartDocument();
                tw.WriteStartElement("Scores");

                for (int i = 0; i < entries.Count; i++)
                {
                    tw.WriteStartElement("Score");

                    // Attribute: Name
                    tw.WriteStartAttribute("Name");
                    tw.WriteString(entries[i].Name);
                    tw.WriteEndAttribute();

                    // Content: Score
                    tw.WriteString(entries[i].Score.ToString());

                    tw.WriteEndElement();
                }

                tw.WriteEndDocument();
                tw.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #5
0
        ///<summary>
        /// Save preferences to an Xml file
        ///</summary>
        public void Save(string path)
        {
            using (XmlTextWriter xml = new XmlTextWriter(path, null))
            {
                xml.Indentation = 1;
                xml.IndentChar = '\t';

                xml.WriteStartDocument();
                xml.WriteStartElement(null, "preferences", null);

                foreach (DictionaryEntry entry in _prefs)
                {
                    xml.WriteStartElement(null, "pref", null);
                    xml.WriteStartAttribute(null, "name", null);
                    xml.WriteString((string)entry.Key);
                    xml.WriteEndAttribute();
                    xml.WriteString((string)entry.Value);
                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
                xml.WriteEndDocument();
            }
        }
        private byte[] GetMinimalODF(string _element)
        {
            // Return the minimal xml data for required files in a byte array so in can be written to zip.
            // A bit trickier than necessary because .NET StringWriter is UTF-16 and we want UTF-8.

            MemoryStream  ms   = new MemoryStream();
            XmlTextWriter xmlw = new XmlTextWriter(ms, new System.Text.UTF8Encoding());

            xmlw.Formatting = Formatting.Indented;

            xmlw.WriteStartDocument();
            xmlw.WriteStartElement(_element);
            xmlw.WriteAttributeString("xmlns", "office", null, "urn:oasis:names:tc:opendocument:xmlns:office:1.0");

            xmlw.WriteStartAttribute("office:version");
            xmlw.WriteString("1.1");
            xmlw.WriteEndAttribute();

            xmlw.WriteEndElement();
            xmlw.Flush();
            xmlw.Close();

            return(ms.ToArray());
        }
        /// <summary>
        /// Saves the data in this class to an XML file.
        /// </summary>
        public void SaveData()
        {
            XmlTextWriter writer = null;

            try
            {
                writer             = new XmlTextWriter(File, Encoding.ASCII);
                writer.Indentation = 2;
                writer.Formatting  = Formatting.Indented;
                writer.WriteStartElement("MentalisProxy");
                // Write the version
                writer.WriteStartElement("Version");
                writer.WriteStartAttribute("", "value", "");
                writer.WriteString(Assembly.GetCallingAssembly().GetName().Version.ToString(2));
                writer.WriteEndAttribute();
                writer.WriteEndElement();
                // Write the settings
                SaveSettings(writer);
                // Write the Authentication list to the file
                SaveUsers(writer);
                // Write the Listeners list to the file
                SaveListeners(writer);
                // Clean up
                writer.WriteEndElement();
            }
            catch
            {
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Exemple #8
0
        static void Main()
        {
            var xmlWriter = new XmlTextWriter("TelephoneBook.xml", null);

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("MyContacts");
            xmlWriter.WriteStartElement("Contact");
            xmlWriter.WriteStartAttribute("TelephoneNumber");
            xmlWriter.WriteString("(093)*******");
            xmlWriter.WriteEndAttribute();
            xmlWriter.WriteString("Alex Alexeev");
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();

            xmlWriter.Close();

            Console.SetWindowSize(100, 25);

            FileStream stream = new FileStream("TelephoneBook.xml", FileMode.Open);

            XmlTextReader xmlReader = new XmlTextReader(stream);

            while (xmlReader.Read())
            {
                Console.WriteLine("NodeType: {0,-15}| Name: {1,-15}| Value: {2,-15}",
                                  xmlReader.NodeType,
                                  xmlReader.Name,
                                  xmlReader.Value);
            }

            xmlReader.Close();
            stream.Close();

            // Delay.
            Console.ReadKey();
        }
        private void InsertCellInRow(int RowNumber, String ConditionalCell, XmlTextWriter xtw, int CollNrStart, int CollNrEnd)
        {
            List <int> intListCol           = new List <int>();
            String     ConditionalCellStyle = "";
            String     Style = "";

            styleCellNumber = new Hashtable();


            foreach (string value in ConditionalCell.Split())
            {
                if (value.Contains("-"))
                {
                    ConditionalCellStyle = ConditionalCell.Substring(ConditionalCell.IndexOf(value) + value.Length);
                    Style = ConditionalCellStyle.Substring(0, ConditionalCellStyle.IndexOf('='));

                    string CellStart = value.Substring(0, value.IndexOf('-'));
                    string CellEnd   = value.Substring(value.IndexOf('-') + 1);

                    int RowStart = System.Int32.Parse(CellStart.Substring(CellStart.IndexOf('|') + 1));
                    int ColStart = System.Int32.Parse(CellStart.Substring(0, CellStart.IndexOf('|')));

                    int RowEnd = System.Int32.Parse(CellEnd.Substring(CellEnd.IndexOf('|') + 1));
                    int ColEnd = System.Int32.Parse(CellEnd.Substring(0, CellEnd.IndexOf('|')));

                    if ((RowStart <= RowNumber) && (RowNumber <= RowEnd))
                    {
                        for (int CollNr = ColStart; CollNr <= ColEnd; CollNr++)
                        {
                            if (!intListCol.Contains(CollNr))
                            {
                                if (CollNrStart < CollNr && CollNr < CollNrEnd)
                                {
                                    intListCol.Add(CollNr);
                                    styleCellNumber.Add(CollNr, System.Int32.Parse(Style));
                                }
                            }
                        }
                    }
                }
                else if (value.Contains("|"))
                {
                    ConditionalCellStyle = ConditionalCell.Substring(ConditionalCell.IndexOf(value) + value.Length);
                    Style = ConditionalCellStyle.Substring(0, ConditionalCellStyle.IndexOf('='));

                    int CollNr = System.Int32.Parse(value.Substring(0, value.IndexOf('|')));

                    int Row = System.Int32.Parse(value.Substring(value.IndexOf('|') + 1));

                    if (Row == RowNumber)
                    {
                        if (!intListCol.Contains(CollNr))
                        {
                            if (CollNrStart < CollNr && CollNr < CollNrEnd)
                            {
                                intListCol.Add(CollNr);
                                styleCellNumber.Add(CollNr, System.Int32.Parse(Style));
                            }
                        }
                    }
                }
            }

            intListCol.Sort();

            for (int count = 0; count < intListCol.Count; count++)
            {
                string cell = NumbersToChars(intListCol[count]) + RowNumber.ToString();


                xtw.WriteStartElement(null, "c", null);

                xtw.WriteStartAttribute(null, "r", null);
                xtw.WriteString(cell);
                xtw.WriteEndAttribute();

                string coord = intListCol[count].ToString(System.Globalization.CultureInfo.InvariantCulture)
                               + "|"
                               + RowNumber.ToString(System.Globalization.CultureInfo.InvariantCulture);

                xtw.WriteAttributeString(NS_PREFIX, "p", PACKAGE_NS, coord);

                xtw.WriteAttributeString(NS_PREFIX, "ConditionalStyle", PACKAGE_NS, styleCellNumber[intListCol[count]].ToString());

                xtw.WriteEndElement();
            }
        }
Exemple #10
0
    } //WriteXmlSchemaParticle()

    // XmlSchemaElement
    public static void WriteXmlSchemaElement(XmlSchemaElement element, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartElement("element", XmlSchema.Namespace);
      if (element.Name != null)
      {
        myXmlTextWriter.WriteAttributeString("name", element.Name);
      }//if

      if (!element.RefName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("ref", null);
        myXmlTextWriter.WriteQualifiedName(element.RefName.Name, element.RefName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (!element.SchemaTypeName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("type", null);
        myXmlTextWriter.WriteQualifiedName(element.SchemaTypeName.Name, element.SchemaTypeName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (element.SchemaType != null)
      {
        if (element.SchemaType is XmlSchemaComplexType)
          WriteXmlSchemaComplexType((XmlSchemaComplexType)element.SchemaType, myXmlSchema, myXmlTextWriter);
        else
          WriteXmlSchemaSimpleType((XmlSchemaSimpleType)element.SchemaType, myXmlTextWriter);
      } //if
      myXmlTextWriter.WriteEndElement();
    } //WriteXmlSchemaElement()
Exemple #11
0
        /// <summary>
        /// Writes data stored in memory to an appriopriate text format.
        /// </summary>
        /// <param name="fileName"></param>
        public void DumpToFile(string fileName)
        {
            File.Delete(fileName);
            /* for now, it's better not to sort, to preserve original order */
            // StringRefs.Sort(CompareTlkStringRef);

            int           totalCount   = StringRefs.Count();
            int           count        = 0;
            int           lastProgress = -1;
            XmlTextWriter xr           = new XmlTextWriter(fileName, Encoding.UTF8);

            xr.Formatting  = Formatting.Indented;
            xr.Indentation = 4;

            xr.WriteStartDocument();
            xr.WriteStartElement("tlkFile");
            xr.WriteAttributeString("TLKToolVersion", App.GetVersion());

            xr.WriteComment("Male entries section begin");

            foreach (var s in StringRefs)
            {
                if (s.position == Header.MaleEntryCount)
                {
                    xr.WriteComment("Male entries section end");
                    xr.WriteComment("Female entries section begin");
                }

                xr.WriteStartElement("String");

                xr.WriteStartAttribute("id");
                xr.WriteValue(s.StringID);
                xr.WriteEndAttribute();

                if (s.BitOffset < 0)
                {
                    xr.WriteStartAttribute("calculatedID");
                    xr.WriteValue(-(Int32.MinValue - s.StringID));
                    xr.WriteEndAttribute();

                    xr.WriteString("-1");
                }
                else
                {
                    xr.WriteString(s.Data);
                }

                xr.WriteEndElement(); // </string>

                int progress = (++count * 100) / totalCount;
                if (progress > lastProgress)
                {
                    lastProgress = progress;
                    OnProgressChanged(lastProgress);
                }
            }
            xr.WriteComment("Female entries section end");
            xr.WriteEndElement(); // </tlkFile>
            xr.Flush();
            xr.Close();
        }
Exemple #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="obj"></param>
        public static void LLSDWriteOne(XmlTextWriter writer, object obj)
        {
            if (obj == null)
            {
                writer.WriteStartElement(String.Empty, "undef", String.Empty);
                writer.WriteEndElement();
                return;
            }

            if (obj is string)
            {
                writer.WriteStartElement(String.Empty, "string", String.Empty);
                writer.WriteString((string)obj);
                writer.WriteEndElement();
            }
            else if (obj is int)
            {
                writer.WriteStartElement(String.Empty, "integer", String.Empty);
                writer.WriteString(obj.ToString());
                writer.WriteEndElement();
            }
            else if (obj is double)
            {
                writer.WriteStartElement(String.Empty, "real", String.Empty);
                writer.WriteString(obj.ToString());
                writer.WriteEndElement();
            }
            else if (obj is bool)
            {
                bool b = (bool)obj;
                writer.WriteStartElement(String.Empty, "boolean", String.Empty);
                writer.WriteString(b ? "1" : "0");
                writer.WriteEndElement();
            }
            else if (obj is ulong)
            {
                throw new Exception("ulong in LLSD is currently not implemented, fix me!");
            }
            else if (obj is UUID)
            {
                UUID u = (UUID)obj;
                writer.WriteStartElement(String.Empty, "uuid", String.Empty);
                writer.WriteString(u.ToString());
                writer.WriteEndElement();
            }
            else if (obj is Hashtable)
            {
                Hashtable h = obj as Hashtable;
                writer.WriteStartElement(String.Empty, "map", String.Empty);
                foreach (string key in h.Keys)
                {
                    writer.WriteStartElement(String.Empty, "key", String.Empty);
                    writer.WriteString(key);
                    writer.WriteEndElement();
                    LLSDWriteOne(writer, h[key]);
                }
                writer.WriteEndElement();
            }
            else if (obj is ArrayList)
            {
                ArrayList a = obj as ArrayList;
                writer.WriteStartElement(String.Empty, "array", String.Empty);
                foreach (object item in a)
                {
                    LLSDWriteOne(writer, item);
                }
                writer.WriteEndElement();
            }
            else if (obj is byte[])
            {
                byte[] b = obj as byte[];
                writer.WriteStartElement(String.Empty, "binary", String.Empty);

                writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
                writer.WriteString("base64");
                writer.WriteEndAttribute();

                //// Calculate the length of the base64 output
                //long length = (long)(4.0d * b.Length / 3.0d);
                //if (length % 4 != 0) length += 4 - (length % 4);

                //// Create the char[] for base64 output and fill it
                //char[] tmp = new char[length];
                //int i = Convert.ToBase64CharArray(b, 0, b.Length, tmp, 0);

                //writer.WriteString(new String(tmp));

                writer.WriteString(Convert.ToBase64String(b));
                writer.WriteEndElement();
            }
            else
            {
                throw new LLSDSerializeException("Unknown type " + obj.GetType().Name);
            }
        }
Exemple #13
0
        public void Serialize(System.IO.TextWriter writer)
        {
            DoapNs        doap = new DoapNs();
            RdfNs         rdf  = new RdfNs();
            FoafNs        foaf = new FoafNs();
            StringWriter  sw   = new StringWriter();
            XmlTextWriter w    = new XmlTextWriter(sw);

            string[] urltypes = new string[] { "homepage", "mailing-list",
                                               "download-page", "download-mirror",
                                               "wiki", "bug-database", "screenshots" };

            string[] literaltypes = new string[] {
                "created", "os", "programming-language"
            };

            string[] peopletypes = new string [] {
                "maintainer", "developer", "documenter",
                "translator", "tester", "helper"
            };

            w.WriteStartDocument();

            w.WriteStartElement(null, "content", null);

            foreach (Node proj in model.GetSources(rdf ["type"],
                                                   doap ["Project"]))
            {
                w.WriteStartElement(null, "project", null);

                Node name = model.GetTarget(proj, doap ["name"]);
                w.WriteStartElement("name");
                w.WriteString(name.Literal);
                w.WriteEndElement();

                Node description = model.GetTarget(proj, doap ["description"]);
                w.WriteStartElement("description");
                w.WriteStartAttribute("xml", "lang", null);
                w.WriteString(description.Language);
                w.WriteEndAttribute();
                w.WriteString(description.Literal);
                w.WriteEndElement();

                Node shortdesc = model.GetTarget(proj, doap ["shortdesc"]);
                w.WriteStartElement("shortdesc");
                w.WriteStartAttribute("xml", "lang", null);
                w.WriteString(shortdesc.Language);
                w.WriteEndAttribute();
                w.WriteString(shortdesc.Literal);
                w.WriteEndElement();

                foreach (string p in urltypes)
                {
                    Node r = model.GetTarget(proj, doap [p]);
                    if (r != null)
                    {
                        w.WriteStartElement(p);
                        w.WriteStartAttribute(null, "href", null);
                        w.WriteString(r.Uri.ToString());
                        w.WriteEndElement();
                    }
                }

                foreach (string p in literaltypes)
                {
                    foreach (Node r in model.GetTargets(proj, doap [p]))
                    {
                        w.WriteStartElement(p);
                        w.WriteString(r.Literal);
                        w.WriteEndElement();
                    }
                }

                foreach (string p in peopletypes)
                {
                    foreach (Node r in model.GetTargets(proj, doap [p]))
                    {
                        w.WriteStartElement("person");
                        w.WriteStartAttribute(null, "role", null);
                        w.WriteString(p);
                        w.WriteEndAttribute();

                        Node n  = model.GetTarget(r, foaf ["name"]);
                        Node hp = model.GetTarget(r, foaf ["homepage"]);

                        w.WriteStartAttribute(null, "name", null);
                        w.WriteString(n.Literal);
                        w.WriteEndAttribute();

                        if (hp != null)
                        {
                            w.WriteStartAttribute(null, "homepage", null);
                            w.WriteString(hp.Uri.ToString());
                            w.WriteEndAttribute();
                        }
                        w.WriteEndElement();
                        w.WriteEndElement();
                    }
                }

                w.WriteEndElement();
            }

            w.WriteEndDocument();

            // now do XML transform
            System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(new XmlTextReader(new StringReader(sw.ToString())));
            style.Transform(doc, null, writer, null);
        }
Exemple #14
0
 public object this[string name]
 {
     set
     {
         writer.WriteStartElement(String.Empty, "key", String.Empty);
         writer.WriteString(name);
         writer.WriteEndElement();
         Type t = value.GetType();
         if (t == typeof(bool))
         {
             writer.WriteStartElement(String.Empty, "boolean", String.Empty);
             writer.WriteValue(value);
             writer.WriteEndElement();
         }
         else if (t == typeof(int))
         {
             writer.WriteStartElement(String.Empty, "integer", String.Empty);
             writer.WriteValue(value);
             writer.WriteEndElement();
         }
         else if (t == typeof(uint))
         {
             writer.WriteStartElement(String.Empty, "integer", String.Empty);
             writer.WriteValue(value.ToString());
             writer.WriteEndElement();
         }
         else if (t == typeof(float))
         {
             writer.WriteStartElement(String.Empty, "real", String.Empty);
             writer.WriteValue(value);
             writer.WriteEndElement();
         }
         else if (t == typeof(double))
         {
             writer.WriteStartElement(String.Empty, "real", String.Empty);
             writer.WriteValue(value);
             writer.WriteEndElement();
         }
         else if (t == typeof(string))
         {
             writer.WriteStartElement(String.Empty, "string", String.Empty);
             writer.WriteValue(value);
             writer.WriteEndElement();
         }
         else if (t == typeof(UUID))
         {
             writer.WriteStartElement(String.Empty, "uuid", String.Empty);
             writer.WriteValue(value.ToString()); //UUID has to be string!
             writer.WriteEndElement();
         }
         else if (t == typeof(DateTime))
         {
             writer.WriteStartElement(String.Empty, "date", String.Empty);
             writer.WriteValue(AsString((DateTime)value));
             writer.WriteEndElement();
         }
         else if (t == typeof(Uri))
         {
             writer.WriteStartElement(String.Empty, "uri", String.Empty);
             writer.WriteValue((value).ToString()); //URI has to be string
             writer.WriteEndElement();
         }
         else if (t == typeof(byte[]))
         {
             writer.WriteStartElement(String.Empty, "binary", String.Empty);
             writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
             writer.WriteString("base64");
             writer.WriteEndAttribute();
             writer.WriteValue(Convert.ToBase64String((byte[])value));  //Has to be base64
             writer.WriteEndElement();
         }
         t = null;
     }
 }
        /// <summary>
        /// Writes wrong data in the other file from XML file.
        /// </summary>
        /// <param name="innerXml"></param>
        /// <param name="projects"></param>
        public void WrongDataFromXml(Dictionary <string, string> innerXml, Project[] projects)
        {
            using (FileStream stream = new FileStream(WrongFileDirectory.Value.ToString(), FileMode.Append, FileAccess.Write))
            {
                using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode)
                {
                    Formatting = Formatting.Indented, IndentChar = '\t', Indentation = 1, QuoteChar = '\''
                })
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Recorsds");
                    writer.WriteStartElement("Memeber");
                    foreach (var item in innerXml.Keys)
                    {
                        if (item.Equals("Projects"))
                        {
                            writer.WriteStartElement(item);
                            List <string> projectID = GetProjectID(innerXml[item]);
                            foreach (string id in projectID)
                            {
                                writer.WriteStartElement("Project");
                                writer.WriteStartAttribute("ID");
                                writer.WriteString(id);
                                writer.WriteEndAttribute();
                                writer.WriteEndElement();
                            }
                            writer.WriteEndElement();
                        }

                        if (!item.Equals("Projects"))
                        {
                            writer.WriteStartElement(item);

                            if (string.IsNullOrEmpty(innerXml[item]))
                            {
                                writer.WriteString(" ");
                            }
                            else
                            {
                                writer.WriteString(innerXml[item]);
                            }

                            writer.WriteEndElement();
                        }
                        else
                        {
                            continue;
                        }
                    }

                    writer.WriteEndElement();

                    #region Write Project

                    writer.WriteStartElement("Projects");
                    for (int i = 0; i < projects.Length; i++)
                    {
                        writer.WriteStartElement("Project");

                        writer.WriteStartElement("ProjectID");
                        writer.WriteString(projects[i].ProjectID.ToString());
                        writer.WriteEndElement();

                        writer.WriteStartElement("ProjectName");
                        writer.WriteString(projects[i].ProjectName.ToString());
                        writer.WriteEndElement();

                        writer.WriteStartElement("ProjectCreatedDate");
                        writer.WriteString(projects[i].ProjectCreatedDate.ToString());
                        writer.WriteEndElement();

                        writer.WriteStartElement("ProjectDueDate");
                        writer.WriteString(projects[i].ProjectDueDate.ToString());
                        writer.WriteEndElement();

                        writer.WriteStartElement("ProjectDescription");
                        writer.WriteString(projects[i].ProjectDueDate.ToString());
                        writer.WriteEndElement();

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

                    #endregion

                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
            }
        }
Exemple #16
0
        public override SceneFileResult Export(bool saveAs)
        {
            MogitorsRoot   mogRoot = MogitorsRoot.Instance;
            MogitorsSystem system  = MogitorsSystem.Instance;

            ProjectOptions opt      = mogRoot.ProjectOptions;
            string         fileName = system.CombinePath(opt.ProjectDir, opt.ProjectName + ".mogscene");

            // If saveAs is true, use the MogitorsSystem Function to retrieve
            // a FileName and also copy the contents of current scene to the new location
            if (saveAs)
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName   = "";
                dlg.DefaultExt = ".mogscene";
                dlg.Filter     = "Mogitor Scene File (.mogscene)|*.mogscene";

                Nullable <bool> result = dlg.ShowDialog();
                if (result != true)
                {
                    return(SceneFileResult.Cancel);
                }

                fileName = dlg.FileName;

                string oldProjDir  = opt.ProjectDir;
                string oldProjName = opt.ProjectName;

                opt.ProjectName = system.ExtractFileName(fileName);
                opt.ProjectDir  = system.ExtractFilePath(fileName);

                mogRoot.AdjustUserResourceDirectories(oldProjDir);

                string newDir = opt.ProjectDir;

                system.MakeDirectory(newDir);
                system.CopyFilesEx(oldProjDir, newDir);

                string delFileStr = system.GetFullPath(system.CombinePath(opt.ProjectDir, oldProjName + ".mogscene"));
                system.DeleteFile(delFileStr);
            }

            XmlTextWriter textWriter = new XmlTextWriter(fileName, System.Text.Encoding.Unicode);

            textWriter.Formatting = Formatting.Indented;
            textWriter.WriteStartDocument();
            textWriter.WriteStartElement("MogitorScene");
            mogRoot.WriteProjectOptions(textWriter, true);

            ObjectVector objectList = new ObjectVector();

            for (EditorType type = 0; type < EditorType.LastEditor; ++type)
            {
                mogRoot.GetObjectList(type, objectList);
                foreach (BaseEditor obj in objectList)
                {
                    // If object does not have a parent, then it is not part of the scene
                    if (obj.Parent == null)
                    {
                        continue;
                    }

                    if (obj.IsSerializable)
                    {
                        textWriter.WriteStartElement("Object");
                        textWriter.WriteStartAttribute("Type");
                        textWriter.WriteValue(obj.ObjectTypeName);
                        textWriter.WriteEndAttribute();

                        // If obj's parent name is "" then the parent is this.rootEditor
                        if (obj.Parent.Name != "")
                        {
                            textWriter.WriteStartAttribute("ParentNode");
                            textWriter.WriteValue(obj.Parent.Name);
                            textWriter.WriteEndAttribute();
                        }
                        Mogre.NameValuePairList theList = new Mogre.NameValuePairList();
                        obj.GetObjectProperties(theList);
                        foreach (KeyValuePair <string, string> it in theList)
                        {
                            textWriter.WriteStartAttribute(it.Key);
                            textWriter.WriteValue(it.Value);
                            textWriter.WriteEndAttribute();
                        }
                        textWriter.WriteEndElement();
                    }
                    obj.OnSave();
                }
            }

            textWriter.WriteEndElement();
            textWriter.WriteEndDocument();
            textWriter.Close();

            mogRoot.IsSceneModified = false;

            if (saveAs)
            {
                mogRoot.TerminateScene();
                mogRoot.LoadScene(fileName);
            }
            return(SceneFileResult.Ok);
        }
        /// <summary>
        /// Converts the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="writer">The writer.</param>
        private static void ConvertField(Field field, XmlTextWriter writer)
        {
            switch (field.Type.ToLower())
            {
            case "lookup":
                LookupField lookupField = new LookupField(field);
                if (lookupField.TargetItem != null)
                {
                    string language = lookupField.TargetItem["Regional Iso Code"];
                    if (string.IsNullOrEmpty(language) || !UseRegionalIsoCodeForEnglish)
                    {
                        language = lookupField.TargetItem["Iso"];
                    }

                    if (!string.IsNullOrEmpty(language))
                    {
                        writer.WriteStartAttribute(field.Name, string.Empty);
                        writer.WriteString(language);
                        writer.WriteEndAttribute();
                    }
                }

                break;

            case "link":
                LinkField link = new LinkField(field);
                if (link.InternalPath != string.Empty)
                {
                    writer.WriteStartAttribute(field.Name, string.Empty);
                    writer.WriteString(link.InternalPath);
                    writer.WriteEndAttribute();
                }

                break;

            case "checkbox":
                CheckboxField checkbox = new CheckboxField(field);
                if (field.Name == "mode")
                {
                    if (!checkbox.Checked)
                    {
                        writer.WriteStartAttribute(field.Name, string.Empty);
                        writer.WriteString("off");
                        writer.WriteEndAttribute();
                    }
                }
                else
                {
                    if (checkbox.Checked)
                    {
                        writer.WriteStartAttribute(field.Name, string.Empty);
                        writer.WriteString("true");
                        writer.WriteEndAttribute();
                    }
                }

                break;

            default:
                if (field.Value != string.Empty)
                {
                    writer.WriteStartAttribute(field.Name, string.Empty);
                    writer.WriteString(field.Value);
                    writer.WriteEndAttribute();
                }

                break;
            }
        }
Exemple #18
0
    /// <summary>
    /// Save the map to file.
    /// </summary>
    /// <param name="filename">
    /// A <see cref="System.String"/>
    /// </param>
    private void SaveMap(string filename)
    {
        //XML file
        string xmlFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename) + ".xml");
        //Tile data file
        //string tdFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename) + ".td");

        Log.Write("Saving current map to XML " + xmlFile);

        XmlWriter xmlWriter = new XmlTextWriter(xmlFile, new System.Text.UTF8Encoding());

        xmlWriter.WriteStartDocument();
        xmlWriter.WriteWhitespace("\r\n");
        xmlWriter.WriteStartElement("map");
        xmlWriter.WriteStartAttribute("id");
        xmlWriter.WriteValue(model.MapID);
        xmlWriter.WriteEndAttribute();

        //Write dimensions
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteStartElement("geometry");

        //Write dimensions
        xmlWriter.WriteWhitespace("\r\n\t\t");
        xmlWriter.WriteStartElement("width");
        xmlWriter.WriteValue(model.TileMap.Width);
        xmlWriter.WriteEndElement();

        xmlWriter.WriteWhitespace("\r\n\t\t");
        xmlWriter.WriteStartElement("height");
        xmlWriter.WriteValue(model.TileMap.Height);
        xmlWriter.WriteEndElement();

        xmlWriter.WriteWhitespace("\r\n\t\t");
        xmlWriter.WriteStartElement("layers");
        xmlWriter.WriteValue(model.TileMap.Layers);
        xmlWriter.WriteEndElement();

        xmlWriter.WriteWhitespace("\r\n\t\t");
        xmlWriter.WriteStartElement("tilesize");
        xmlWriter.WriteValue(model.TileMap.Tilesize);
        xmlWriter.WriteEndElement();

        //Offsets
        xmlWriter.WriteWhitespace("\r\n\t\t");
        xmlWriter.WriteStartElement("xoffset");
        xmlWriter.WriteValue(model.TileMap.OffsetX);
        xmlWriter.WriteEndElement();

        xmlWriter.WriteWhitespace("\r\n\t\t");
        xmlWriter.WriteStartElement("yoffset");
        xmlWriter.WriteValue(model.TileMap.OffsetY);
        xmlWriter.WriteEndElement();

        //Geometry end
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteEndElement();
        xmlWriter.WriteWhitespace("\r\n");

        //Tileset
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteStartElement("tileset");
        {

            bool foundTileset = false;
            foreach (string tsName in model.ResourceManager.Tilesets)
            {
                Tileset ts = model.ResourceManager.GetTileset(tsName);
                if (ts == model.CurrentTileset)
                {
                    xmlWriter.WriteValue(tsName);
                    foundTileset = true;
                    break;
                }
            }
            if (!foundTileset)
            {
                throw new NotFoundException("Tileset was not found in resource manager. This should not happen! What did you do?");
            }
        }

        xmlWriter.WriteEndElement();

        //Background
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteStartElement("background");
        xmlWriter.WriteValue(model.Background);
        xmlWriter.WriteEndElement();
        xmlWriter.WriteWhitespace("\r\n");

        //Extra properties
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteStartElement("properties");
        foreach (KeyValuePair<string, string> o in model.ExtraProperties)
        {
            xmlWriter.WriteWhitespace("\r\n\t\t");
            xmlWriter.WriteStartElement(o.Key);
            xmlWriter.WriteValue(o.Value);
            xmlWriter.WriteEndElement();
        }
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteEndElement();
        xmlWriter.WriteWhitespace("\r\n");

        //Write objects
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteStartElement("objects");
        foreach (MapObject o in model.Objects)
        {
            xmlWriter.WriteWhitespace("\r\n\t\t");
            xmlWriter.WriteStartElement("object");

            xmlWriter.WriteWhitespace("\r\n\t\t\t");
            xmlWriter.WriteStartElement("name");
            xmlWriter.WriteValue(o.Name);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteWhitespace("\r\n\t\t\t");
            xmlWriter.WriteStartElement("x-pos");
            xmlWriter.WriteValue(o.Position.X);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteWhitespace("\r\n\t\t\t");
            xmlWriter.WriteStartElement("y-pos");
            xmlWriter.WriteValue(o.Position.Y);
            xmlWriter.WriteEndElement();

            foreach (KeyValuePair<string, string> p in o.ExtraProperties)
            {
                xmlWriter.WriteWhitespace("\r\n\t\t\t");
                xmlWriter.WriteStartElement(p.Key);
                xmlWriter.WriteValue(p.Value);
                xmlWriter.WriteEndElement();
            }
            //Object end
            xmlWriter.WriteWhitespace("\r\n\t\t");
            xmlWriter.WriteEndElement();
        }
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteEndElement();
        xmlWriter.WriteWhitespace("\r\n");

        //Write tiledata
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteStartElement("tiledata");
        xmlWriter.WriteAttributeString("encoding", "base64");

        TileMap tm = model.TileMap;
        byte[] tiledata = new byte[tm.Width*tm.Height*tm.Layers*sizeof(int)];

        //Convert the 3D array to a byte stream for input into the XML file as base64 encoding
        for (int x = 0; x < model.TileMap.Width; x++)
        {
            for (int y = 0; y < model.TileMap.Height; y++)
            {
                for (int z = 0; z < model.TileMap.Layers; z++)
                {
                    for (int i = 0; i < sizeof(int); i++)
                    {
                        int index = i + z*sizeof(int) + y*sizeof(int)*model.TileMap.Layers + x*sizeof(int)*model.TileMap.Layers*model.TileMap.Height;
                        tiledata[index] = (byte)((tm.GetTile(x, y, z).Id & (255 << (i*8))) >> (i*8));
                    }
                }
            }
        }

        string base64Tiledata = Convert.ToBase64String(tiledata);
        int rowLength = 128;
        for (int i = 0; i < base64Tiledata.Length; i+=rowLength)
        {
            xmlWriter.WriteWhitespace("\r\n\t\t");
            xmlWriter.WriteValue(base64Tiledata.Substring(i, Math.Min(rowLength, base64Tiledata.Length-i)));
        }

        //tiledata end
        xmlWriter.WriteWhitespace("\r\n\t");
        xmlWriter.WriteEndElement();

        //map end
        xmlWriter.WriteWhitespace("\r\n");
        xmlWriter.WriteEndElement();

        xmlWriter.Close();
    }
Exemple #19
0
    } //WriteExampleAttributes()

    // Write a single example attribute
    public static void WriteExampleAttribute(XmlSchemaAttribute attribute, XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartAttribute(attribute.QualifiedName.Name, attribute.QualifiedName.Namespace);
      // The examples value
      WriteExampleValue(attribute.AttributeType, myXmlTextWriter);
      myXmlTextWriter.WriteEndAttribute();
    } //WriteExampleAttribute()
Exemple #20
0
    public void Index()
    {
       
            //SEARCHING FOR DIRECTORIES IN ASSETS DIRECTORY, WHICH ARE THEMES
            //string searchPath = Path.Combine(HttpRuntime.AppDomainAppVirtualPath, "Assets");
            string searchPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Assets");
            string[] dirs = Directory.GetDirectories(searchPath, "*");
            List<int> ids = new List<int>();

            foreach (string dir in dirs)
            {
                int directoryId;
                if (int.TryParse(new DirectoryInfo(dir).Name, out directoryId))
                {
                    ids.Add(Convert.ToInt32(new DirectoryInfo(dir).Name));
                }
            }

            var stages = ServerModel.DB.Load<TblResources>("CourseRef", ids);
            string xmlindex = Path.Combine(HttpRuntime.AppDomainAppPath, "tomcat-solr\\apache-solr-1.4.0\\Iudico\\");

        try
        {            
            //DELETING PREVIOUS CREATING XMLs
            string[] filePaths = Directory.GetFiles(xmlindex, "*.xml");
            foreach (string filePath in filePaths)
            {
                File.Delete(filePath);
            }


            //DELETING SOLR INDEX
            HttpWebRequest request = WebRequest.Create("http://localhost:8080/apache-solr-1.4.0/update?stream.body=%3Cdelete%3E%3Cquery%3Ename:*%3C/query%3E%3C/delete%3E") as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            { }

            HttpWebRequest requestCommit = WebRequest.Create("http://localhost:8080/apache-solr-1.4.0/update?stream.body=%3Ccommit/%3E") as HttpWebRequest;
            using (HttpWebResponse response = requestCommit.GetResponse() as HttpWebResponse)
            { }

        }
        catch (Exception ex)
        {
            if (ex.Message.ToString() == "Unable to connect to the remote server")
            {
                System.Diagnostics.Process procTomcat = new System.Diagnostics.Process();
                procTomcat.EnableRaisingEvents = false;
                procTomcat.StartInfo.FileName = Path.Combine(HttpRuntime.AppDomainAppPath, "tomcat-solr\\tomcatStart.bat");
                procTomcat.Start();
            }
        }

        //CREATING NEW INDEX
        string filename = "";
        int i = 0;
        XmlTextWriter writer;

        try
        {
            foreach (TblResources res in stages)
            {
                i++;

                filename = "XML" + i.ToString() + DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + DateTime.Now.TimeOfDay.Seconds.ToString() + ".xml";

                //CREATING XML WITH ID, NAME AND CONTENT OF THEME
                writer = new XmlTextWriter(xmlindex + filename, null);
                writer.WriteStartElement("add");
                writer.WriteStartElement("doc");
                writer.WriteStartElement("field");
                writer.WriteStartAttribute("name");
                writer.WriteString("id");
                writer.WriteEndAttribute();
                writer.WriteString(res.CourseRef.ToString());
                writer.WriteEndElement();

                var stages2 = ServerModel.DB.Load<TblCourses>(res.CourseRef);

                string name = stages2.Name;

                writer.WriteStartElement("field");
                writer.WriteStartAttribute("name");
                writer.WriteString("name");
                writer.WriteEndAttribute();
                writer.WriteString(name);
                writer.WriteEndElement();

                string filePath = Path.Combine(CourseManager.GetCoursePath(res.CourseRef), res.Href.ToString());
                FileStream file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
                StreamReader sr = new StreamReader(file);
                string s = sr.ReadToEnd();
                sr.Close();
                file.Close();

                IHTMLDocument2 doc = new HTMLDocumentClass();
                doc.write(new object[] { s });
                doc.close();

                writer.WriteStartElement("field");
                writer.WriteStartAttribute("name");
                writer.WriteString("content");
                writer.WriteEndAttribute();
                writer.WriteString(doc.body.innerText);
                writer.WriteEndElement();

                writer.Flush();
                writer.Close();
                //Response.Write(res.Href + "<br>");


                //INDEXING OF XML BY METHOD POST VIA HTTP
                Encoding xmlEncoding = Encoding.UTF8;

                string filePathXml = xmlindex + filename;
                FileStream fileXML = new FileStream(filePathXml, FileMode.OpenOrCreate, FileAccess.Read);
                StreamReader sr1 = new StreamReader(fileXML);
                string ss = sr1.ReadToEnd();
                sr1.Close();
                fileXML.Close();

                HttpWebRequest requestIndex = WebRequest.Create("http://localhost:8080/apache-solr-1.4.0/update") as HttpWebRequest;
                requestIndex.Method = "POST";
                requestIndex.ContentType = "text/xml; charset=utf-8";
                requestIndex.ProtocolVersion = HttpVersion.Version10;
                requestIndex.KeepAlive = false;

                byte[] data = xmlEncoding.GetBytes(ss);
                requestIndex.ContentLength = ss.Length;

                using (var postParams = requestIndex.GetRequestStream())
                {
                    postParams.Write(data, 0, data.Length);
                    using (var response = requestIndex.GetResponse())
                    {
                        using (var rStream = response.GetResponseStream())
                        {
                            string r = xmlEncoding.GetString(ReadFully(rStream));
                        }
                    }
                }

            }


            HttpWebRequest requestCommit1 = WebRequest.Create("http://localhost:8080/apache-solr-1.4.0/update?stream.body=%3Ccommit/%3E") as HttpWebRequest;
            using (HttpWebResponse response = requestCommit1.GetResponse() as HttpWebResponse)
            {


            }


        }
        catch (Exception ex)
        {
            if (ex.Message.ToString() == "Unable to connect to the remote server")
            {
                System.Diagnostics.Process procTomcat = new System.Diagnostics.Process();
                procTomcat.EnableRaisingEvents = false;
                procTomcat.StartInfo.FileName = Path.Combine(HttpRuntime.AppDomainAppPath, "tomcat-solr\\tomcatStart.bat");
                procTomcat.Start();
            }
        }

    }
Exemple #21
0
        /// <summary>
        /// Ecrit la représentation Xml d'une propriété.
        /// </summary>
        /// <param name="xmlWriter">Writer XML.</param>
        /// <param name="property">Propriété.</param>
        /// <param name="propertyValue">Valeur de la propriété.</param>
        private static void WriteProperty(XmlTextWriter xmlWriter, BeanPropertyDescriptor property, object propertyValue)
        {
            ICollection collection = propertyValue as ICollection;

            if (property.PrimitiveType == typeof(byte[]))
            {
                xmlWriter.WriteStartElement(XmlNodeProperty);
                xmlWriter.WriteStartAttribute(XmlNameAttribute);
                xmlWriter.WriteName(property.PropertyName);
                xmlWriter.WriteEndAttribute();
                if (propertyValue != null)
                {
                    xmlWriter.WriteCData(Convert.ToBase64String((byte[])propertyValue));
                }
                else
                {
                    xmlWriter.WriteCData(string.Empty);
                }

                xmlWriter.WriteEndElement();
            }
            else if (collection != null)
            {
                xmlWriter.WriteStartElement(XmlNodeCollection);
                xmlWriter.WriteStartAttribute(XmlNameAttribute);
                xmlWriter.WriteName(property.PropertyName);
                xmlWriter.WriteEndAttribute();
                foreach (object data in collection)
                {
                    WriteProperty(xmlWriter, property, data);
                }

                xmlWriter.WriteEndElement();
            }
            else if (property.PrimitiveType == null)
            {
                xmlWriter.WriteStartElement(XmlNodeObject);
                xmlWriter.WriteStartAttribute(XmlNameAttribute);
                xmlWriter.WriteName(property.PropertyName);
                xmlWriter.WriteEndAttribute();

                WriteProperties(xmlWriter, propertyValue);

                xmlWriter.WriteEndElement();
            }
            else
            {
                xmlWriter.WriteStartElement(XmlNodeProperty);
                xmlWriter.WriteStartAttribute(XmlNameAttribute);
                xmlWriter.WriteName(property.PropertyName);
                xmlWriter.WriteEndAttribute();

                if (propertyValue != null)
                {
                    if (propertyValue.GetType() == typeof(ExtendedValue))
                    {
                        xmlWriter.WriteCData(property.ConvertToString(propertyValue));
                    }
                    else if (propertyValue.GetType() == typeof(DateTime))
                    {
                        if (property.DomainName == "DO_JOUR_MOIS")
                        {
                            xmlWriter.WriteCData(((DateTime)propertyValue).ToString("dd/MM", DateTimeFormatInfo.CurrentInfo));
                        }
                        else
                        {
                            xmlWriter.WriteCData(property.ConvertToString(propertyValue));
                        }
                    }
                    else if (propertyValue.GetType() == typeof(bool))
                    {
                        xmlWriter.WriteCData(Convert.ToString(propertyValue, CultureInfo.CurrentCulture));
                    }
                    else
                    {
                        xmlWriter.WriteCData(property.ConvertToString(propertyValue));
                    }
                }

                xmlWriter.WriteEndElement();
            }
        }
Exemple #22
0
        private static void SaveRegion(Region region, XmlTextWriter writer)
        {
            writer.WriteStartElement("region");

            if (region.Type != null)
            {
                writer.WriteStartAttribute("type");
                writer.WriteValue(region.Type);
                writer.WriteEndAttribute();
            }

            if (region.Priority != 9999)
            {
                writer.WriteStartAttribute("priority");
                writer.WriteValue(region.Priority);
                writer.WriteEndAttribute();
            }

            if (region.Name != null)
            {
                writer.WriteStartAttribute("name");
                writer.WriteValue(region.Name);
                writer.WriteEndAttribute();
            }

            if (region.RuneName != null)
            {
                writer.WriteStartElement("rune");

                writer.WriteStartAttribute("name");
                writer.WriteValue(region.RuneName);
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.Area.Count > 0)
            {
                SaveAreas(region.Area, writer);
            }

            if (region.GoLocation.X != 9999 && region.GoLocation.Y != 9999 && region.GoLocationZ != 9999)
            {
                writer.WriteStartElement("go");

                writer.WriteStartAttribute("x");
                writer.WriteValue(region.GoLocation.X);
                writer.WriteEndAttribute();

                writer.WriteStartAttribute("y");
                writer.WriteValue(region.GoLocation.Y);
                writer.WriteEndAttribute();

                writer.WriteStartAttribute("z");
                writer.WriteValue(region.GoLocationZ);
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.Entrance.X != 9999 && region.Entrance.Y != 9999)
            {
                writer.WriteStartElement("entrance");

                writer.WriteStartAttribute("x");
                writer.WriteValue(region.Entrance.X);
                writer.WriteEndAttribute();

                writer.WriteStartAttribute("y");
                writer.WriteValue(region.Entrance.Y);
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.MusicName != null)
            {
                writer.WriteStartElement("music");

                writer.WriteStartAttribute("name");
                writer.WriteValue(region.MusicName);
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.MinZRange != 9999)
            {
                writer.WriteStartElement("zrange");

                writer.WriteStartAttribute("min");
                writer.WriteValue(region.MinZRange);
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (!region.LogoutDelayActive)
            {
                writer.WriteStartElement("logoutDelay");

                writer.WriteStartAttribute("active");
                writer.WriteValue(XmlConvert.ToString(region.LogoutDelayActive));
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.GuardsDisabled)
            {
                writer.WriteStartElement("guards");

                writer.WriteStartAttribute("disabled");
                writer.WriteValue(XmlConvert.ToString(region.GuardsDisabled));
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.SmartNoHousing)
            {
                writer.WriteStartElement("smartNoHousing");

                writer.WriteStartAttribute("active");
                writer.WriteValue(XmlConvert.ToString(region.SmartNoHousing));
                writer.WriteEndAttribute();

                writer.WriteEndElement();
            }

            if (region.Type == "QuestOfferRegion" || region.Type == "CancelQuestRegion")
            {
                writer.WriteStartElement("quest");

                if (region.QuestType != null)
                {
                    writer.WriteStartAttribute("type");
                    writer.WriteValue(region.QuestType);
                    writer.WriteEndAttribute();
                }

                writer.WriteEndElement();
            }

            if (region.Type == "QuestNoEntryRegion")
            {
                writer.WriteStartElement("quest");

                if (region.QuestType != null)
                {
                    writer.WriteStartAttribute("type");
                    writer.WriteValue(region.QuestType);
                    writer.WriteEndAttribute();
                }

                if (region.QuestMin != null)
                {
                    writer.WriteStartAttribute("min");
                    writer.WriteValue(region.QuestMin);
                    writer.WriteEndAttribute();
                }

                if (region.QuestMessage != 0)
                {
                    writer.WriteStartAttribute("message");
                    writer.WriteValue(region.QuestMessage);
                    writer.WriteEndAttribute();
                }

                writer.WriteEndElement();
            }

            if (region.Type == "QuestCompleteObjectiveRegion")
            {
                writer.WriteStartElement("quest");

                if (region.QuestType != null)
                {
                    writer.WriteStartAttribute("type");
                    writer.WriteValue(region.QuestType);
                    writer.WriteEndAttribute();
                }

                if (region.QuestComplete != null)
                {
                    writer.WriteStartAttribute("complete");
                    writer.WriteValue(region.QuestComplete);
                    writer.WriteEndAttribute();
                }

                writer.WriteEndElement();
            }

            if (region.Spawns.Count > 0)
            {
                SaveSpawns(region.Spawns, writer);
            }

            foreach (Region r in region.Regions)
            {
                SaveRegion(r, writer);
            }

            writer.WriteEndElement();
        }
Exemple #23
0
        private bool CompareResult(XmlNode testCase, string sourceFile, object value, bool xmlCompare)
        {
            string id       = ((XmlElement)testCase).GetAttribute("name");
            bool   isSingle = false;
            bool   isExcpt  = (id == "fn-union-node-args-005") ||
                              (id == "fn-union-node-args-006") || (id == "fn-union-node-args-007") ||
                              (id == "fn-union-node-args-009") || (id == "fn-union-node-args-010") ||
                              (id == "fn-union-node-args-011");

            if (id == "ReturnExpr010")
            {
                xmlCompare = true;
            }
            if (id != "CondExpr012" && id != "NodeTest006")
            {
                if (value is XPathItem)
                {
                    isSingle = true;
                }
                else if (value is XPath2NodeIterator)
                {
                    XPath2NodeIterator iter = (XPath2NodeIterator)value;
                    isSingle = iter.IsSingleIterator;
                }
            }
            XmlDocument doc1 = new XmlDocument(_nameTable);

            if (xmlCompare)
            {
                doc1.Load(sourceFile);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version='1.0'?>");
                sb.Append("<root>");
                TextReader textReader = new StreamReader(sourceFile, true);
                sb.Append(textReader.ReadToEnd());
                textReader.Close();
                sb.Append("</root>");
                doc1.LoadXml(sb.ToString());
            }
            MemoryStream ms     = new MemoryStream();
            XmlWriter    writer = new XmlTextWriter(ms, Encoding.UTF8);

            if (!(xmlCompare && isSingle || isExcpt))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement(doc1.DocumentElement.Name, "");
            }
            if (value is XPath2NodeIterator)
            {
                bool string_flag = false;
                foreach (XPathItem item in (XPath2NodeIterator)value)
                {
                    if (item.IsNode)
                    {
                        XPathNavigator nav = (XPathNavigator)item;
                        if (nav.NodeType == XPathNodeType.Attribute)
                        {
                            writer.WriteStartAttribute(nav.Prefix, nav.LocalName, nav.NamespaceURI);
                            writer.WriteString(nav.Value);
                            writer.WriteEndAttribute();
                        }
                        else
                        {
                            writer.WriteNode(nav, false);
                        }
                        string_flag = false;
                    }
                    else
                    {
                        if (string_flag)
                        {
                            writer.WriteString(" ");
                        }
                        writer.WriteString(item.Value);
                        string_flag = true;
                    }
                }
            }
            else
            if (value is XPathItem)
            {
                XPathItem item = (XPathItem)value;
                if (item.IsNode)
                {
                    writer.WriteNode((XPathNavigator)item, false);
                }
                else
                {
                    writer.WriteString(item.Value);
                }
            }
            else
            {
                if (value != Undefined.Value)
                {
                    writer.WriteString(XPath2Convert.ToString(value));
                }
            }
            if (!(xmlCompare && isSingle || isExcpt))
            {
                writer.WriteEndElement();
            }
            writer.Flush();
            ms.Position = 0;
            XmlDocument doc2 = new XmlDocument(_nameTable);

            doc2.Load(ms);
            writer.Close();
            TreeComparer comparer = new TreeComparer();

            comparer.IgnoreWhitespace = true;
            bool res = comparer.DeepEqual(doc1.CreateNavigator(), doc2.CreateNavigator());

            return(res);
        }
        public void SaveToXml(string path)
        {
            lock (this) {
                uint timer_id = Hyena.Log.DebugTimerStart();
                bool success  = false;

                try {
                    XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
                    writer.Formatting  = Formatting.Indented;
                    writer.Indentation = 2;
                    writer.IndentChar  = ' ';

                    writer.WriteStartDocument(true);

                    writer.WriteStartElement("banshee-collection");
                    writer.WriteStartAttribute("version");
                    writer.WriteString(TrackInfo.ExportVersion);
                    writer.WriteEndAttribute();

                    for (int i = 0; i < model_caches.Count; i++)
                    {
                        CachedList <DatabaseTrackInfo> model = model_caches[i];
                        if (model.Count <= 0)
                        {
                            continue;
                        }

                        writer.WriteStartElement("model");
                        for (int j = 0; j < model.Count; j++)
                        {
                            writer.WriteStartElement("item");

                            foreach (KeyValuePair <string, object> item in model[j].GenerateExportable(export_fields))
                            {
                                string type = "string";
                                if (item.Value is Boolean)
                                {
                                    type = "bool";
                                }
                                else if (item.Value is Byte)
                                {
                                    type = "byte";
                                }
                                else if (item.Value is SByte)
                                {
                                    type = "sbyte";
                                }
                                else if (item.Value is Int16)
                                {
                                    type = "short";
                                }
                                else if (item.Value is UInt16)
                                {
                                    type = "ushort";
                                }
                                else if (item.Value is Int32)
                                {
                                    type = "int";
                                }
                                else if (item.Value is UInt32)
                                {
                                    type = "uint";
                                }
                                else if (item.Value is Int64)
                                {
                                    type = "long";
                                }
                                else if (item.Value is UInt64)
                                {
                                    type = "ulong";
                                }
                                else if (item.Value is Char)
                                {
                                    type = "char";
                                }
                                else if (item.Value is Double)
                                {
                                    type = "double";
                                }
                                else if (item.Value is Single)
                                {
                                    type = "float";
                                }

                                writer.WriteStartElement(item.Key);
                                writer.WriteStartAttribute("type");
                                writer.WriteString(type);
                                writer.WriteEndAttribute();
                                writer.WriteString(item.Value.ToString());
                                writer.WriteEndElement();
                            }

                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                    }

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

                    success = true;
                } catch (Exception e) {
                    Log.Exception(e);
                }

                Hyena.Log.DebugTimerPrint(timer_id, "CollectionIndexer.SaveToXml: {0}");

                SaveToXmlFinishedHandler handler = save_to_xml_finished;
                if (handler != null)
                {
                    handler(success, path);
                }
            }
        }
Exemple #25
0
 private void WriteXMLAttribute(string AttrName, string AttrValue, XmlTextWriter xmlOutput)
 {
     xmlOutput.WriteStartAttribute(AttrName);
     xmlOutput.WriteString(AttrValue);
     xmlOutput.WriteEndAttribute();
 }
    private static void SqlDataReaderToXml(
    SqlDataReader AReader,
    //DataTable     ADataTable,
    XmlTextWriter AWriter,
    Boolean       ASkipNameColumn,
    String        ARowTag,
    TRowSetMap    AMap
  )
    {
        const String ROW_TAG      = "ROW";
        const String METADATA_TAG = "METADATA";
        const String FIELD_TAG    = "FIELD";
        const String NONAME_FIELD_PREFIX = "FIELD";

        int
          i,
          start_field_index   = ASkipNameColumn ? 1 : 0,
          empty_name_field_no = 1;
        String FieldName;

        DataTable LDataTable = AReader.GetSchemaTable();

        List<TFieldAlias> LFields = new List<TFieldAlias>();
        TFieldAlias LField;
        int FieldCount = AReader.FieldCount;

        if(AMap.Fields.Length > 0)
        {
          foreach (String FieldMap in AMap.Fields.Split(new char[] {','}))
          {
        i = FieldMap.IndexOf('=');
        if(i >= 0)
        {
          LField.Name = FieldMap.Substring(0, i);
          FieldName   = FieldMap.Substring(i + 1);
        }
        else
        {
          LField.Name = FieldMap;
          FieldName   = FieldMap;
        }
        for(i = start_field_index; i < FieldCount; i++)
        {
          if(FieldName.Equals(AReader.GetName(i), StringComparison.InvariantCultureIgnoreCase))
            break;
        }
        if((i < 0) || (i >= FieldCount))
          throw new SystemException("RowSet Field = [" + FieldName + "] not found.");
        // LField.Name = XmlConvert.EncodeLocalName(LField.Name);
        LField.FieldIndex = i;
        LFields.Add(LField);

        //AWriter.WriteStartAttribute(LField.Name);
        //AWriter.WriteValue(SqlMetaDataToString(LDataTable.Rows[i]));
          }
        }
        else
        {
          for(LField.FieldIndex = start_field_index; LField.FieldIndex < FieldCount; LField.FieldIndex++)
          {
        FieldName = AReader.GetName(LField.FieldIndex);
        if(FieldName.Length == 0)
          FieldName = NONAME_FIELD_PREFIX + (empty_name_field_no++).ToString();
        LField.Name = FieldName;
        //LField.Name = XmlConvert.EncodeLocalName(FieldName);
        LFields.Add(LField);

        //AWriter.WriteStartAttribute(LField.Name);
        //AWriter.WriteValue(SqlMetaDataToString(LDataTable.Rows[LField.FieldIndex]));
          }
        }

        AWriter.WriteStartElement(METADATA_TAG);
        for (i = 0; i < LFields.Count; i++)
        {
          AWriter.WriteStartElement(FIELD_TAG);
        AWriter.WriteStartAttribute(ATTRIBUTE_INDEX);
        AWriter.WriteValue(i + 1);
        AWriter.WriteStartAttribute(ATTRIBUTE_NAME);
        AWriter.WriteValue(LFields[i].Name);
        AWriter.WriteStartAttribute(ATTRIBUTE_TYPE);
        AWriter.WriteValue(SqlMetaDataToString(LDataTable.Rows[LFields[i].FieldIndex]));
          AWriter.WriteEndElement();
        }
        AWriter.WriteEndElement();

        object Value;
        while (AReader.Read())
        {
          AWriter.WriteStartElement(ARowTag ?? ROW_TAG);

          for (i = 0; i < LFields.Count; i++)
          {
        Value = AReader.GetValue(LFields[i].FieldIndex);
        if (Value != DBNull.Value) // NULL пропускаем
        {
          AWriter.WriteStartAttribute(XmlConvert.EncodeLocalName(LFields[i].Name));
          try
          {
            AWriter.WriteValue(Value);
          }
          catch (InvalidCastException)
          {
            AWriter.WriteValue(Value.ToString());
          }

          AWriter.WriteEndAttribute();
        }
          }
          AWriter.WriteEndElement();
        }
    }
Exemple #27
0
        public static bool GerarArquivoXml(List <objNota.xPag> lstPag, string rodape, List <objNota.Produto> lst, List <objNota.Xdest> lstDest)
        {
            string caminhoNFCe = string.Empty;

            valorTotal = 0;
            int ano = Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
            int mes = Convert.ToInt32(DateTime.Now.Month.ToString());

            if (!PingContigencia())
            {
                Global.tpEmis = "9";
            }
            if (PingContigencia())
            {
                Global.tpEmis = "1";
            }
            if (Global.tpEmis == "9")
            {
                caminhoNFCe = Global.PastaValidar;
            }

            if (Global.tpEmis != "9")
            {
                caminhoNFCe = @"C:\\ASAsys\\ASAsysNFCE";
            }
            string Chave = montaChaveAcessoNFe(Global.UnidadeFederativaCodigo, ano, mes, Global.CNPJ, Global.Serie, Global.Nota, Global.tpEmis);

            try
            {
                UTF8Encoding  _utf8 = new UTF8Encoding();
                XmlTextWriter _xml  = new XmlTextWriter(caminhoNFCe + "\\" + Chave + "-nfe.xml", _utf8);
                _xml.WriteStartDocument();
                #region NFe
                _xml.WriteStartElement("NFe", "http://www.portalfiscal.inf.br/nfe");// TAG raiz da NF-e, Nó com tipo de

                #region infNFe
                _xml.WriteStartElement("infNFe"); //Grupo que contém as informações da NF-e;

                _xml.WriteStartAttribute("Id");   // informar a chave de acesso da

                _xml.WriteString("NFe" + Chave);
                _xml.WriteEndAttribute();

                _xml.WriteStartAttribute("versao"); ////Versão do leiaute (v2.0),Atributos do Nó
                _xml.WriteString("3.10");           //vesao da nfe.
                _xml.WriteEndAttribute();

                #region ide
                _xml.WriteStartElement("ide");                    //ide (inserida como filha na tag infNFe)
                _xml.WriteStartElement("cUF");                    //Código da UF do emitente do Documento Fiscal. Utilizar a Tabela do IBGE de código de unidades da federação (Anexo IV - Tabela de UF, Município e País).
                _xml.WriteString(Global.UnidadeFederativaCodigo); // Código da Uf, tam. 2
                _xml.WriteEndElement();

                _xml.WriteStartElement("cNF");            //Código numérico que compõe a Chave de Acesso. Número aleatório gerado pelo emitente para cada NF-e para evitar acessos indevidos da NF-e.(v2.0)
                _xml.WriteString(Chave.Substring(35, 8)); // Código da Nf, tam. 8
                _xml.WriteEndElement();

                _xml.WriteStartElement("natOp");                           //Descrição da Natureza da Operação
                _xml.WriteString("VENDAS DE PRODUCAO DO ESTABELECIMENTO"); // Tam. 1-60
                _xml.WriteEndElement();

                _xml.WriteStartElement("indPag"); //Indicador forma de pagamento; 0 – pagamento à vista;1 – pagamento à prazo;2 - outros.
                _xml.WriteString("0");            // tam. 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("mod"); //Código do Modelo do Documento Fiscal
                _xml.WriteString("65");        // tam. 2; Utilizar o código 55 para identificação da NF-e, emitida em substituição ao modelo 1 ou 1A.
                _xml.WriteEndElement();

                _xml.WriteStartElement("serie"); //Série do Documento Fiscal
                _xml.WriteString(Global.Serie);  // Tam 1-3
                _xml.WriteEndElement();

                _xml.WriteStartElement("nNF"); //Número do Documento Fiscal
                _xml.WriteString(Global.Nota); // Tam. 1 - 9
                _xml.WriteEndElement();

                _xml.WriteStartElement("dhEmi");                                                     //Data de emissão do Documento Fiscal
                _xml.WriteString(String.Format("{0:yyyy-MM-ddTHH:mm:ss}", DateTime.Now) + "-03:00"); // Formato “AAAA-MM-DD”
                _xml.WriteEndElement();


                _xml.WriteStartElement("tpNF"); //Tipo de Operação
                _xml.WriteString("1");          // 0-entrada / 1-saída, tam. 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("idDest"); //Código do Município de Ocorrência do Fato Gerador
                _xml.WriteString("1");            // tam. 7
                _xml.WriteEndElement();

                _xml.WriteStartElement("cMunFG"); //Código do Município de Ocorrência do Fato Gerador
                _xml.WriteString(Global.cMunFG);  // tam. 7
                _xml.WriteEndElement();


                _xml.WriteStartElement("tpImp"); //Formato de Impressão do DANFE
                _xml.WriteString("4");           //1-Retrato/ 2-Paisagem
                _xml.WriteEndElement();

                _xml.WriteStartElement("tpEmis"); //Tipo de Emissão da NF-e (normal, contingencia, ver manual)
                _xml.WriteString(Global.tpEmis);  // tam. 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("cDV");            //Dígito Verificador da Chave de Acesso da NF-e
                _xml.WriteString(Chave.Substring(43, 1)); // tam. 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("tpAmb");         //Tipo de ambiente,1-Produção/ 2-Homologação
                _xml.WriteString(Global.AmbienteCodigo); // Tam 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("finNFe"); //Finalidade de emissão da NFe,1- NF-e normal/ 2-NF-e complementar / 3 – NF-e de ajuste
                _xml.WriteString("1");            // Finalidade da Nfe
                _xml.WriteEndElement();

                _xml.WriteStartElement("indFinal"); //Finalidade de emissão da NFe,1- NF-e normal/ 2-NF-e complementar / 3 – NF-e de ajuste
                _xml.WriteString("1");              // Finalidade da Nfe
                _xml.WriteEndElement();

                _xml.WriteStartElement("indPres"); //Finalidade de emissão da NFe,1- NF-e normal/ 2-NF-e complementar / 3 – NF-e de ajuste
                _xml.WriteString("1");             // Finalidade da Nfe
                _xml.WriteEndElement();

                _xml.WriteStartElement("procEmi"); //Processo de emissão da NF-e
                _xml.WriteString("0");             // Tam 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("verProc"); //Versão do Processo de emissão da NF-e
                _xml.WriteString("ASAsysNFCe");    // tam. 1-20
                _xml.WriteEndElement();

                if (Global.tpEmis == "9")
                {
                    _xml.WriteStartElement("dhCont");                                                    //Processo de emissão da NF-e
                    _xml.WriteString(String.Format("{0:yyyy-MM-ddTHH:mm:ss}", DateTime.Now) + "-03:00"); // Tam 1
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("xJust");                                                 //Versão do Processo de emissão da NF-e
                    _xml.WriteString("Entrada em Contigencia por falta de comunicação com a SEFAZ"); // tam. 1-20
                    _xml.WriteEndElement();
                }



                _xml.WriteEndElement();//ide
                //fim ide
                #endregion

                #region emit
                _xml.WriteStartElement("emit"); //ide

                _xml.WriteStartElement("CNPJ"); // CNPJ Emitente
                _xml.WriteString(Global.CNPJ);  // tam 14
                _xml.WriteEndElement();

                _xml.WriteStartElement("xNome"); //Razão Social ou Nome do emitente
                _xml.WriteString(Global.xNome);  // tam. 2-60
                _xml.WriteEndElement();

                _xml.WriteStartElement("xFant"); //Nome fantasia
                _xml.WriteString(Global.xFant);  // tam. 1-60
                _xml.WriteEndElement();
                #region enderEmit
                _xml.WriteStartElement("enderEmit"); //Tag codigo Uf

                _xml.WriteStartElement("xLgr");      //Logradouro
                _xml.WriteString(Global.xLgr);       //tam. 2-60
                _xml.WriteEndElement();

                _xml.WriteStartElement("nro"); //Número
                _xml.WriteString(Global.Nro);  // 1-60
                _xml.WriteEndElement();
                //ocorrencia 0-1


                _xml.WriteStartElement("xBairro"); //Bairro
                _xml.WriteString(Global.xBairro);  // tam. 2-60
                _xml.WriteEndElement();

                _xml.WriteStartElement("cMun"); //Código do município
                _xml.WriteString(Global.cMun);  // 1
                _xml.WriteEndElement();

                _xml.WriteStartElement("xMun"); //Nome do município
                _xml.WriteString(Global.xMun);  // tam. 2-60
                _xml.WriteEndElement();

                _xml.WriteStartElement("UF"); //Sigla da UF
                _xml.WriteString(Global.UF);  // tam. 2
                _xml.WriteEndElement();

                _xml.WriteStartElement("CEP"); //Código do CEP, Informar os zeros não significativos.
                _xml.WriteString(Global.CEP);  // tam. 8
                _xml.WriteEndElement();

                _xml.WriteStartElement("cPais"); //Código do País
                _xml.WriteString("1058");        // tam. 4 1058 - Brasil
                _xml.WriteEndElement();

                _xml.WriteStartElement("xPais"); //Nome do País
                _xml.WriteString("Brasil");      // tam. 1-60; Brasil ou BRASIL
                _xml.WriteEndElement();

                _xml.WriteStartElement("fone");    //Telefone
                _xml.WriteString(Global.telefone); // tam. 6-14 - Preencher com o Código DDD + número do telefone.
                //Nas operações com exterior é permitido informar o código do país + código da localidade + número do telefone (v.2.0)
                _xml.WriteEndElement();
                _xml.WriteEndElement();//enderEmit
                #endregion

                _xml.WriteStartElement("IE"); //IE
                _xml.WriteString(Global.IE);  // tam. 0-14
                _xml.WriteEndElement();
                //Ocorrencia 0-1
                _xml.WriteStartElement("CRT");//Código de Regime Tributário
                //Este campo será obrigatoriamente preenchido com:
                //1 – Simples Nacional;
                //2 – Simples Nacional – excesso de sublimite de receita bruta;
                //3 – Regime Normal. (v2.0).
                _xml.WriteString(Global.CRT); // Tam. 1
                _xml.WriteEndElement();
                _xml.WriteEndElement();       //emit
                #endregion

                #region dest

                if (lstDest.Count != 0)
                {
                    #region dest
                    _xml.WriteStartElement("dest");////INICIO DEST

                    foreach (var item in lstDest)
                    {
                        if (item.CNPJ.Length == 14)
                        {
                            _xml.WriteStartElement("CNPJ");
                            _xml.WriteString(item.CNPJ.Trim());
                            _xml.WriteEndElement();
                        }
                        if (item.CNPJ.Length == 11)
                        {
                            _xml.WriteStartElement("CPF");
                            _xml.WriteString(item.CNPJ.Trim());
                            _xml.WriteEndElement();
                        }
                        _xml.WriteStartElement("xNome");
                        _xml.WriteString(item.xNome.Trim());
                        _xml.WriteEndElement();

                        #endregion

                        if (item.xLgr.Replace(" ", "").Length > 2)
                        {
                            #region EndDest

                            _xml.WriteStartElement("enderDest");

                            _xml.WriteStartElement("xLgr");
                            _xml.WriteString(item.xLgr.Trim());
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("nro");
                            _xml.WriteString(item.nro.Trim());
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("xBairro");
                            _xml.WriteString(item.xBairro.Trim());
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("cMun");
                            _xml.WriteString(item.cMun.Trim());
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("xMun");
                            _xml.WriteString(item.xMun.Trim());
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("UF");
                            _xml.WriteString(item.UF.Trim());
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("CEP");
                            _xml.WriteString(item.CEP.Trim());
                            _xml.WriteEndElement();


                            _xml.WriteEndElement();



                            #endregion
                        }
                    }


                    _xml.WriteStartElement("indIEDest");
                    _xml.WriteString("9");
                    _xml.WriteEndElement();

                    _xml.WriteEndElement();//FIM DEST


                    #endregion
                }
                #region det
                int incrementoProd = 1;

                foreach (var item in lst)
                {
                    _xml.WriteStartElement("det");                   //Grupo do detalhamento de Produtos e Serviços da NF-e
                    _xml.WriteStartAttribute("nItem");               //Número do item (1-990)
                    _xml.WriteString(incrementoProd.ToString().Trim());
                    _xml.WriteEndAttribute();                        // finalizando o atributo
                    #region prod
                    _xml.WriteStartElement("prod");                  //TAG de grupo do detalhamento de Produtos e Serviços da NF-e

                    _xml.WriteStartElement("cProd");                 //Código do produto ou serviço
                    _xml.WriteString(item.codigo.ToString().Trim()); // tam 1-60
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("cEAN");//GTIN (Global Trade Item Number) do produto, antigo código EAN ou código de barras
                    // _xml.WriteString("2");// tam 0,8,12,13,14
                    _xml.WriteEndElement();

                    if (incrementoProd == 1 && Global.AmbienteCodigo == "2")
                    {
                        _xml.WriteStartElement("xProd");                                                              //Descrição do produto ou serviço
                        _xml.WriteString("NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL".Trim()); // tam 1-120
                        _xml.WriteEndElement();
                    }
                    else
                    {
                        _xml.WriteStartElement("xProd");         //Descrição do produto ou serviço
                        _xml.WriteString(item.descricao.Trim()); // tam 1-120
                        _xml.WriteEndElement();
                    }


                    //omitida tag EX_TIPI

                    _xml.WriteStartElement("NCM");                //Código NCM com 8 dígitos ou 2 dígitos (gênero)
                    _xml.WriteString(item.NCM.ToString().Trim()); // tam 2,8
                    _xml.WriteEndElement();
                    if (item.CEST == string.Empty)
                    {
                    }
                    else
                    {
                        _xml.WriteStartElement("CEST"); //Código NCM com 8 dígitos ou 2 dígitos (gênero)
                        _xml.WriteString("1300101");    // tam 2,8
                        _xml.WriteEndElement();
                    }

                    //omitida tag EX_TIPI
                    _xml.WriteStartElement("CFOP"); //Código Fiscal de Operações e Prestações
                    _xml.WriteString(item.CFOP);    // tam 4
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("uCom");                                           //Unidade Comercial
                    _xml.WriteString(item.unidade.Trim().Replace('"', ' ').Replace(" ", "")); // tam 1-6
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("qCom");                                   //Quantidade Comercial
                    _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.qtd))); //tam 15
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("vUnCom");                                     //Valor Unitário de Comercialização
                    _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.vlrUnit))); //tam 21
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("vProd");                                                                                                 //Valor Total Bruto dos Produtos ou Serviços
                    _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.vlrUnit) * Convert.ToDecimal(item.qtd.ToString().Replace(".", ",")))); // tam 15
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("cEANTrib");//GTIN (Global Trade Item Number) da unidade tributável, antigo código EAN ou código de barras
                    //  _xml.WriteString("");// tam 0,8,12,13,14
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("uTrib");                                          //Unidade Tributável
                    _xml.WriteString(item.unidade.Trim().Replace('"', ' ').Replace(" ", "")); // tam 1-6
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("qTrib");                                  //Quantidade Tributável
                    _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.qtd))); //tam 15
                    _xml.WriteEndElement();

                    _xml.WriteStartElement("vUnTrib");                                    //Valor Unitário de tributação
                    _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.vlrUnit))); // tam 21
                    _xml.WriteEndElement();
                    if (Global._VlrOutros > 0 && incrementoProd == 1)
                    {
                        _xml.WriteStartElement("vOutro");                       //Outras despesas acessórias
                        _xml.WriteString(FormatValueForXML(Global._VlrOutros)); // tam 21
                        _xml.WriteEndElement();
                    }
                    if (item.descontoPorc > 0)
                    {
                        _xml.WriteStartElement("vDesc");                        //Valor Unitário de tributação
                        _xml.WriteString(FormatValueForXML(item.descontoPorc)); // tam 21
                        _xml.WriteEndElement();
                    }
                    else
                    {
                    }
                    //ocorrencia 0-1
                    _xml.WriteStartElement("indTot"); //Indica se valor do Item (vProd) entra no valor total da NF-e (vProd)
                    _xml.WriteString("1");            // Este campo deverá ser preenchido com:
                    //0 – o valor do item (vProd) não compõe o valor total da NF-e(vProd)
                    //1 – o valor do item (vProd)compõe o valor total da NF-e(vProd) (v2.0)
                    _xml.WriteEndElement();

                    _xml.WriteEndElement();//fim prod

                    #endregion

                    #region imposto
                    _xml.WriteStartElement("imposto");//Grupo de Tributos incidentes no Produto ou Serviço


                    _xml.WriteStartElement("vTotTrib");                 //Indica se valor do Item (vProd) entra no valor total da NF-e (vProd)
                    _xml.WriteString(FormatValueForXML(item.vTotTrib)); // Este campo deverá ser preenchido com:

                    _xml.WriteEndElement();

                    #region ICMS
                    _xml.WriteStartElement("ICMS");//Grupo do ICMS da Operação própria e ST
                    if (item.CST == ("101"))
                    {
                        #region ICMS 101
                        _xml.WriteStartElement("ICMSSN101"); //Grupo do ICMS da Operação própria e ST

                        _xml.WriteStartElement("orig");      //Origem da mercadoria
                        _xml.WriteString("0");               // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("CSOSN"); //Origem da mercadoria
                        _xml.WriteString("101");         // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("pCredSN"); //Origem da mercadoria
                        _xml.WriteString("0.00");          // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("vCredICMSSN"); //Origem da mercadoria
                        _xml.WriteString("0.00");              // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteEndElement();

                        #endregion
                    }
                    if (item.CST == ("300"))
                    {
                        #region ICMS 500
                        _xml.WriteStartElement("ICMSSN102"); //Grupo do ICMS da Operação própria e ST

                        _xml.WriteStartElement("orig");      //Origem da mercadoria
                        _xml.WriteString("0");               // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("CSOSN"); //Origem da mercadoria
                        _xml.WriteString("300");         // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteEndElement();

                        #endregion
                    }
                    if (item.CST == ("500"))
                    {
                        #region ICMS 500
                        _xml.WriteStartElement("ICMSSN500"); //Grupo do ICMS da Operação própria e ST

                        _xml.WriteStartElement("orig");      //Origem da mercadoria
                        _xml.WriteString("0");               // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("CSOSN"); //Origem da mercadoria
                        _xml.WriteString("500");         // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("vBCSTRet"); //Origem da mercadoria
                        _xml.WriteString("0.00");           // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("vICMSSTRet"); //Origem da mercadoria
                        _xml.WriteString("0.00");             // tam 1
                        _xml.WriteEndElement();

                        _xml.WriteEndElement();

                        #endregion
                    }
                    if (item.CST != ("500") && item.CST != ("300") && item.CST != ("101"))
                    {
                        #region ICMS_ValComum
                        _xml.WriteStartElement("ICMS" + item.CST);//Grupo do ICMS da Operação própria e ST

                        //para o caso ICMS00,10,20,30,40,51,90,Part,ST,101,102,201,202,500,900
                        _xml.WriteStartElement("orig"); //Origem da mercadoria
                        _xml.WriteString("0");          // tam 1
                        _xml.WriteEndElement();

                        //para o caso ICMS00,10,20,51,70,90,Part,900
                        _xml.WriteStartElement("CST"); //Valor da BC do ICMS
                        _xml.WriteString(item.CST);    // tam 15
                        _xml.WriteEndElement();
                        if (item.CST == "00")
                        {
                            _xml.WriteStartElement("modBC");
                            _xml.WriteString("1");
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("vBC");
                            _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.vlrUnit) * Convert.ToInt32(item.qtd)));
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("pICMS");
                            _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item._pICMS)));
                            _xml.WriteEndElement();



                            _xml.WriteStartElement("vICMS");

                            _xml.WriteString(FormatValueForXML(item._vICMS).Replace(",", "."));
                            _xml.WriteEndElement();

                            if (item._vICMS > 0)
                            {
                                _vlrTotVicms   = _vlrTotVicms + item._vICMS;
                                _vlrTotBCVicms = _vlrTotBCVicms + Convert.ToDecimal(item.vlrUnit) * Convert.ToInt32(item.qtd);
                            }
                        }

                        _xml.WriteEndElement();

                        #endregion
                    }
                    _xml.WriteEndElement();
                    #endregion


                    if (Global.lstCST_PIS_COFINS.Contains(item.CSTPIS))
                    {
                        #region region PIS 04,05,06,07,08,09

                        _xml.WriteStartElement("PIS");   //Grupo do PIS

                        _xml.WriteStartElement("PISNT"); //Grupo de PIS tributado pela alíquota


                        _xml.WriteStartElement("CST"); //Código de Situação Tributária do PIS
                        _xml.WriteString(item.CSTPIS); // tam 2
                        _xml.WriteEndElement();

                        _xml.WriteEndElement();
                        _xml.WriteEndElement();

                        #endregion
                    }
                    if (!Global.lstCST_PIS_COFINS.Contains(item.CSTPIS))
                    {
                        #region PIS
                        _xml.WriteStartElement("PIS");//Grupo do PIS
                        #region PISComum

                        _xml.WriteStartElement("PISOutr");//Grupo de PIS tributado pela alíquota


                        _xml.WriteStartElement("CST"); //Código de Situação Tributária do PIS
                        _xml.WriteString(item.CSTPIS); // tam 2
                        _xml.WriteEndElement();

                        #endregion

                        #region PISAliq_PISOutr
                        _xml.WriteStartElement("vBC");                              //Valor da Base de Cálculo do PIS
                        _xml.WriteString(item.vBCPIS.ToString().Replace(",", ".")); // tam 15
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("pPIS");                                                      //Alíquota do PIS (em percentual)
                        _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.pPIS.Replace(",", ".")))); // tam 5
                        _xml.WriteEndElement();

                        #endregion



                        //usado em PISAliq,PISQtde,PISOutr
                        _xml.WriteStartElement("vPIS");                           //Valor do PIS
                        _xml.WriteString(item.vPIS.ToString().Replace(",", ".")); // tam 15
                        _xml.WriteEndElement();
                        _xml.WriteEndElement();                                   //end tipo do pis..
                        _xml.WriteEndElement();                                   //end PIS...;
                        #endregion
                    }
                    if (Global.lstCST_PIS_COFINS.Contains(item.CSTCOFINS))
                    {
                        #region region COFINS 04,05,06,07,08,09

                        _xml.WriteStartElement("COFINS");   //Grupo do PIS

                        _xml.WriteStartElement("COFINSNT"); //Grupo de PIS tributado pela alíquota


                        _xml.WriteStartElement("CST"); //Código de Situação Tributária do PIS
                        _xml.WriteString(item.CSTPIS); // tam 2
                        _xml.WriteEndElement();

                        _xml.WriteEndElement();
                        _xml.WriteEndElement();

                        #endregion
                    }
                    if (!Global.lstCST_PIS_COFINS.Contains(item.CSTPIS))
                    {
                        #region COFINS


                        _xml.WriteStartElement("COFINS");     //Grupo do COFINS

                        _xml.WriteStartElement("COFINSOutr"); //Grupo de COFINS tributado pela alíquota

                        _xml.WriteStartElement("CST");        //Código de Situação Tributária do COFINS
                        _xml.WriteString(item.CSTCOFINS);     // tam 2
                        _xml.WriteEndElement();



                        _xml.WriteStartElement("vBC");                                 //Valor da Base de Cálculo do COFINS
                        _xml.WriteString(item.vBCCOFINS.ToString().Replace(",", ".")); // tam 15
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("pCOFINS");                                                      //Alíquota da COFINS (em percentual)
                        _xml.WriteString(FormatValueForXML(Convert.ToDecimal(item.pCOFINS.Replace(",", ".")))); // tam 5
                        _xml.WriteEndElement();



                        //usado em COFINSAliq,COFINSQtde,COFINSOutr
                        _xml.WriteStartElement("vCOFINS");                           //Valor do COFINS
                        _xml.WriteString(item.vCOFINS.ToString().Replace(",", ".")); // tam 15
                        _xml.WriteEndElement();

                        _xml.WriteEndElement(); //end COFINS...;

                        _xml.WriteEndElement(); //end COFINS;
                        #endregion
                    }

                    //ou este


                    _xml.WriteEndElement();//end element Imposto
                    #endregion
                    #endregion

                    _xml.WriteEndElement();
                    //omitida tag DI e filhos
                    //omitida tag veicProd e filhos
                    //omitida tag med e filhos
                    //omitida tag arma
                    //omitida tag comb
                    incrementoProd++;

                    //fim det
                    #endregion
                }

                #region Total
                _xml.WriteStartElement("total");//Grupo de Valores Totais da NF-e

                #region ICMSTot

                _xml.WriteStartElement("ICMSTot");                                     //Grupo de Valores Totais referentes ao ICMS

                _xml.WriteStartElement("vBC");                                         //Valor da BC do ICMS
                _xml.WriteString(FormatValueForXML(_vlrTotBCVicms).Replace(",", ".")); // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vICMS");                                     //Valor do ICMS
                _xml.WriteString(FormatValueForXML(_vlrTotVicms).Replace(",", ".")); // tam 5
                _xml.WriteEndElement();

                _xml.WriteStartElement("vICMSDeson"); //Valor da BC do ICMS ST
                _xml.WriteString("0.00");             // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vBCST"); //Valor da BC do ICMS ST
                _xml.WriteString("0.00");        // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vST"); //Valor da BC do ICMS ST
                _xml.WriteString("0.00");      // tam 15
                _xml.WriteEndElement();
                // decimal validar = Convert.ToDecimal(Global._lstVendaItem.Sum(s => s.valorTotal));
                _xml.WriteStartElement("vProd");//Valor Total Bruto dos Produtos ou Serviços
                decimal valor = 0;

                foreach (var item in lst)
                {
                    valor      = Convert.ToDecimal(item.vlrUnit) * Convert.ToDecimal(item.qtd.ToString().Replace(".", ","));
                    valorTotal = valorTotal + valor;
                }


                _xml.WriteString(FormatValueForXML(valorTotal));// tam 15
                _xml.WriteEndElement();
                valorTotal = valorTotal + Global._VlrOutros;
                _xml.WriteStartElement("vFrete"); //Valor Total do Frete
                _xml.WriteString("0.00");         // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vSeg"); //Valor Total do Seguro
                _xml.WriteString("0.00");       // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vDesc");                          //Valor do Desconto
                _xml.WriteString(FormatValueForXML(Global._VlrDescNFce)); // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vII"); //Valor Total do II
                _xml.WriteString("0.00");      // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vIPI"); //Valor do IPI
                _xml.WriteString("0.00");       // tam 3
                _xml.WriteEndElement();

                _xml.WriteStartElement("vPIS"); //Valor do PIS
                _xml.WriteString("0.00");       // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vCOFINS"); //Valor do COFINS
                _xml.WriteString("0.00");          // tam 15
                _xml.WriteEndElement();

                _xml.WriteStartElement("vOutro");//Outras despesas acessórias
                if (Global._VlrOutros > 0)
                {
                    _xml.WriteString(FormatValueForXML(Global._VlrOutros));// tam 15
                    _xml.WriteEndElement();
                }
                if (Global._VlrOutros == 0)
                {
                    _xml.WriteString("0.00");// tam 15
                    _xml.WriteEndElement();
                }

                _xml.WriteStartElement("vNF");                                           //Valor Total da NF-e

                _xml.WriteString(FormatValueForXML((valorTotal - Global._VlrDescNFce))); // tam 15
                _xml.WriteEndElement();


                _xml.WriteStartElement("vTotTrib");                            //Indica se valor do Item (vProd) entra no valor total da NF-e (vProd)
                _xml.WriteString(FormatValueForXML(lst.Sum(e => e.vTotTrib))); // Este campo deverá ser preenchido com:

                _xml.WriteEndElement();


                _xml.WriteEndElement();

                #endregion
                //ocorrencia 0-1

                //ocorrencia 0-1


                _xml.WriteEndElement();
                #endregion

                #region transp

                _xml.WriteStartElement("transp");   //Grupo de Informações do Transporte da NF-e

                _xml.WriteStartElement("modFrete"); //Modalidade do frete
                _xml.WriteString("9");              // tam 15
                _xml.WriteEndElement();



                _xml.WriteEndElement();
                #endregion

                #region pag

                decimal resta = valorTotal - Global._VlrDescNFce;
                Global._VlrTrocolNFce = Math.Abs((lstPag.Sum(s => s.VlrPag) - resta));
                int count = 1;
                foreach (var item in lstPag)
                {
                    Thread.Sleep(150);

                    if (lstPag.Count() > 1)
                    {
                        resta = resta - item.VlrPag;
                    }
                    _xml.WriteStartElement("pag");  //Grupo de Informações do Transporte da NF-e
                    _xml.WriteStartElement("tPag"); //Modalidade do frete
                    if (item.tpPag.ToString().Length == 1)
                    {
                        _xml.WriteString("0" + item.tpPag.ToString());// tam 15
                        _xml.WriteEndElement();
                    }
                    else
                    {
                        _xml.WriteString(item.tpPag.ToString());// tam 15
                        _xml.WriteEndElement();
                    }
                    _xml.WriteStartElement("vPag");//Modalidade do frete

                    if (lstPag.Count() > 1)
                    {
                        #region MAIS DE UMA FORMA PAG
                        decimal diferencial = item.VlrPag - valorTotal;

                        if (item.VlrPag < valorTotal && lstPag.Count() > 1 && resta == Math.Abs(diferencial))
                        {
                            _xml.WriteString(FormatValueForXML(item.VlrPag));// tam 15
                            _xml.WriteEndElement();
                        }
                        if (item.VlrPag > valorTotal && lstPag.Count() > 1)
                        {
                            string pAGtSTa = FormatValueForXML(Math.Abs(item.VlrPag - Math.Abs(resta)));
                            _xml.WriteString(pAGtSTa);// tam 15
                            _xml.WriteEndElement();
                        }
                        if (item.VlrPag < valorTotal && lstPag.Count() > 1 && resta != Math.Abs(diferencial) && count < lstPag.Count())
                        {
                            string pAGtST = FormatValueForXML(item.VlrPag);

                            _xml.WriteString(pAGtST);// tam 15
                            _xml.WriteEndElement();
                        }
                        if (item.VlrPag < valorTotal && lstPag.Count() > 1 && resta != Math.Abs(diferencial) && count == lstPag.Count())
                        {
                            string pAGtST = FormatValueForXML(Math.Abs(item.VlrPag - Math.Abs(resta)));

                            _xml.WriteString(pAGtST);// tam 15
                            _xml.WriteEndElement();
                        }

                        _xml.WriteEndElement();

                        #endregion
                    }
                    if (lstPag.Count() == 1)
                    {
                        #region MAIS DE UMA FORMA PAG
                        if (item.VlrPag > valorTotal && lstPag.Count() == 1)
                        {
                            _xml.WriteString(FormatValueForXML(valorTotal - Global._VlrDescNFce));// tam 15
                            _xml.WriteEndElement();
                        }
                        else
                        {
                            _xml.WriteString(FormatValueForXML(valorTotal - Global._VlrDescNFce));// tam 15
                            _xml.WriteEndElement();
                        }

                        _xml.WriteEndElement();

                        #endregion
                    }

                    count++;
                }

                Global._VlrTotalNFce = lstPag.Sum(s => s.VlrPag);
                if (Global._VlrTotalNFce < valorTotal)
                {
                    Global._VlrTotalNFce = valorTotal - Global._VlrDescNFce;
                }

                #endregion

                #region
                _xml.WriteStartElement("infAdic"); //Grupo de Informações do Transporte da NF-e
                _xml.WriteStartElement("infCpl");  //Grupo de Informações do Transporte da NF-e
                string troco = string.Empty;
                if (lstPag.Sum(s => s.VlrPag) > lstPag.Sum(s => s.VlrPag))
                {
                    troco = "Troco: " + FormatValueForXML(lstPag.Sum(s => s.VlrPag) + lstPag.Sum(s => s.VlrPag));
                }

                _xml.WriteString(troco + rodape);


                _xml.WriteEndElement();
                _xml.WriteEndElement();
                #endregion



                _xml.WriteEndElement();//InfNFE
                #endregion

                //end envnfe
                _xml.WriteEndElement();//envNFE

                _xml.Close();



                if (Global._VlrTrocolNFce < 0)
                {
                    Global._VlrTrocolNFce = 0;
                }
                _vlrTotVicms   = 0;
                _vlrTotBCVicms = 0;
                valorTotal     = 0;
                resta          = 0;
                count          = 0;

                if (Global.tpEmis != "9")
                {
                    File.Move(caminhoNFCe + "\\" + Chave + "-nfe.xml", Global.PastaXmlEnvio + "\\" + Chave + "-nfe.xml");
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
 public void WriteEndAttribute()
 {
     _writer.WriteEndAttribute();
 }
        /// <summary>
        /// LoadXML
        /// Exporting Data to File.
        /// </summary>
        /// /// <param name="filePath">DATA path for Export</param>
        public void ExportToFile(List <Address> addresses, string filePath, string fileExtension)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new DirectoryNotFoundException($"File Directory not found: {filePath}");
            }

            var sb           = new StringBuilder();
            var stringWriter = new StringWriter(sb);

            switch (fileExtension)
            {
            case ".xml":
            {
                XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("AddressInfo");

                var cityNames = addresses.SelectMany(x => x.CityName, (p, t) => new { p.CityName, p.CityCode }).Distinct();

                foreach (var item in cityNames)
                {
                    xmlWriter.WriteStartElement("City");

                    xmlWriter.WriteStartAttribute("name");
                    xmlWriter.WriteString(item.CityName.ToString());
                    xmlWriter.WriteStartAttribute("code");
                    xmlWriter.WriteString(item.CityCode.ToString());
                    xmlWriter.WriteEndAttribute();

                    var districtNames = addresses.Where(x => x.CityCode == item.CityCode).Select(x => x.DistrictName).Distinct();
                    foreach (var districtName in districtNames)
                    {
                        xmlWriter.WriteStartElement("District");

                        xmlWriter.WriteStartAttribute("name");
                        xmlWriter.WriteString(districtName);
                        xmlWriter.WriteEndAttribute();

                        var zipCodes = addresses.Where(x => x.CityCode == item.CityCode && x.DistrictName == districtName).Select(x => x.ZipCode).Distinct();
                        foreach (var zipCode in zipCodes)
                        {
                            xmlWriter.WriteStartElement("Zip");
                            xmlWriter.WriteStartAttribute("code");
                            xmlWriter.WriteString(zipCode);
                            xmlWriter.WriteEndAttribute();
                            // END of Zip element
                            xmlWriter.WriteEndElement();
                        }

                        // END of District element
                        xmlWriter.WriteEndElement();
                    }
                    // END of City element
                    xmlWriter.WriteEndElement();
                }

                // END of AddressInfo element
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndDocument();
                xmlWriter.Close();

                sb.Remove(0, 39);
                break;
            }

            case ".csv":
            {
                sb.Append("\ufeff");
                sb.AppendLine("CityName,CityCode,DistrictName,ZipCode");

                foreach (var item in addresses)
                {
                    var line = string.Format("{0},{1},{2},{3}", item.CityName, item.CityCode, item.DistrictName, item.ZipCode);
                    sb.AppendLine(line);
                }

                break;
            }
            }

            File.WriteAllText(filePath, sb.ToString());
        }
Exemple #30
0
        static void Main(string[] args)
        {
            XmlTextWriter xmlWriter = new XmlTextWriter("TelephoneBook.xml", null);

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("MyContacts");
            xmlWriter.WriteStartElement("Contact");
            xmlWriter.WriteStartAttribute("TelephoneNumber");
            xmlWriter.WriteString("911");
            xmlWriter.WriteEndAttribute();
            xmlWriter.WriteString("Vasya");
            xmlWriter.WriteEndElement();
            xmlWriter.WriteStartElement("Contact");
            xmlWriter.WriteStartAttribute("TelephoneNumber");
            xmlWriter.WriteString("112");
            xmlWriter.WriteEndAttribute();
            xmlWriter.WriteString("Lena");
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();
            xmlWriter.Close();
            Console.WriteLine("Added information");
            //  Task2
            Console.WriteLine("Information from TelephoneBook.xml file:");
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("TelephoneBook.xml");
            XmlElement xRoot = xmlDoc.DocumentElement;

            foreach (XmlNode t in xRoot)
            {
                Console.WriteLine("Name:");
                foreach (XmlNode td in t.ChildNodes)
                {
                    Console.WriteLine(td.InnerText);
                }
                Console.WriteLine("Telephone number:");
                if (t.Attributes.Count > 0)
                {
                    XmlNode attr = t.Attributes.GetNamedItem("TelephoneNumber");
                    if (attr != null)
                    {
                        Console.WriteLine(attr.Value);
                    }
                }

                Console.WriteLine();
            }
            //  Task3
            XmlDocument xmlDoc2 = new XmlDocument();

            xmlDoc.Load("TelephoneBook.xml");
            XmlElement xRoot2 = xmlDoc.DocumentElement;

            Console.WriteLine("Telephones:");
            foreach (XmlNode t in xRoot2)
            {
                if (t.Attributes.Count > 0)
                {
                    XmlNode attr = t.Attributes.GetNamedItem("TelephoneNumber");
                    if (attr != null)
                    {
                        Console.WriteLine(attr.Value);
                    }
                }
            }
            Console.ReadLine();
        }
Exemple #31
0
 public static void WriteAttribute(XmlTextWriter writer, string name, decimal value)
 {
     writer.WriteStartAttribute(name);
     writer.WriteValue(value.ToString(CultureInfo.InvariantCulture));
     writer.WriteEndAttribute();
 }
Exemple #32
0
        //Serializes the object using the passed XmlWriter.
        private void SerializeObject(XmlTextWriter writer, FormatterConverter converter, string elementName, string key, object objectToSerialize, Type objectType)
        {
            //Write the opening tag
            writer.WriteStartElement(elementName);

            //Include type information.
            WriteAttributes(writer, objectType, key);

            //Only serialize object if not null
            if (objectToSerialize != null)
            {
                //Write an object reference if the object has already been serialized
                if (!Shallow && _objectIds.ContainsKey(objectToSerialize))
                {
                    writer.WriteStartAttribute("ref");
                    writer.WriteString(_objectIds[objectToSerialize].ToString());
                    writer.WriteEndAttribute();

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

                    return;
                }

                int id = _objectIds.Count + 1;
                _objectIds.Add(objectToSerialize, id);

                //Write the id attribute
                writer.WriteStartAttribute("id");
                writer.WriteString(id.ToString());
                writer.WriteEndAttribute();

                //for each serializable item in this object
                foreach (SerializationEntry entry in GetMemberInfo(objectToSerialize, objectType, converter))
                {
                    //Simple type, directly write the value.
                    if (entry.ObjectType.IsPrimitive || entry.ObjectType == typeof(string) || entry.ObjectType.IsEnum || entry.ObjectType == typeof(DateTime))
                    {
                        WriteValueElement(writer, entry);
                    }
                    //Write resource
                    else if (IsResource(entry.ObjectType))
                    {
                        ResourceEntry resource = new ResourceEntry(entry.Name, entry.ObjectType, entry.Value);

                        //Get a unique uri for the resource
                        string uri = String.Format("/Resource/{0}/{1}.{2}", resource.Name, id, resource.GetResourceType());

                        //Write the uri reference to the document
                        WriteResourceElement(entry.Name, writer, entry.ObjectType, uri);

                        //Add to the resources dictionary
                        if (!_resources.ContainsKey(uri))
                        {
                            _resources.Add(uri, resource);
                        }
                    }
                    //Serialize the object (recursive call), if not shallow
                    else if (!Shallow)
                    {
                        SerializeObject(writer, converter, entry.Name, null, entry.Value, entry.ObjectType);
                    }
                }

                //Process list and dictionary members
                bool isList       = typeof(IList).IsAssignableFrom(objectType);
                bool isDictionary = typeof(IDictionary).IsAssignableFrom(objectType);

                //An IList collection
                if (isList)
                {
                    //write the opening tag.
                    writer.WriteStartElement("Collection");

                    //Indicate that this is a collection
                    writer.WriteStartAttribute("type");
                    writer.WriteString("IList");
                    writer.WriteEndAttribute();

                    IList list = objectToSerialize as IList;
                    if (list != null)
                    {
                        IEnumerator enumerator = list.GetEnumerator();

                        while (enumerator.MoveNext())
                        {
                            Type enumeratedType = enumerator.Current.GetType();

                            //serialize the object (recursive call)
                            SerializeObject(writer, converter, enumeratedType.Name, null, enumerator.Current, enumeratedType);
                        }
                    }

                    //Write closing tag
                    writer.WriteEndElement();
                }

                //An IDictionary collection
                else if (isDictionary)
                {
                    //write the opening tag.
                    writer.WriteStartElement("Collection");

                    //Indicate that this is a collection
                    writer.WriteStartAttribute("type");
                    writer.WriteString("IDictionary");
                    writer.WriteEndAttribute();

                    IDictionary dictionary = objectToSerialize as IDictionary;
                    if (dictionary != null)
                    {
                        IDictionaryEnumerator enumerator = dictionary.GetEnumerator();

                        while (enumerator.MoveNext())
                        {
                            Type enumeratedType = enumerator.Value.GetType();

                            //serialize the object (recursive call)
                            SerializeObject(writer, converter, enumeratedType.Name, enumerator.Key.ToString(), enumerator.Value, enumeratedType);
                        }
                    }

                    //Close the collection element
                    writer.WriteEndElement();
                }
            }

            //Write the closing tag and flush the contents of the writer to the stream
            writer.WriteEndElement();
            writer.Flush();
        }
Exemple #33
0
    } //WriteXSDSchema()

    /// <summary>
    /// This method writes out an XML schema attribute.
    /// </summary>
    /// <param name="attribute">XML schema attribute to be output.</param>
    /// <param name="myXmlTextWriter">XmlTextWriter to write output to.</param>
    public static void WriteXmlSchemaAttribute(XmlSchemaAttribute attribute, XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartElement("attribute", XmlSchema.Namespace);
      if (attribute.Name != null)
      {
        myXmlTextWriter.WriteAttributeString("name", attribute.Name);
      } //if

      if (!attribute.RefName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("ref", null);
        myXmlTextWriter.WriteQualifiedName(attribute.RefName.Name, attribute.RefName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (!attribute.SchemaTypeName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("type", null);
        myXmlTextWriter.WriteQualifiedName(attribute.SchemaTypeName.Name, attribute.SchemaTypeName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (attribute.SchemaType != null)
      {
        WriteXmlSchemaSimpleType(attribute.SchemaType, myXmlTextWriter);
      } //if

      myXmlTextWriter.WriteEndElement();
    } //WriteXmlSchemaAttribute()
Exemple #34
0
 public static void WriteAttribute(XmlTextWriter writer, string name, string value)
 {
     writer.WriteStartAttribute(name);
     writer.WriteValue(value);
     writer.WriteEndAttribute();
 }
Exemple #35
0
        public void Write()
        {
            XmlTextWriter writer = new XmlTextWriter(Constants.GAME_BASE_PATH, Encoding.UTF8);

            try
            {
                writer.WriteStartDocument();
                writer.Formatting  = Formatting.Indented;
                writer.IndentChar  = '\t';
                writer.Indentation = 1;
                writer.WriteStartElement("game");

                writer.WriteStartAttribute("testLastID", null);
                writer.WriteString(Test.LAST_ID.ToString());
                writer.WriteEndAttribute();

                foreach (Category cat in data.Categories)
                {
                    writer.WriteStartElement("category");

                    writer.WriteStartAttribute("text", null);
                    writer.WriteString(cat.Text);
                    writer.WriteEndAttribute();
                    foreach (Test test in cat.Tests)
                    {
                        writer.WriteStartElement("test");

                        writer.WriteStartAttribute("id", null);
                        writer.WriteString(test.ID.ToString());
                        writer.WriteEndAttribute();

                        writer.WriteStartAttribute("text", null);
                        writer.WriteString(test.Text);
                        writer.WriteEndAttribute();

                        foreach (Question question in test.Questions)
                        {
                            writer.WriteStartElement("question");

                            writer.WriteStartAttribute("text", null);
                            writer.WriteString(question.Text);
                            writer.WriteEndAttribute();
                            foreach (Answer answer in question.Answers)
                            {
                                writer.WriteStartElement("answer");

                                writer.WriteStartAttribute("text", null);
                                writer.WriteString(answer.Text);
                                writer.WriteEndAttribute();

                                writer.WriteStartAttribute("isCorrect", null);
                                writer.WriteString(answer.IsCorrect.ToString());
                                writer.WriteEndAttribute();

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

                    writer.WriteEndElement();
                }
            }
            catch (System.Xml.XmlException e)
            {
                Console.WriteLine($"Exception(Game.Write): {e.Message}");
            }
            writer.Close();
        }
        private void InsertEmptyRowsWithConditional(List <int> intListRow, String ConditionalCell, XmlTextWriter xtw, int RowNumber, int PrevRowNumber, Boolean CheckIfBigConditional, Boolean InsertRowWithConditionalAfterLastRow)
        {
            if (CheckIfBigConditional)
            {
                for (int count = PrevRowNumber + 1; count < RowNumber; count++)
                {
                    xtw.WriteStartElement(null, "row", SPREADSHEET_ML_NS);

                    xtw.WriteStartAttribute(null, "r", null);
                    xtw.WriteString(count.ToString());
                    xtw.WriteEndAttribute();

                    if (InsertRowWithConditionalAfterLastRow)
                    {
                        xtw.WriteStartAttribute(null, "oox:ConditionalRepeat", null);
                        xtw.WriteString("continue");
                        xtw.WriteEndAttribute();
                    }

                    InsertCellInRow(count, ConditionalCell, xtw, 0, 256);

                    xtw.WriteEndElement();
                    if (InsertRowWithConditionalAfterLastRow)
                    {
                        break;
                    }
                }
            }
            else
            {
                for (int count = 0; count < intListRow.Count; count++)
                {
                    if (PrevRowNumber < intListRow[count] && intListRow[count] < RowNumber)
                    {
                        xtw.WriteStartElement(null, "row", SPREADSHEET_ML_NS);
                        xtw.WriteStartAttribute(null, "r", null);
                        xtw.WriteString(intListRow[count].ToString());
                        xtw.WriteEndAttribute();

                        if (InsertRowWithConditionalAfterLastRow && (intListRow.Count + PrevRowNumber - 65536) >= 0)
                        {
                            xtw.WriteStartAttribute(null, "oox:ConditionalRepeat", null);
                            xtw.WriteString("continue");
                            xtw.WriteEndAttribute();
                        }


                        InsertCellInRow(intListRow[count], ConditionalCell, xtw, 0, 256);

                        xtw.WriteEndElement();
                        if (InsertRowWithConditionalAfterLastRow && (intListRow.Count + PrevRowNumber - 65536) >= 0)
                        {
                            break;
                        }
                    }
                    else if (RowNumber < intListRow[count])
                    {
                        break;
                    }
                }
            }
        }
Exemple #37
0
        public void Write()
        {
            XmlTextWriter writer = new XmlTextWriter(Constants.USERS_BASE_PATH, Encoding.UTF8);

            try
            {
                writer.WriteStartDocument();
                writer.Formatting  = Formatting.Indented;
                writer.IndentChar  = '\t';
                writer.Indentation = 1;
                writer.WriteStartElement("users");
                foreach (IUser user in Users)
                {
                    writer.WriteStartElement("user");

                    writer.WriteStartAttribute("id", null);
                    writer.WriteString(user.ID.ToString());
                    writer.WriteEndAttribute();

                    writer.WriteStartAttribute("login", null);
                    writer.WriteString(user.Login);
                    writer.WriteEndAttribute();

                    writer.WriteStartAttribute("password", null);
                    writer.WriteString(user.Password);
                    writer.WriteEndAttribute();

                    writer.WriteStartAttribute("type", null);
                    writer.WriteString(((int)user.GetUserType()).ToString());
                    writer.WriteEndAttribute();

                    writer.WriteStartElement("birthdate");

                    writer.WriteStartAttribute("day", null);
                    writer.WriteString(user.BirthDate.Day.ToString());
                    writer.WriteEndAttribute();
                    writer.WriteStartAttribute("month", null);
                    writer.WriteString(user.BirthDate.Month.ToString());
                    writer.WriteEndAttribute();
                    writer.WriteStartAttribute("year", null);
                    writer.WriteString(user.BirthDate.Year.ToString());
                    writer.WriteEndAttribute();

                    writer.WriteEndElement();
                    foreach (Result result in user.Results)
                    {
                        writer.WriteStartElement("result");

                        writer.WriteStartAttribute("testID", null);
                        writer.WriteString(result.TestID.ToString());
                        writer.WriteEndAttribute();

                        writer.WriteStartAttribute("grade", null);
                        writer.WriteString(result.Grade.ToString());
                        writer.WriteEndAttribute();

                        writer.WriteStartAttribute("date", null);
                        writer.WriteString(result.Date.ToString());
                        writer.WriteEndAttribute();

                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
            }
            catch (System.Xml.XmlException e)
            {
                Console.WriteLine($"Exception(Users.Write): {e.Message}");
            }
            writer.Close();
        }
Exemple #38
0
 private void xmlwriteatrr(XmlTextWriter xml, string Name, string Value)
 {
     xml.WriteStartAttribute(Name); //Attribute 'Name'
     xml.WriteString(Value);        //Attribute 'Value'
     xml.WriteEndAttribute();
 }
Exemple #39
0
	public static void WriteNode(XmlElement node, string method, XmlTextWriter output, TextWriter raw) {
		if (node.Name == "string") {
			output.WriteString(node.InnerText);
			return;
		}
		
		if (node.Name == "Attribute")
			output.WriteStartAttribute(node.GetAttribute("Name"), "");
		else if (node.Name == "Text") {
		}
		else if (node.Name != "Element")
			output.WriteStartElement(node.Name);
		else
			output.WriteStartElement(node.GetAttribute("Name"));
		
		foreach (XmlElement child in node.SelectNodes("*")) {
			string status = child.GetAttribute("Status");
			if (status == "") {
				WriteNode(child, method, output, raw);
			} else if (status == "Same") {
				WriteNodeRaw(child, method, output);
			} else if (status == "Added" || status == "Removed") {
				output.Flush();
				if (method == "text") {
					if (status == "Added") raw.Write("\n+"); else raw.Write("\n-");
				} else if (method == "groff") {
					if (status == "Added") raw.Write("\\m[blue]"); else raw.Write("\\m[red]");
				}
				raw.Flush();
				
				WriteNodeRaw((XmlElement)child.FirstChild, method, output);

				output.Flush();
				if (method == "text") {
					raw.Write("\n");
				} else if (method == "groff") {
					if (status == "Added") raw.Write("\\m[]"); else raw.Write("\\m[]");
				}
				raw.Flush();
			} else if (status == "Changed") {
				output.Flush();
				if (method == "text") {
					raw.Write("\n-");
				} else if (method == "groff") {
					raw.Write("\\m[green]");
				}
				raw.Flush();
				
				WriteNodeRaw((XmlElement)child.FirstChild, method, output);

				output.Flush();
				if (method == "text") {
					raw.Write("\n+");
				} else if (method == "groff") {
					raw.Write("\\m[]\\m[magenta]");
				}
				raw.Flush();
				
				WriteNodeRaw((XmlElement)child.FirstChild.NextSibling, method, output);

				output.Flush();
				if (method == "text") {
					raw.Write("\n");
				} else if (method == "groff") {
					raw.Write("\\m[]");
				}
				raw.Flush();
			} else {
				throw new InvalidOperationException("Bad status: " + status);
			}
		}

		if (node.FirstChild is XmlText)
			output.WriteString(node.FirstChild.Value);		
		
		if (node.Name == "Attribute")
			output.WriteEndAttribute();
		else if (node.Name == "Text")
		{}
		else
			output.WriteEndElement();
	}