Esempio n. 1
0
        public static bool Save()
        {
            bool saved = false;

            try
            {
                if (fpss.Count > 10)
                {
                    CalculateAverageFPS();
                }
                AddInfo("Ukladam...");
                Console.WriteLine("Ukladani logu do " + path);
                string name = "log" + startTime.ToString() + ".html";
                name = name.Replace(":", "-");
                lock (doc)
                {
                    doc.Save(path + "log.html");
                    doc.Save(path + name);
                    doc.Save("log.html");
                    saved = true;
                }
                lock (dbgDoc)
                {
                    dbgDoc.Save("debug_log.html");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Chyba ukladani logu!" + ex.ToString());
            }
            return(saved);
        }
Esempio n. 2
0
        public void DataSet_ColumnNameWithSpaces()
        {
            DataSet ds = new DataSet("New Data Set");

            DataTable table1 = ds.Tables.Add("New Table 1");
            DataTable table2 = ds.Tables.Add("New Table 2");

            table1.Columns.Add("col 1", typeof(int));
            table1.Columns.Add("col 2", typeof(int));

            table1.PrimaryKey = new DataColumn[] { ds.Tables [0].Columns [0] };

            // No exception shud be thrown
            XmlDataDocument doc = new XmlDataDocument(ds);

            // Should not fail to save because of "no rows"
            doc.Save(new StringWriter());

            table1.Rows.Add(new object[] { 0 });
            table1.Rows.Add(new object[] { 1 });
            table1.Rows.Add(new object[] { 2 });

            // No exception shud be thrown
            StringWriter swriter = new StringWriter();

            doc.Save(swriter);

            StringReader    sreader = new StringReader(swriter.ToString());
            DataSet         ds1     = ds.Clone();
            XmlDataDocument doc1    = new XmlDataDocument(ds1);

            Assert.AreEqual(0, ds1.Tables [0].Rows.Count, "#2");
            doc1.Load(sreader);
            Assert.AreEqual(3, ds1.Tables [0].Rows.Count, "#3");
        }
Esempio n. 3
0
        // Methods
        public void ExportTOKhai(string template, string fileName)
        {
            XmlDataDocument document = new XmlDataDocument();

            document.Load(template);
            document.Save(fileName);
        }
Esempio n. 4
0
        private void DelBtn_MouseClick(object sender, MouseEventArgs e)
        {
            bool            found = false;
            XmlDataDocument doc   = new XmlDataDocument();

            doc.Load("Tables.xml");
            XmlNodeList list    = doc.GetElementsByTagName("column");
            string      colName = dataGridView1.Columns[columnIndex].Name;

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].FirstChild.InnerText == colName)
                {
                    XmlNodeList pk = list[i].ChildNodes;

                    if (pk[2].InnerText == "false")
                    {
                        XmlNode removeNode = list[i];
                        list[i].ParentNode.RemoveChild(removeNode);
                        found = true;
                    }
                    else
                    {
                        MessageBox.Show("You can't delete column contains pk");
                    }
                }
            }
            if (found)
            {
                dataGridView1.Columns.RemoveAt(columnIndex);
            }
            doc.Save("Tables.xml");
        }
Esempio n. 5
0
        public static bool AddOnlineUser(string QQNumber, string IpEndPoint)
        {
            string XmlUrl = "onlineinf\\onLine.xml";

            if (!File.Exists(XmlUrl))
            {
                File.Create(XmlUrl).Close();
                StringBuilder add = new StringBuilder();
                StreamWriter  str = new StreamWriter(XmlUrl);
                add.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                add.Append("<root></root>");
                str.Write(add.ToString());
                str.Close();
            }
            XmlDataDocument XmlData = new XmlDataDocument();

            XmlData.Load(XmlUrl);
            XmlNode root = XmlData.SelectSingleNode("root");

            if (!IsThisUserOnline(XmlData, QQNumber, IpEndPoint))
            {
                XmlElement online     = XmlData.CreateElement("online");
                XmlElement QQnumber   = XmlData.CreateElement("QQnumber");
                XmlElement Ipendpoint = XmlData.CreateElement("IpEndPoint");
                QQnumber.InnerText   = QQNumber;
                Ipendpoint.InnerText = IpEndPoint;
                online.AppendChild(QQnumber);
                online.AppendChild(Ipendpoint);
                root.AppendChild(online);
            }
            XmlData.Save(XmlUrl);
            return(true);
        }
Esempio n. 6
0
        private void addFriendsToXML(string path, string uid)
        {
            #region
            TUserBusiness   userbusiness = new TUserBusiness();
            DataSet         friends      = userbusiness.GetFriendsByGroup(uid);
            XmlDataDocument temp         = new XmlDataDocument();
            temp.Load(path);

            XmlNodeList AllGroup = temp.SelectSingleNode("root").ChildNodes;
            foreach (XmlNode node in AllGroup)
            {
                string filter = string.Format("{0}='{1}'",
                                              GroupData.groupName, node.Attributes["groupName"].Value);
                DataRow[] drarr = friends.Tables[0].Select(filter);
                foreach (DataRow dr in drarr)
                {
                    XmlElement friend       = temp.CreateElement("friend");
                    XmlElement FriendNumber = temp.CreateElement("FriendNumber");
                    XmlElement FriendName   = temp.CreateElement("FriendName");
                    XmlElement friendid     = temp.CreateElement("FriendId");

                    FriendName.InnerText   = dr["friendFullname"].ToString().Trim();
                    FriendNumber.InnerText = dr["friendQQ"].ToString().Trim();
                    friendid.InnerText     = dr["friendId"].ToString().Trim();
                    friend.AppendChild(FriendNumber);
                    friend.AppendChild(FriendName);
                    friend.AppendChild(friendid);
                    node.AppendChild(friend);
                    //break;
                }
            }
            temp.Save(path);
            #endregion
        }
        protected void submitButton_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();

            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = "insert into [Table] values('" + nameTextBox.Text + "','" + genderRadioButtonList.Text + "','" + Calendar1.SelectedDate.ToShortDateString() + "','" + pobDropDownList.Text + "','" + commentTextBox.Text + "')";
            cmd.ExecuteNonQuery();



            DataSet ds = new DataSet();

            try
            {
                SqlDataAdapter da = new SqlDataAdapter("select * from [Table]", con);
                da.Fill(ds, "table");
            }
            catch
            {
                Label1.Text = "Error while connecting to a database";
            }
            XmlDataDocument doc = new XmlDataDocument(ds);

            doc.Save(MapPath("XMLS//xmlData.xml"));

            con.Close();
        }
Esempio n. 8
0
        private void _Mtd_CrearArchivoISLR(string _P_Str_ID_Archivo)
        {
            System.IO.DirectoryInfo _DirInf = new System.IO.DirectoryInfo("c:\\seniat");
            if (!_DirInf.Exists)
            {
                _DirInf.Create();
            }
            string  _Str_Cadena = "SELECT REPLACE(crifagenretencion,'-','') AS crifagenretencion,cfecha FROM TARCHIVOISLRD WHERE cgroupcomp='" + Frm_Padre._Str_GroupComp + "' AND ccompany='" + Frm_Padre._Str_Comp + "' AND cidarchivoislr='" + _P_Str_ID_Archivo + "'";
            DataSet _Ds         = Program._MyClsCnn._mtd_conexion._Mtd_RetornarDataset(_Str_Cadena);

            if (_Ds.Tables[0].Rows.Count > 0)
            {
                string _Str_RifAgente = _Ds.Tables[0].Rows[0]["crifagenretencion"].ToString().Trim();
                string _Str_Periodo   = _Ds.Tables[0].Rows[0]["cfecha"].ToString().Trim();
                _Str_Cadena             = "SELECT REPLACE(crifprovee,'-','') AS RifRetenido,REPLACE(cnumfact,'-','') AS NumeroFactura, REPLACE(cnumcont,'-','') AS NumeroControl,CONVERT(VARCHAR,cfechaoperacion,103) AS FechaOperacion,ccodigoconcepto AS CodigoConcepto,REPLACE(cmontdocu,',','.') AS MontoOperacion,REPLACE(cporcenreten,',','.') AS PorcentajeRetencion FROM TARCHIVOISLRD WHERE cgroupcomp='" + Frm_Padre._Str_GroupComp + "' AND ccompany='" + Frm_Padre._Str_Comp + "' AND cidarchivoislr='" + _P_Str_ID_Archivo + "'";
                _Ds                     = Program._MyClsCnn._mtd_conexion._Mtd_RetornarDataset(_Str_Cadena);
                _Ds.Tables[0].TableName = "DetalleRetencion";
                //const string _Str_Comillas = "\"";
                //_Ds.DataSetName = "RelacionRetencionesISLR RifAgente=" + _Str_Comillas + _Str_RifAgente + _Str_Comillas + " Periodo=" + _Str_Periodo;
                _Ds.DataSetName        = "RelacionRetencionesISLR";
                _Ds.EnforceConstraints = false;
                XmlDataDocument _Xml_d    = new XmlDataDocument(_Ds);
                XmlDeclaration  _Xml_Decl = _Xml_d.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
                XmlElement      _Xml_Elem = _Xml_d.DocumentElement;
                _Xml_d.InsertBefore(_Xml_Decl, _Xml_Elem);
                XmlAttribute _Xml_a = _Xml_d.CreateAttribute("RifAgente");
                _Xml_a.Value = _Str_RifAgente;
                _Xml_d["RelacionRetencionesISLR"].Attributes.Append(_Xml_a);
                _Xml_a       = _Xml_d.CreateAttribute("Periodo");
                _Xml_a.Value = _Str_Periodo;
                _Xml_d["RelacionRetencionesISLR"].Attributes.Append(_Xml_a);
                _Xml_d.Save("c:\\seniat\\XML_relacionRetencionesISLR_.xml");
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Guarda una puntuación entre las más altas
        /// </summary>
        /// <param name="dificultad">Dificultad en la que se ha jugado (3 para ganadores)</param>
        /// <param name="puntos">Puntos conseguidos</param>
        /// <param name="nombre">Nombre del jugador</param>
        public void guardarPuntuacion(int dificultad, int puntos, string nombre)
        {
            // Se recupera la lista de puntuaciones
            List <Puntuacion> lista = getPuntuaciones(dificultad);

            // Se añade la nueva puntuación y se ordenan todas
            Puntuacion nuevo = new Puntuacion();

            nuevo.Puntos = puntos;
            nuevo.Nombre = nombre;
            lista.Add(nuevo);
            lista.Sort((p, q) => q.Puntos.CompareTo(p.Puntos));

            XmlDataDocument doc = getXML(rutaPuntos);

            // Se busca el tag de modo que coincida con esta dificultad
            XmlNodeList modo     = doc.GetElementsByTagName("modo");
            XmlNode     esteModo = null;

            foreach (XmlNode n in modo)
            {
                if (n.Attributes.GetNamedItem("dif").InnerText.Equals($"{dificultad}"))
                {
                    esteModo = n;
                    break;
                }
            }

            // Si no existe, se lanza error
            if (esteModo == null)
            {
                throw new XmlException();
            }

            // Se borran todas las etiquetas hijas
            while (esteModo.FirstChild != null)
            {
                esteModo.RemoveChild(esteModo.FirstChild);
            }

            // Se limitan las puntuaciones guardadas a 5
            int numDatos = lista.Count < 5 ? lista.Count : 5;

            // Se vuelven a rellenar con los nuevos datos
            for (int i = 0; i < numDatos; i++)
            {
                XmlNode n = esteModo.OwnerDocument.CreateElement("puntuacion");
                esteModo.AppendChild(n);

                XmlNode nodoPuntos = n.OwnerDocument.CreateElement("puntos");
                nodoPuntos.InnerText = lista[i].Puntos.ToString();
                XmlNode nodoNombre = n.OwnerDocument.CreateElement("nombre");
                nodoNombre.InnerText = lista[i].Nombre;

                n.AppendChild(nodoPuntos);
                n.AppendChild(nodoNombre);
            }

            doc.Save(rutaPuntos);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         try
         {
             XmlDocument xmldoc1 = new XmlDocument();
             xmldoc1.Load(Server.MapPath("~/vendor.xml"));
             XmlElement root = xmldoc1.DocumentElement;
             root.RemoveAll();
         }
         catch { }
         DataSet ds = new DataSet();
         try
         {
             SqlConnection con = new SqlConnection(@"Data Source=HPPAV14\HPPAV14;Initial Catalog=EscapediaDB;Integrated Security=True");
             con.Open();
             SqlDataAdapter da = new SqlDataAdapter("select * from Partner", con);
             da.Fill(ds, "vendor");
         }
         catch
         {
             ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('Not able to connect to DB')", true);
         }
         XmlDataDocument doc = new XmlDataDocument(ds);
         doc.Save(MapPath("~/vendor.xml"));
     }
 }
Esempio n. 11
0
        protected void btnSImpan_Click(object sender, EventArgs e)
        {
            DataSet ds           = new DataSet();
            string  dbconnstring = "Data Source=DESKTOP-52BJLFO\\SQLEXPRESS;Initial Catalog=dbUser;Integrated Security=True";

            try
            {
                SqlConnection  dbconn = new SqlConnection(dbconnstring);
                string         sql    = "select * from tr_unit";
                SqlDataAdapter da     = new SqlDataAdapter(sql, dbconn);
                da.Fill(ds, "data");

                XmlDataDocument doc = new XmlDataDocument(ds);
                doc.Save(MapPath("~/latihan-xml/unit2.xml"));

                Xml1.Document = doc;

                XslTransform transform = new XslTransform();
                transform.Load(MapPath("~/latihan-xml/style.xslt"));
                Xml1.Transform = transform;
                Label1.Text    = "Proses selesai!";
            }
            catch
            {
                Label1.Text = "Error connecting database!";
            }
        }
Esempio n. 12
0
        public void Rows_With_Null_Values()
        {
            DataSet   ds    = new DataSet();
            DataTable table = ds.Tables.Add("table1");

            table.Columns.Add("col1", typeof(int));
            table.Columns.Add("col2", typeof(int));

            XmlDataDocument doc = new XmlDataDocument(ds);

            table.Rows.Add(new object[] { 1 });

            StringWriter sw = new StringWriter();

            doc.Save(sw);

            DataSet         ds1  = ds.Clone();
            XmlDataDocument doc1 = new XmlDataDocument(ds1);
            StringReader    sr   = new StringReader(sw.ToString());

            doc1.Load(sr);

            AssertEquals("#1", 1, ds1.Tables [0].Rows [0][0]);
            AssertEquals("#2", true, ds1.Tables [0].Rows [0].IsNull(1));
        }
Esempio n. 13
0
        public void AddLink(string title, string uri)
        {
            XmlDocument doc = new XmlDataDocument();

            doc.Load("RssLinks.xml");
            XmlNode rootNode = doc.SelectSingleNode("links");

            XmlNode linkNode = doc.CreateElement("link");

            XmlNode titleNode = doc.CreateElement("title");
            XmlText titleText = doc.CreateTextNode(title);

            titleNode.AppendChild(titleText);

            XmlNode uriNode = doc.CreateElement("uri");
            XmlText uriText = doc.CreateTextNode(uri);

            uriNode.AppendChild(uriText);

            XmlNode defaultshowNode = doc.CreateElement("defaultshow");
            XmlText defaultshowText = doc.CreateTextNode("false");

            defaultshowNode.AppendChild(defaultshowText);

            linkNode.AppendChild(titleNode);
            linkNode.AppendChild(uriNode);
            linkNode.AppendChild(defaultshowNode);

            rootNode.AppendChild(linkNode);

            doc.Save("RssLinks.xml");
        }
Esempio n. 14
0
    public static void Main()
    {
        DataSet dsNorthwind = new DataSet();

        //Create the connection string.
        String sConnect;

        sConnect = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind";

        //Create a connection object to connect to the northwind db.
        SqlConnection nwconnect = new SqlConnection(sConnect);

        //Create a command string to select all the customers in the WA region.
        String sCommand = "Select * from Customers where Region='WA'";

        //Create an adapter to load the DataSet.
        SqlDataAdapter myDataAdapter = new SqlDataAdapter(sCommand, nwconnect);

        //Fill the DataSet with the selected records.
        myDataAdapter.Fill(dsNorthwind, "Customers");

        //Load the document with the DataSet.
        XmlDataDocument doc = new XmlDataDocument(dsNorthwind);

        //Display the XmlDataDocument.
        doc.Save(Console.Out);
    }
Esempio n. 15
0
        private void update_button_Click(object sender, EventArgs e)
        {
            XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNodeList     xmlnode;
            int             i = temp[0], j = temp[1];
            string          str = null;
            FileStream      fs  = new FileStream("product.xml", FileMode.Open, FileAccess.ReadWrite);

            xmldoc.Load(fs);
            XmlElement  root  = xmldoc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("/Table/Product");

            foreach (XmlNode node in nodes)
            {
                if (node["Product_id"].InnerText.ToString().Trim() == search_textBox.Text)
                {
                    node["Product_price"].InnerText = update_textBox.Text;
                }
            }
            xmldoc.Save(fs);

            /*
             * xmlnode = xmldoc.GetElementsByTagName("Product");
             * xmlnode[i].ChildNodes.Item(j).InnerText.Trim();
             * str = update_textBox.Text;
             * xmlnode[i].ChildNodes.Item(j).InnerText = str;*/
        }
Esempio n. 16
0
        private static void AddNode(string sUid, string sPwd, bool RememberMe)
        {
            bool            isAdd    = true;
            XmlDataDocument UserDate = new XmlDataDocument();

            UserDate.Load(QQuser);
            XmlNode root = UserDate.SelectSingleNode("root");

            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                if (root.ChildNodes[i].Attributes["user"].Value.Trim() == sUid)
                {
                    //更新用户消息
                    if (RememberMe)
                    {
                        root.ChildNodes[i].ChildNodes[0].InnerText = sPwd;
                    }
                    else
                    {
                        root.ChildNodes[i].ChildNodes[0].InnerText = "";
                    }
                    UserDate.Save(QQuser);
                    isAdd = false;
                    break;
                }
            }
            if (isAdd)
            {
                XmlNode    NodeAtt = UserDate.CreateNode(XmlNodeType.Attribute, "user", null);
                XmlElement user    = UserDate.CreateElement("user");
                XmlElement pwd     = UserDate.CreateElement("pwd");
                user.Attributes.SetNamedItem(NodeAtt);
                user.Attributes["user"].Value = sUid;
                if (RememberMe)
                {
                    pwd.InnerText = sPwd;
                }
                else
                {
                    pwd.InnerText = "";
                }
                user.AppendChild(pwd);
                root.AppendChild(user);
                UserDate.Save(QQuser);
            }
        }
Esempio n. 17
0
        private void ToolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
        {
            switch (e.Button.Tag as string)
            {
            case "save":

                try
                {
                    string provider = ProviderComboBox.SelectedItem.ToString();

                    // First Lets Remove the current node for this entire database
                    XmlNode node = settings.SelectSingleNode(string.Format("Languages/Language[@From='{0}']", provider));
                    node.ParentNode.RemoveChild(node);

                    // Grab the parent node of the entire xml file
                    XmlNode parentNode = settings.SelectSingleNode(@"//Languages");

                    // Create our new Language Node entry for this database
                    XmlNode langNode = settings.CreateNode(XmlNodeType.Element, "Language", null);
                    parentNode.AppendChild(langNode);

                    // Fill in it's To/From Attributes
                    XmlAttribute attr = settings.CreateAttribute("From");
                    attr.Value = provider;
                    langNode.Attributes.Append(attr);

                    attr       = settings.CreateAttribute("To");
                    attr.Value = "C#";
                    langNode.Attributes.Append(attr);

                    // Lets sort them in order of the database column type
                    DataTable dt = (DataTable)MappingsDataGridView.DataSource;
                    dt.DefaultView.Sort = "Database ASC";

                    // Now let's add all of the mappings
                    foreach (DataRowView row in dt.DefaultView)
                    {
                        XmlNode typeNode = settings.CreateNode(XmlNodeType.Element, "Type", null);
                        langNode.AppendChild(typeNode);

                        attr       = settings.CreateAttribute("From");
                        attr.Value = (string)row.Row["Database"];
                        typeNode.Attributes.Append(attr);

                        attr       = settings.CreateAttribute("To");
                        attr.Value = (string)row.Row[".NET"];
                        typeNode.Attributes.Append(attr);
                    }

                    settings.Save(this.Settings.LanguageMappingFile);
                }
                catch (Exception ex)
                {
                    this.MainWindow.ShowError(ex);
                }
                break;
            }
        }
Esempio n. 18
0
 private void Form1_Load(object sender, EventArgs e)
 {
     CustomersTable    = CreateDataSet.DataSetFiller.FillDataset(dataFilePath).Tables["Customers"];
     xdd               = new XmlDataDocument(CustomersTable.DataSet);
     dgView.DataSource = CustomersTable;
     xdd.Save(Application.ExecutablePath + "_xdd.xml");
     xmlViewer.Navigate(Application.ExecutablePath + "_xdd.xml");
     CustomersTable.RowChanged += new DataRowChangeEventHandler(CustomersTable_RowChanged);
 }
Esempio n. 19
0
        public void writeSAVE(Stream oldsavefile, string @newsavepath, Stream newsavefile)
        {
            //First things first, we create a backup of the old savefile.
            FileStream save_backup;

            save_backup          = File.OpenWrite(@newsavepath + ".backup");
            oldsavefile.Position = 0;
            oldsavefile.CopyTo(save_backup);
            save_backup.Close();

            //Load save file
            //XmlDataDocument xmlsav = new XmlDataDocument();
            //xmlsav.PreserveWhitespace = true;
            oldsavefile.Position = 0; //We have to reset the position to 0 otherwise this fails
            //xmlsav.Load(oldsavefile); //Load the Save file as an XML document
            XmlNode hnSav = xmlsav.GetElementsByTagName("HacknetSave")[0];
            XmlAttributeCollection miscData = hnSav.Attributes;

            hnSav.Attributes.GetNamedItem("Username").InnerText = userNameInput.Text; //set username
            hnSav.Attributes.GetNamedItem("Language").InnerText = textBox1.Text;      //set language
            if (hideMailFlag.Checked)
            {
                hnSav.Attributes.GetNamedItem("DisableMailIcon").InnerText = "true";
            }
            else
            {
                hnSav.Attributes.GetNamedItem("DisableMailIcon").InnerText = "false";
            }
            XmlNode mission = xmlsav.GetElementsByTagName("mission")[0];

            mission.Attributes.GetNamedItem("next").Value  = missionInput.Text;
            mission.Attributes.GetNamedItem("goals").Value = goalInput.Text;



            //===========================================================
            //Now we actually save the values to a file
            //===========================================================

            //xmlsav.PreserveWhitespace = false;
            newsavefile.Close();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Indent          = false;
            xmlSettings.NewLineHandling = System.Xml.NewLineHandling.None;
            //xmlSettings.
            XmlWriter newsavefile_final = XmlWriter.Create(newsavepath, xmlSettings);

            xmlsav.Normalize();
            xmlsav.Save(newsavefile_final);

            newsavefile_final.Close();

            Console.WriteLine("Saved successfully!");
        }
Esempio n. 20
0
        public void DataSet_ColumnNameWithSpaces()
        {
            DataSet ds = new DataSet("New Data Set");

            DataTable table1 = ds.Tables.Add("New Table 1");
            DataTable table2 = ds.Tables.Add("New Table 2");

            table1.Columns.Add("col 1", typeof(int));
            table1.Columns.Add("col 2", typeof(int));

            table1.PrimaryKey = new DataColumn[] { ds.Tables [0].Columns [0] };

            // No exception shud be thrown
            XmlDataDocument doc = new XmlDataDocument(ds);

            // Should fail to save as there are no rows
            try
            {
                doc.Save(new StringWriter());
                Fail("#1");
            }
            catch (InvalidOperationException)
            {
            }

            table1.Rows.Add(new object[] { 0 });
            table1.Rows.Add(new object[] { 1 });
            table1.Rows.Add(new object[] { 2 });

            // No exception shud be thrown
            StringWriter swriter = new StringWriter();

            doc.Save(swriter);

            StringReader    sreader = new StringReader(swriter.ToString());
            DataSet         ds1     = ds.Clone();
            XmlDataDocument doc1    = new XmlDataDocument(ds1);

            AssertEquals("#2", 0, ds1.Tables [0].Rows.Count);
            doc1.Load(sreader);
            AssertEquals("#3", 3, ds1.Tables [0].Rows.Count);
        }
Esempio n. 21
0
        private void SaveFile()
        {
            Validate();
            xmlGridView.EndEdit();
            CurrencyManager cm = (CurrencyManager)xmlGridView.BindingContext[xmlGridView.DataSource, "data"];

            cm.EndCurrentEdit();
            xmlDocument.Save(xmlFileName);
            isDataModified = false;
            UpdateForm();
        }
Esempio n. 22
0
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            if (this.txt_observacion.Text.Trim() == "")
            {
                this.lbl_error.Text = "Debe ingresar una observacion";
                return;
            }


            XmlTextWriter xml = new XmlTextWriter(me, System.Text.Encoding.UTF8);

            xml.Formatting = Formatting.Indented;
            xml.Namespaces = true;
            xml.WriteStartDocument(false);
            xml.WriteStartElement("Root");

            nline = 10000;

            for (int i = 0; i < gr_dato.Rows.Count; i++)
            {
                operacion_nomina(Convert.ToInt32(gr_dato.DataKeys[i].Values[0].ToString()),
                                 Convert.ToInt32(gr_dato.DataKeys[i].Values[1].ToString()),
                                 Convert.ToInt16(gr_dato.DataKeys[i].Values[5].ToString()), xml);
            }

            xml.WriteEndElement();
            xml.WriteEndDocument();
            xml.Flush();

            me.Position = 0;
            string r = new StreamReader(me).ReadToEnd();

            xml.Close();
            me.Close();

            string strPath = System.Configuration.ConfigurationManager.AppSettings["DIARIO_GENERAL"];


            string          path  = strPath + id_inventario + "-" + DateTime.Now.ToString("dd-MM-yy") + ".xml";
            XmlDataDocument xmDoc = new XmlDataDocument();

            xmDoc.LoadXml(r);
            xmDoc.Save(path);



            string mrendir = new chequesBC().rendir_cheque(Convert.ToInt32(id_inventario), this.txt_observacion.Text.Trim(),
                                                           Convert.ToInt32(this.total.Text));


            this.ImageButton1.Enabled = false;

            this.lbl_error.Text = "CONTROL DE EGRESO REALIZADO CON EXITO";
        }
Esempio n. 23
0
        /// <summary>
        /// Guarda las opciones
        /// </summary>
        /// <param name="b">Bean de opciones</param>
        public void guardaOpciones(BeanOpciones b)
        {
            XmlDataDocument xml = getXML(rutaOpciones);

            xml.GetElementsByTagName("esGorda")[0].InnerText              = b.EsGorda ? "1" : "0";
            xml.GetElementsByTagName("sacaLengua")[0].InnerText           = b.SacaLengua ? "1" : "0";
            xml.GetElementsByTagName("frecuenciaSacaLengua")[0].InnerText = b.FrecuenciaSacaLengua.ToString();
            xml.GetElementsByTagName("indiceManzana")[0].InnerText        = b.IndiceManzana.ToString();

            xml.Save(rutaOpciones);
        }
Esempio n. 24
0
        public static void ConvertFormResx(string filePath, string targetLang, string destinationPath)
        {
            XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNodeList     xmlnode;
            int             i            = 0;
            string          strEng       = string.Empty;
            List <string>   strConverted = new List <string>();
            FileStream      fs           = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);

            xmldoc.Load(fs);
            xmlnode = xmldoc.GetElementsByTagName("data");
            XmlNodeList aNodes = xmldoc.SelectNodes("/root/data");

            for (i = 0; i < aNodes.Count; i++)
            {
                string attrVal = aNodes[i].Attributes["name"].Value;
                if (attrVal.EndsWith(".Text"))
                {
                    XmlNodeList aInnerNodes = aNodes[i].ChildNodes;
                    string      sNew        = aInnerNodes[1].InnerXml;
                    if (sNew.Contains("&amp;"))
                    {
                        sNew = sNew.Replace("&amp;", string.Empty);
                    }
                    if (!string.IsNullOrEmpty(sNew))
                    {
                        strConverted            = Internalization.YandexTranslate.Translate(targetLang, sNew);
                        aInnerNodes[1].InnerXml = strConverted[0];
                    }
                }
            }
            fs.Close();
            if (destinationPath == string.Empty)
            {
                xmldoc.Save(Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_" + targetLang + Path.GetExtension(filePath));
            }
            else
            {
                xmldoc.Save(destinationPath + "_" + targetLang + Path.GetExtension(filePath));
            }
        }
Esempio n. 25
0
        public static void GetStringValueFromResource(string filePath, string targetLang, string destinationPath)
        {
            List <String>   resxValue = new List <string>();
            XmlDataDocument xmldoc    = new XmlDataDocument();
            XmlNodeList     xmlnode;
            int             i            = 0;
            string          strEng       = string.Empty;
            List <string>   strConverted = new List <string>();
            FileStream      fs           = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);

            xmldoc.Load(fs);
            xmlnode = xmldoc.GetElementsByTagName("value");
            XmlNodeList aNodes = xmldoc.SelectNodes("/root/data/value");

            foreach (XmlNode aNode in aNodes)
            {
                if (aNode.InnerText != null)
                {
                    string currentValue = aNode.InnerText;
                    if (currentValue.Contains("&"))
                    {
                        currentValue = currentValue.Replace("&", String.Empty);
                    }
                    if (!string.IsNullOrEmpty(currentValue))
                    {
                        strConverted    = Internalization.YandexTranslate.Translate(targetLang, currentValue);
                        aNode.InnerText = strConverted[0];
                    }
                }
            }
            fs.Close();
            if (destinationPath == string.Empty)
            {
                xmldoc.Save(Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_" + targetLang + Path.GetExtension(filePath));
            }
            else
            {
                xmldoc.Save(destinationPath + "_" + targetLang + Path.GetExtension(filePath));
            }
        }
        public void RemoveLongState()
        {
            XmlNodeList states      = jflap.GetElementsByTagName("state");
            XmlNodeList transitions = jflap.GetElementsByTagName("transition");

            for (int i = 0; i < states.Count; i++)
            {
                for (int y = 0; y < nodes.Count; y++)
                {
                    if (states[i].Attributes["id"].Value == nodes[y].id)
                    {
                        for (int j = 0; j < ts.Count; j++)
                        {
                            if (states[i].Attributes["id"].Value == ts[j].to || nodes[y].initial)
                            {
                                break;
                            }
                            if (j == ts.Count - 1)
                            {
                                for (int z = 0; z < transitions.Count; z++)
                                {
                                    foreach (XmlNode x in transitions[z].SelectNodes("from"))
                                    {
                                        if (x.InnerText == states[i].Attributes["id"].Value)
                                        {
                                            transitions[z].ParentNode.RemoveChild(transitions[z]);
                                            ts.Remove(ts[z]);
                                        }
                                    }
                                }
                                states[i].ParentNode.RemoveChild(states[i]);
                                nodes.Remove(nodes[i]);
                            }
                        }
                    }
                }
            }
            jflap.Save(nameFile);
        }
        public void Save(string outputDirectory)
        {
            if (Directory.Exists(outputDirectory) == false)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Invalid output directory {0}", outputDirectory));
            }

            string cultureFile = Path.Combine(outputDirectory, "culture.txt");

            if (File.Exists(cultureFile))
            {
                using (StreamReader reader = new StreamReader(cultureFile))
                {
                    culture = reader.ReadToEnd();
                }
            }

            foreach (KeyValuePair <AssemblyName, ResourceDataCollection> pair in resources)
            {
                AssemblyName           assemblyName = pair.Key;
                ResourceDataCollection data         = pair.Value;

                string fileName = Path.Combine(outputDirectory, assemblyName.Name + ".xml");

                InsertExistingTranslations(fileName, data);

                using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartElement("root");
                    writer.WriteStartElement("assembly");
                    writer.WriteAttributeString("culture", string.IsNullOrEmpty(fileCulture) ? culture : fileCulture);
                    writer.WriteAttributeString("name", assemblyName.Name + ".resources");
                    writer.WriteAttributeString("version", assemblyName.Version.ToString());
                    writer.WriteEndElement();

                    foreach (ResourceData rd in data)
                    {
                        writer.WriteStartElement("resources");
                        writer.WriteAttributeString("name", rd.ResourceName);
                        writer.WriteAttributeString("type", rd.ResourceType);
                        XmlDataDocument xml = new XmlDataDocument(rd.DataSet);
                        xml.Save(writer);
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                    writer.Close();
                }
            }
        }
Esempio n. 28
0
        private void button1_Click(object sender, EventArgs e)
        {
            int row = dataGridView1.Rows.Count;
            int col = dataGridView1.Rows[1].Cells.Count;
            int sum = 0, a = 0;

            //check the persentage
            for (int i = 0; i < row; i++)
            {
                if (dataGridView1.Rows[i].Cells[1].Value != null)
                {
                    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
                }
                else
                {
                    a++;
                }
            }

            if (a != 0 || sum != 100)
            {
                MessageBox.Show("Invalid Input");
            }
            else
            {
                //MessageBox.Show("Valid input");
                XmlDataDocument xmlDoc = new XmlDataDocument();
                xmlDoc.Load("task.xml");
                XmlNodeList nodeList = xmlDoc.SelectSingleNode("UIC").ChildNodes;
                int         count    = 0;
                foreach (XmlNode xn in nodeList)
                {
                    XmlElement xe = (XmlElement)xn;

                    if (xe.GetAttribute("CourseName") == CourseName)
                    {
                        XmlNodeList nls = xe.ChildNodes;
                        foreach (XmlNode xn1 in nls)
                        {
                            xn1.Attributes[3].Value = dataGridView1.Rows[count].Cells[1].Value.ToString();
                            count++;
                        }
                    }
                }
                xmlDoc.Save("task.xml");
                MessageBox.Show("Saved");
            }
        }
Esempio n. 29
0
        public void UpdateWebConfig(string key, string strValue)
        {
            string          keyPath       = "/configuration/appSettings/add[@key='?']";
            XmlDataDocument webConfig     = new XmlDataDocument();
            string          webConfigPath = HttpContext.Current.Server.MapPath("~") + @"\web.config";

            webConfig.Load(webConfigPath);
            XmlNode updateKey = webConfig.SelectSingleNode((keyPath.Replace("?", key)));

            if (updateKey == null)
            {
                throw new ArgumentException("没有找到<add key='" + key + "'value=/>的配置字节");
            }
            updateKey.Attributes["value"].InnerText = strValue;
            webConfig.Save(webConfigPath);
        }
Esempio n. 30
0
        void ModifyXml(string sFile)
        {
            Debug.WriteLine(sFile);

            XmlDocument doc = new XmlDataDocument();

            //string sFile ="G:/Itf/Source/WireTrace/Itf_WireTrace.vcproj";
            System.IO.File.Copy(sFile, sFile + ".bk");

            doc.Load(sFile);
            XmlElement  root = doc.DocumentElement;
            XmlNodeList nl   = root.SelectNodes("//Tool[@Name='VCCLCompilerTool']");

            for (int i = 0; i < nl.Count; i++)
            {
                XmlNode node = nl.Item(i);

                if (node.Attributes["AdditionalOptions"] != null)
                {
                    string s = node.Attributes["AdditionalOptions"].Value;
                    if (s.IndexOf("/Zm") < 0)
                    {
                        node.Attributes["AdditionalOptions"].Value = "/Zm200 " + s;
                    }

                    Debug.WriteLine(s + " --> " + node.Attributes["AdditionalOptions"].Value);
                }
                else
                {
                    XmlAttribute attr = node.OwnerDocument.CreateAttribute("AdditionalOptions");
                    attr.Value = "/Zm200 ";
                    node.Attributes.Append(attr);

                    Debug.WriteLine(" --> " + node.Attributes["AdditionalOptions"].Value);
                }
                //node.Attributes.Append(
                for (int j = 0; j < node.Attributes.Count; j++)
                {
                    //XmlAttribute nodeAttr =node.Attributes.Item(j);
                    //nodeAttr.
                    //nodeAttr.InnerText
                }
            }

            doc.Save(sFile);
        }