AcceptChanges() public method

Commits all the changes made to this since it was loaded or the last time was called.
public AcceptChanges ( ) : void
return void
 public void TestSerializeDataSet()
 {
     DataSet ds = new DataSet("DataSet");
     //Table 1
     ds.Tables.Add(new DataTable("Table"));
     ds.Tables[0].Columns.Add("col1", typeof(int));
     ds.Tables[0].Columns.Add("col2", typeof(int));
     DataRow dr = ds.Tables[0].NewRow();
     dr["col1"] = 1;
     dr["col2"] = 2;
     ds.Tables[0].Rows.Add(dr);
     //Table 2
     ds.Tables.Add(new DataTable("Table1"));
     ds.Tables[1].Columns.Add("col1_col1", typeof(int));
     ds.Tables[1].Columns.Add("col2", typeof(int));
     dr = ds.Tables[1].NewRow();
     dr["col1_col1"] = 1;
     ds.Tables[1].Rows.Add(dr);
     ds.Relations.Add(new DataRelation("table_table1", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0], true));
     ds.AcceptChanges();
     string actualXml = XmlSerializationHelper.SerializeDataTable(ds.Tables[0], true);
     string expectedXml = "<DataSet><Table><col1>1</col1><col2>2</col2></Table><Table1><col1_col1>1</col1_col1></Table1></DataSet>";
     Trace.Write(actualXml);
     Assert.AreEqual(actualXml, expectedXml);
 }
Esempio n. 2
0
        /// <summary>
        /// 删除
        /// </summary>
        private void Delete()
        {
            if (this.ds.Tables.Count == 0 && this.ds.Tables[0].Rows.Count == 0)
            {
                return;
            }
            if (MessageBox.Show("删除文件" + lbFileName.Text + ",此操作不可恢复,是否继续", "警告", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == DialogResult.No)
            {
                return;
            }
            string ID     = this.lbPrimaryID.Text;
            string strSql = "delete  from com_downloadfile t where t.primary_id = '{0}'";

            strSql = string.Format(strSql, ID);
            OracleTransaction trans = this.con.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);

            mgr.SetTrans(trans);
            int i = mgr.ExeNoQuery(this.con, strSql);

            if (i <= 0)
            {
                trans.Rollback();
                MessageBox.Show("删除数据失败" + mgr.Err);
            }
            else
            {
                trans.Commit();
                object[] keys = new object[] { this.lbPrimaryID.Text };
                DataRow  row  = ds.Tables[0].Rows.Find(keys);
                this.ds.Tables[0].Rows.Remove(row);
                ds.AcceptChanges();
                MessageBox.Show("删除成功");
            }
        }
Esempio n. 3
0
 private void btnShto_Click(object sender, System.EventArgs e)
 {
     try
     {
         // Nese data qe eshte e futur eshte me e vogel ose e barabarte me daten e tanishme te
         // sistemi atehere jep mesazh qe te nderroje daten dhe dil
         if (Convert.ToDateTime(this.dtpShtoMesazh.Value) <= DateTime.Now)
         {
             MessageBox.Show("Koha e mesazhit te alarmit duhet te jete me e madhe se koha qe ka sistemi juaj",
                             "Perkujtese", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         // Nese nuk eshte konfiguruar akoma dataseti dsMesazhe atehere duhet krijuar struktura per te.
         // Ky dataset do te kete 2 kolona: njera do te jete data dhe ora e alarmit dhe tjetra do
         // mbaje mesazhin e alarmit
         if (dsMesazhe.Tables.Count == 0)
         {
             DataTable dtMesazhet = new DataTable("Mesazhet");
             dtMesazhet.Columns.Add("Data", typeof(String));
             dtMesazhet.Columns.Add("Mesazhi", typeof(String));
             dsMesazhe.Tables.Add(dtMesazhet);
             dsMesazhe.AcceptChanges();
         }
         // Hedhim nje rresht te ri ne dsMesazhe
         DataRow dr = dsMesazhe.Tables[0].NewRow();
         dr["Data"]    = Convert.ToDateTime(this.dtpShtoMesazh.Value).ToString("dd/MM/yyyy HH:mm");
         dr["Mesazhi"] = this.txtShtoMesazh.Text;
         dsMesazhe.Tables[0].Rows.Add(dr);
         dsMesazhe.AcceptChanges();
         // Bejme renditjen e rreshtave te datasetit sipas kohes se mesazhit
         DataTable dt1 = dsMesazhe.Tables[0].Copy();
         dt1.Rows.Clear();
         DataRow[] drMesazhe = dsMesazhe.Tables[0].Select("", "Data");
         for (int i = 0; i < drMesazhe.Length; i++)
         {
             DataRow dr1 = dt1.NewRow();
             dr1["Data"]    = drMesazhe[i]["Data"];
             dr1["Mesazhi"] = drMesazhe[i]["Mesazhi"];
             dt1.Rows.Add(dr1);
         }
         dsMesazhe.Tables.Clear();
         dsMesazhe.Tables.Add(dt1);
         // Hedhim datasetin ne Xml
         dsMesazhe.WriteXml(Application.StartupPath + "\\MesazheAlarmi.xml", XmlWriteMode.WriteSchema);
         MainForm main = this.Main as MainForm;
         main.StartTimer1();
         this.dgMesazhe.DataSource           = dsMesazhe.Tables[0];
         this.dgMesazhe.RootTable.DataMember = this.dsMesazhe.Tables[0].TableName;
     }
     catch (Exception ex)
     {
         return;
     }
 }
Esempio n. 4
0
        public static void Load_ListDS()
        {
            if (File.Exists(m_MySensors_FilePath))
              {
            SensorDS = new DataSet("SensorDS");
            SensorDS.ReadXml(m_MySensors_FilePath, XmlReadMode.ReadSchema);
              }
              else
              {
            if (SensorDS != null)
            {
              SensorDS.Dispose();
              GC.Collect();
            }
            DataTable dt0 = new DataTable("SensorTBL");
            dt0.Columns.Add(new DataColumn(Cfg.C_IS_PICK, Type.GetType(Cfg.SYS_INT32)));
            dt0.Columns[Cfg.C_IS_PICK].DefaultValue = 1;

            dt0.Columns.Add(new DataColumn(Sensor.C_SENSOR_ID, Type.GetType(Cfg.SYS_INT64)));
            dt0.Columns[Sensor.C_SENSOR_ID].DefaultValue = Sensor.Sensor_ID;

            dt0.Columns.Add(new DataColumn(Sensor.C_LOCATION_NAME, Type.GetType(Cfg.SYS_STRING)));
            dt0.Columns[Sensor.C_LOCATION_NAME].DefaultValue = Sensor.Location_Name;

            dt0.Rows.Add(dt0.NewRow());
            dt0.AcceptChanges();
            SensorDS = new DataSet("SensorDS");
            SensorDS.Tables.Add(dt0);
            SensorDS.AcceptChanges();
              }
              SensorDS.Tables[0].DefaultView.Sort = Sensor.C_SENSOR_ID;
        }
Esempio n. 5
0
        private DataSet importExcelFile(string fileName)
        {
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

            System.Data.DataSet ds     = new System.Data.DataSet();
            Workbook            wkBook = excelApp.Workbooks.Open(fileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

            ds.DataSetName = wkBook.Name;

            foreach (Worksheet ws in wkBook.Worksheets)
            {
                ds.Merge(importExcelSheet(ws));
                ds.AcceptChanges();
            }

            System.Windows.Forms.DataGridTableStyle tstyle = new System.Windows.Forms.DataGridTableStyle();
            tstyle.AllowSorting   = true;
            tstyle.RowHeaderWidth = 0;

            DG.TableStyles.Add(tstyle);

            DG.NavigateBack();
            DG.NavigateBack();
            DG.DataSource = ds;

            excelApp.Quit();
            releaseObject(excelApp);
            releaseObject(wkBook);

            return(ds);
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            // string connectionString = @"data source=(localDB)\v11.0; Initial catalog=TrainingDB; integrated security=SSPI";

            //string connectionString = "data source=192.168.20.125;database=SMSDB;Integrated Security=false; user id=sa; password=leads@123";

            string connectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\TrainingDB.mdf;Initial Catalog=TrainingDB;Integrated Security=True";

            string commandString = @"SELECT * FROM Shippers";

            SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString);

            SqlCommandBuilder scb = new SqlCommandBuilder(dataAdapter);

            DataSet myDataSet = new DataSet();
            dataAdapter.Fill(myDataSet, "Shippers");

            DataTable sTable = myDataSet.Tables["Shippers"];

            // add data
            object[] o = { 1, "General", "555-1212" };
            sTable.Rows.Add(o);

            dataAdapter.Update(myDataSet, "Shippers");

            myDataSet.AcceptChanges();

            Console.ReadKey();
        }
Esempio n. 7
0
 public Task UpdateCustomerData(DataSet updatedCustomerData)
 {
     // simulate save to database and store in memory
     updatedCustomerData.AcceptChanges();
     customerData = updatedCustomerData;
     return(Task.CompletedTask);
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serverAPI"></param>
        public wfrm_System_Frame(ServerAPI serverAPI)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            try
            {
                m_ServerAPI = serverAPI;

                dsSettings = m_ServerAPI.GetSettings();
                dsSettings.AcceptChanges();
            }
            catch(Exception x){
                wfrm_Error frm = new wfrm_Error(x,new System.Diagnostics.StackTrace());
                frm.ShowDialog(this);
            }

            InitTab();
        }
Esempio n. 9
0
        public void TestMethod1()
        {
            DataSet dataSet = new DataSet("dataSet");
            dataSet.Namespace = "NetFrameWork";
            DataTable table = new DataTable();
            DataColumn idColumn = new DataColumn("id", typeof(int));
            idColumn.AutoIncrement = true;

            DataColumn itemColumn = new DataColumn("item");
            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);
            dataSet.Tables.Add(table);

            for (int i = 0; i < 2; i++)
            {
                DataRow newRow = table.NewRow();
                newRow["item"] = "item " + i;
                table.Rows.Add(newRow);
            }

            dataSet.AcceptChanges();

            var jsonResult = OrbCore.toJson(dataSet);

            Console.WriteLine(jsonResult);
        }
		public DataSet GetReleaseFileInfo(string componentCode, string version)
		{
			// get XML doc
			XDocument xml = GetReleasesFeed();

			// get current release
			var release = (from r in xml.Descendants("release")
						   where r.Parent.Parent.Attribute("code").Value == componentCode
						   && r.Attribute("version").Value == version
						   select r).FirstOrDefault();

			if (release == null)
				return null; // requested release was not found

			DataSet ds = new DataSet();
			DataTable dt = ds.Tables.Add();
			dt.Columns.Add("ReleaseFileID", typeof(int));
			dt.Columns.Add("FullFilePath", typeof(string));
			dt.Columns.Add("UpgradeFilePath", typeof(string));
			dt.Columns.Add("InstallerPath", typeof(string));
			dt.Columns.Add("InstallerType", typeof(string));

			dt.Rows.Add(
				Int32.Parse(release.Element("releaseFileID").Value),
				release.Element("fullFilePath").Value,
				release.Element("upgradeFilePath").Value,
				release.Element("installerPath").Value,
				release.Element("installerType").Value);

			ds.AcceptChanges(); // save
			return ds;
		}
Esempio n. 11
0
 /// <summary>
 /// Retrieve excel data and convert it to dataset
 /// </summary>
 /// <param name="file">Excel binary file.</param>
 /// <returns>Dataset containing the data of the sheet pertaining to the position specified</returns>
 public DataSet GetDataSet(byte[] file)
 {
     try
      {
     //try to create an excel application
     CreateExcelApplication();
     KeepFiles = false;
     OpenWorkbook(file);
     List<string> sheets = new List<string>();
     foreach (Worksheet s in Application.Worksheets)
     {
        //ignore hidden sheets
        if (s.Visible != XlSheetVisibility.xlSheetVisible)
        {
           continue;
        }
        sheets.Add(s.Name);
        //release com obj
        ReleaseComObject(s);
     }
     //read respective sheets
     DataSet ds = new DataSet();
     foreach (string s in sheets)
     {
        ds.Tables.Add(GetExcelData(s));
     }
     ds.AcceptChanges();
     return ds;
      }
      finally
      {
     this.Dispose();
      }
 }
Esempio n. 12
0
        public DataSet getmenu(string department)
        {
            EmployeeDao employeedao = new EmployeeDao();
            Employee employee = employeedao.getempdepartment(department);
            ConnectionDao ConnectionDao = new ConnectionDao();
            SqlDataAdapter adp = new SqlDataAdapter("select department_name,weburl from Department where Department_Name='" + employee.department + "'", ConnectionDao.getConnection());
            DataSet ds4 = new DataSet();
            adp.Fill(ds4);
            string Department = ds4.Tables[0].Rows[0]["department_name"].ToString();
            if (Department == "Sales")
            {
                ds4 = addMenu(ds4, "Email");
            }

            if (Department == "Corporate")
            {
                ds4.Tables[0].Rows.RemoveAt (0);
                ds4.AcceptChanges();

                ds4 = addMenu(ds4, "Customer");
                ds4 = addMenu(ds4, "Email");

                ds4 = addMenu(ds4, "Ticketing");
                ds4 = addMenu(ds4, "Dashboard");
                ds4 = addMenu(ds4, "Reports");

            }
            return ds4;
        }
Esempio n. 13
0
        public static NavisionDBUser Abrir_Login(string UserId, string Password, ref DataSet DsRes, NavisionDBConnection DBConn)
        {
            NavisionDBUser DBUser = null;
            DsRes = Utilidades.GenerarResultado("No conectado");
            DsRes.Tables[0].Columns.Add("Connected", Type.GetType("System.Boolean"), "false");
            DsRes.Tables[0].AcceptChanges();
            try
            {
                DBUser = DBConn.DoLogin(UserId, Password, ref DsRes);

                //Obtengo los roles
                if ((DsRes.Tables.Count > 0) && (DsRes.Tables[0].Columns.Count > 0) && (!DsRes.Tables[0].Columns.Contains("Error")))
                    if (Convert.ToBoolean(DsRes.Tables[0].Rows[0]["Connected"]) == true)
                    {
                        DsRes.Tables[0].Columns.Add("Administracion", System.Type.GetType("System.Boolean"));
                        DsRes.Tables[0].Columns.Add("Gestion", System.Type.GetType("System.Boolean"));
                        DsRes.Tables[0].Columns.Add("Compras", System.Type.GetType("System.Boolean"));
                        DsRes.Tables[0].Columns.Add("Mensajería", System.Type.GetType("System.Boolean"));
                        DsRes.Tables[0].Columns.Add("Comercial", System.Type.GetType("System.Boolean"));

                        NavisionDBTable dt = new NavisionDBTable(DBConn, DBUser);
                        NavisionDBCommand cmd = new NavisionDBCommand(DBConn);
                        NavisionDBDataReader rd;

                        dt.TableName = "Mobile Users";

                        dt.AddColumn("Administracion");
                        dt.AddColumn("Gestion");
                        dt.AddColumn("Compras");
                        dt.AddColumn("Mensajería");
                        dt.AddColumn("Comercial");

                        dt.AddFilter("User ID", UserId);
                        dt.AddFilter("Password", Password);

                        cmd.Table = dt;
                        rd = cmd.ExecuteReader(false);

                        if (rd.RecordsAffected > 0)
                        {
                            DsRes.Tables[0].Rows[0]["Administracion"] = rd.GetBoolean(0);
                            DsRes.Tables[0].Rows[0]["Gestion"] = rd.GetBoolean(1);
                            DsRes.Tables[0].Rows[0]["Compras"] = rd.GetBoolean(2);
                            DsRes.Tables[0].Rows[0]["Mensajería"] = rd.GetBoolean(3);
                            DsRes.Tables[0].Rows[0]["Comercial"] = rd.GetBoolean(4);
                        }

                        DsRes.Tables[0].AcceptChanges();
                        DsRes.AcceptChanges();
                    }

                return DBUser;
            }
            catch (Exception ex)
            {
                Utilidades.GenerarError(UserId, "Abrir_Login()", ex.Message);
                return null;
            }
        }
 private static DataSet getDataSet()
 {
     DataSet op_ds=new DataSet();
     DataTable v_dt=new DataTable();
     op_ds.Tables.Add(v_dt);
     op_ds.AcceptChanges();
     return op_ds;
 }
Esempio n. 15
0
	void MainForm_Load (object sender, EventArgs e)
	{
		_dataSet = new DataSet ();
		_dataSet.ReadXml ("test.xml");
		_dataGrid.DataSource = _dataSet;
		_dataGrid.DataMember = "Table";
		_dataSet.AcceptChanges ();
	}
Esempio n. 16
0
        private void readDictionaryFile(string filename)
        {
            try
            {
                // Read the XML document back in.
                System.IO.FileStream     fsReadXml   = new System.IO.FileStream(filename, System.IO.FileMode.Open);
                System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml);
                dictionaryDataSet.ReadXml(myXmlReader, XmlReadMode.IgnoreSchema);                               // we already have schema
                myXmlReader.Close();

                dictionaryDataSet.AcceptChanges();
            }
            catch
            {
                LibSys.StatusBar.Error("bad dictionary at " + filename);
            }
        }
Esempio n. 17
0
        protected void btnAddRcd_Click(object sender, EventArgs e)
        {
            this.txtSN.Focus();
            if (this.txtSN.Text.Trim() == "")
            {
                Methods.AjaxMessageBox(this, "物料序列号不能为空!"); return;
            }

            int rc = Methods.getMatierialIDCount(this.txtSN.Text.Trim());
            if (rc > 0)
            {
                Methods.AjaxMessageBox(this, "此物料序列号已经存在!"); return;
            }
            else if (rc < 0) { Methods.AjaxMessageBox(this, "查询部件序列号时出现异常,详情请查看日志!"); return; }

            ds = (DataSet)ViewState["tmpds"];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (this.txtSN.Text.Trim() == ds.Tables[0].Rows[i]["ID"].ToString())
                {
                    Methods.AjaxMessageBox(this, "此物料序列号已经存在!"); return;
                }
            }

            int Len = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MIDLenInSN"]);
            if (this.txtSN.Text.Trim().Length <= Len)
            {
                Methods.AjaxMessageBox(this, "此部件序列号长度必须" + Len + "位以上!"); return;
            }

            DataRow r = ds.Tables[0].NewRow();//将数据源添加一新行

            string mid = this.txtSN.Text.Trim().Substring(0, Len);
            //if(mid!=ModelID)
            //{
            //        Methods.AjaxMessageBox(this,"序列号对应的品号与计划中的品号不一致!"); return;
            //}
            //WSProcedureCtrl.ProcedureCtrl pctrl = new ProcedureCtrl();
            //if (!pctrl.CheckModel(mid, SessionUser.ID))
            //{
            //    Methods.AjaxMessageBox(this, "序列号对应的品号与计划中的品号不一致!"); return;
            //}

            r["ID"] = this.txtSN.Text.Trim();
            r["ModelID"] = mid;
            r["Batch"] = "";
            r["Vendor"] = "";
            r["EmployeeID"] = "";
            r["FoundTime"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd");
            r["Remark"] = "";

            ds.Tables[0].Rows.InsertAt(r, 0);
            ds.AcceptChanges();

            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();
        }
Esempio n. 18
0
 public void MyTestInitialize()
 {
     dataSet = new DataSet("TestSet");
     dataSet.Tables.Add("Property");
     dataSet.Tables["Property"].Columns.Add("Property", typeof (string));
     dataSet.Tables["Property"].Columns.Add("Value", typeof(string));
     dataSet.Tables["Property"].Rows.Add(new object[] {"MyName", "Put Stuff Here" });
     dataSet.AcceptChanges();
 }
Esempio n. 19
0
        public byte[] Get_Restore_Files()
        {
            DataSet DataSet = new System.Data.DataSet();

            DataSet.Tables.Add("RestoreFiles");
            DataSet.Tables["RestoreFiles"].Columns.Add("RESTORE_DATETIME", typeof(DateTime));
            DataSet.Tables["RestoreFiles"].Columns.Add("RESTORE_FILE", typeof(String));

            StringBuilder strQry = new StringBuilder();

            string strFileDirectory = AppDomain.CurrentDomain.BaseDirectory + "Backup";

            if (Directory.Exists(strFileDirectory))
            {
                string strDataBaseName = "InteractPayrollClient_";
#if (DEBUG)
                strDataBaseName = "InteractPayrollClient_Debug_";
#endif
                string[] filePaths = Directory.GetFiles(@strFileDirectory, strDataBaseName + @"*.bak");

                if (filePaths.Length > 0)
                {
                    for (int intRow = 0; intRow < filePaths.Length; intRow++)
                    {
                        int intDateTimeOffset = filePaths[intRow].IndexOf(strDataBaseName) + strDataBaseName.Length;

                        if (intDateTimeOffset + 19 <= filePaths[intRow].Length)
                        {
                            DataRow drDataRow = DataSet.Tables["RestoreFiles"].NewRow();

                            drDataRow["RESTORE_FILE"] = filePaths[intRow];

                            try
                            {
                                DateTime myFileDateTime = DateTime.ParseExact(filePaths[intRow].Substring(intDateTimeOffset, 15), "yyyyMMdd_HHmmss", null);

                                drDataRow["RESTORE_DATETIME"] = myFileDateTime;
                            }
                            catch
                            {
                            }

                            DataSet.Tables["RestoreFiles"].Rows.Add(drDataRow);
                        }
                    }
                }
            }

            DataSet.AcceptChanges();

            byte[] bytCompress = clsDBConnectionObjects.Compress_DataSet(DataSet);
            DataSet.Dispose();
            DataSet = null;

            return(bytCompress);
        }
Esempio n. 20
0
        /// <summary>
        /// it saves the data edited in the same file and gives a message box that its done.. and also can be done for multiple nodes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnsave_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
                ds.ReadXml("BasicInfo.xml");                 //taking new file and saving in it....
                ds.Tables[0].Rows[0]["name"] = "hi";// rtxtshow.Text;   //taking node and saving it
                ds.AcceptChanges();
                ds.WriteXml("BasicInfo.xml");

                MessageBox.Show("FILE UPDATED....");
        }
Esempio n. 21
0
		//修改默认语言 
		public static void WriteDefaultLanguage(string lang)
		{
			DataSet ds = new DataSet();
			ds.ReadXml("LanguageDefine.xml");
			DataTable dt = ds.Tables["Language"];

			dt.Rows[0]["DefaultLanguage"] = lang;
			ds.AcceptChanges();
			ds.WriteXml("LanguageDefine.xml");
		}
Esempio n. 22
0
        //public static string GetFilePath(string fileName)
        //{
        //    int index = fileName.IndexOf("/M00/");
        //    return index > -1 ? fileName.Remove(0, index + 4) : fileName;
        //}

        //public static void SaveData(string id, string path)
        //{
        //    DataTable dt;
        //    if (0 == Global.Dataset.Tables.Count)
        //    {
        //        dt = new DataTable("FastDFS");
        //        dt.Columns.Add("ID", typeof(string));
        //        dt.Columns.Add("Path", typeof(string));
        //    }
        //    else
        //    {
        //        dt = Global.Dataset.Tables["FastDFS"];
        //    }
        //    DataRow dr = dt.NewRow();
        //    dr["ID"] = id;
        //    dr["Path"] = path;
        //    dt.Rows.Add(dr);
        //    dt.AcceptChanges();
        //    if (0 == Global.Dataset.Tables.Count)
        //    {
        //        Global.Dataset.Tables.Add(dt);
        //    }
        //    Global.Dataset.AcceptChanges();
        //}

        public static string GetPath(string id)
        {
            DataSet ds = new DataSet("FastDFSData");
            string physicsPath = HttpContext.Current.Server.MapPath(@"~/data/FastDFS.xml");
            ds.ReadXml(physicsPath);
            ds.AcceptChanges();

            DataTable dt =  ds.Tables["FastDFS"];
            DataRow[] dr = dt.Select("ID = '" + id.Replace("'","''") + "'");
            return 0 == dr.Length ? string.Empty : dr[0]["Path"].ToString();
        }
Esempio n. 23
0
	void MainForm_Load (object sender, EventArgs e)
	{
		_dataSet = new DataSet ();
		_dataSet.ReadXml ("test.xml");
		_dataGrid.DataSource = _dataSet;
		_dataGrid.DataMember = _dataSet.Tables [0].TableName;
		_dataSet.AcceptChanges ();

		InstructionsForm instructionsForm = new InstructionsForm ();
		instructionsForm.Show ();
	}
        public void Example()
        {
            #region Usage
            DataSet dataSet = new DataSet("dataSet");
            dataSet.Namespace = "NetFrameWork";
            DataTable table = new DataTable();
            DataColumn idColumn = new DataColumn("id", typeof(int));
            idColumn.AutoIncrement = true;

            DataColumn itemColumn = new DataColumn("item");
            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);
            dataSet.Tables.Add(table);

            for (int i = 0; i < 2; i++)
            {
                DataRow newRow = table.NewRow();
                newRow["item"] = "item " + i;
                table.Rows.Add(newRow);
            }

            dataSet.AcceptChanges();

            string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);

            Console.WriteLine(json);
            // {
            //   "Table1": [
            //     {
            //       "id": 0,
            //       "item": "item 0"
            //     },
            //     {
            //       "id": 1,
            //       "item": "item 1"
            //     }
            //   ]
            // }
            #endregion

            Assert.AreEqual(@"{
  ""Table1"": [
    {
      ""id"": 0,
      ""item"": ""item 0""
    },
    {
      ""id"": 1,
      ""item"": ""item 1""
    }
  ]
}", json);
        }
    public void SerializeAndDeserialize()
    {
      DataSet dataSet = new DataSet("dataSet");
      dataSet.Namespace = "NetFrameWork";
      DataTable table = new DataTable();
      DataColumn idColumn = new DataColumn("id", typeof(int));
      idColumn.AutoIncrement = true;

      DataColumn itemColumn = new DataColumn("item");
      table.Columns.Add(idColumn);
      table.Columns.Add(itemColumn);
      dataSet.Tables.Add(table);

      for (int i = 0; i < 2; i++)
      {
        DataRow newRow = table.NewRow();
        newRow["item"] = "item " + i;
        table.Rows.Add(newRow);
      }

      dataSet.AcceptChanges();

      string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
      
      Assert.AreEqual(@"{
  ""Table1"": [
    {
      ""id"": 0,
      ""item"": ""item 0""
    },
    {
      ""id"": 1,
      ""item"": ""item 1""
    }
  ]
}", json);

      DataSet deserializedDataSet = JsonConvert.DeserializeObject<DataSet>(json);
      Assert.IsNotNull(deserializedDataSet);

      Assert.AreEqual(1, deserializedDataSet.Tables.Count);

      DataTable dt = deserializedDataSet.Tables[0];

      Assert.AreEqual("Table1", dt.TableName);
      Assert.AreEqual(2, dt.Columns.Count);
      Assert.AreEqual("id", dt.Columns[0].ColumnName);
      Assert.AreEqual(typeof(long), dt.Columns[0].DataType);
      Assert.AreEqual("item", dt.Columns[1].ColumnName);
      Assert.AreEqual(typeof(string), dt.Columns[1].DataType);

      Assert.AreEqual(2, dt.Rows.Count);
    }
Esempio n. 26
0
        public static DataSet ConcatDataTables(DataTable p_dt, DataTable p_dt2)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(p_dt.Copy());

            foreach (DataRow dr in p_dt2.Rows)
            {
                ds.Tables[0].Rows.Add(dr.ItemArray);
            }
            ds.AcceptChanges();

            return ds;
        }
Esempio n. 27
0
        /// <summary>
        /// Updates the DataGridView (Users) with any new information in the DB, as
        /// the DataGridView does not do so automatically
        /// </summary>
        public void SetView () {

            System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("Data Source=" + DB_Connection + ";Version=3;");
            DataSet = new DataSet();
            SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter("SELECT * FROM Members", con);
            dataAdapter.AcceptChangesDuringFill = false;
            dataAdapter.Fill(DataSet);
            DataSet.AcceptChanges();

            Users.DataContext = DataSet.Tables[0].DefaultView;
            con.Close();
            GC.Collect();

        }
Esempio n. 28
0
        /// <summary>
        /// Returns dataset with configuration table.
        /// </summary>
        /// <returns>Dataset with configuration table.</returns>
        public static DataSet CreateDataSet()
        {
            DataSet dataSet = null;

            try
            {
                dataSet = new DataSet();

                dataSet.Locale = CultureInfo.InvariantCulture;
                dataSet.DataSetName = Resources.DatasetName;

                dataSet.Tables.Add(Resources.TableName);

                // Set dataset columns.
                dataSet.Tables[Resources.TableName].Columns.Add(Resources.ColumnAutoStartup,
                    typeof(Boolean));

                dataSet.Tables[Resources.TableName].Columns.Add(Resources.ColumnLogMessages,
                    typeof(Int32));

                dataSet.Tables[Resources.TableName].Columns.Add(Resources.ColumnProcessBatchSize,
                    typeof(Int32));

                dataSet.Tables[Resources.TableName].Columns.Add(Resources.ColumnRunQueuedProcesses,
                    typeof(Boolean));

                dataSet.Tables[Resources.TableName].Columns.Add(Resources.ColumnSynchronousExecution,
                    typeof(Boolean));

                // Set all values to NOT NULL.
                foreach (DataColumn dataColumn in dataSet.Tables[Resources.TableName].Columns)
                {
                    dataColumn.AllowDBNull = false;
                }

                // Accept changes.
                dataSet.AcceptChanges();

                return dataSet;
            }
            catch
            {
                if (dataSet != null)
                {
                    dataSet.Dispose();
                }

                throw;
            }
        }
Esempio n. 29
0
        private void btnAddManual_Click(object sender, EventArgs e)
        {
            if (!NP.ReqField(this.txtBatchNumber, "Please enter Batch Number !!")) { return; }
            if (!NP.ReqField(this.txtQuantity, "Please enter Quantity !!")) { return; }

            //for (int lm = 0; lm < this.dataGridView1.RowCount; lm++)
            //{
            //    if (this.dataGridView1["clnBatchNumber", lm].Value.ToString().Contains(this.txtBatchNumber.Text.Trim()))
            //    {
            //        LimitQty -= decimal.Parse(this.dataGridView1["clnQty", lm].Value.ToString());
            //    }
            //}

            //if (LimitQty < Convert.ToDecimal(txtQuantity.Text.Trim()))
            //{
            //    txtQuantity.Select();
            //    txtQuantity.SelectAll();
            //    NP.MSGB(NP_Cls.NPMgsStyle.WarningType, "Quantity Over Limit !!");
            //    return;
            //}

            if (this.dsOverview.Tables[0].Rows.Count == 0)
            {
                NP_Cls.SqlSelect = "SELECT BatchNumber, UR AS Qty, '" + NP_Cls.autoIDDO + "' as SOAutoID, '" + NP_Cls.SONumberForDO + "' AS SONumber FROM t_StockOverview WHERE (BatchNumber = N'" + this.txtBatchNumber.Text.Trim() + "')";
                dsOverview = NP.GetClientDataSet(NP_Cls.SqlSelect);
                dsOverview.Tables[0].Rows[0]["Qty"] = txtQuantity.Text.Trim();
                dsOverview.Tables[0].Rows[0]["SOAutoID"] = NP_Cls.autoIDDO;
                dsOverview.Tables[0].Rows[0]["SONumber"] = NP_Cls.SONumberForDO;
                dsOverview.Tables[0].Rows[0]["BatchNumber"] = this.txtBatchNumber.Text.Trim();

                dsOverview.AcceptChanges();
            }
            else
            {
                NP_Cls.SqlSelect = "SELECT BatchNumber, UR AS Qty, '" + NP_Cls.autoIDDO + "' as SOAutoID, '" + NP_Cls.SONumberForDO + "' AS SONumber FROM t_StockOverview WHERE (BatchNumber = N'" + this.txtBatchNumber.Text.Trim() + "')";
                DataSet ds2 = new DataSet(); ds2 = NP.GetClientDataSet(NP_Cls.SqlSelect);
                ds2.Tables[0].Rows[0]["Qty"] = txtQuantity.Text.Trim();
                ds2.Tables[0].Rows[0]["SOAutoID"] = NP_Cls.autoIDDO;
                ds2.Tables[0].Rows[0]["SONumber"] = NP_Cls.SONumberForDO;
                ds2.Tables[0].Rows[0]["BatchNumber"] = this.txtBatchNumber.Text.Trim();

                ds2.AcceptChanges();
                foreach (DataRow item in ds2.Tables[0].Rows)
                {
                    this.dsOverview.Tables[0].ImportRow(item);
                }
                dsOverview.AcceptChanges();
            }
            DGV();
        }
		public void SaveChanges(DataSet target, object tag = null)
		{
			try
			{
				string ReturnMessage = _wcfStandard.SetCommonDataSet(DataFilter.GetChangesAndRemoveBlobColums(target, tag == null));
				if (!string.IsNullOrEmpty(ReturnMessage))
				{
					throw new Exception("Save Changes " + ReturnMessage);
				}
			}
			finally
			{
				target.AcceptChanges();
			}
		}
Esempio n. 31
0
    public void Delete(string XMLfile, string OrderNumber)
    {
        DataSet dsResult = new DataSet();
        dsResult.ReadXml(XMLfile);
        DataRow[] dr = dsResult.Tables[0].Select("OrderNumber = '" + OrderNumber + "'");

        if (dr != null && dr.Length > 0)
        {
            //-- Remove the matched row from dataset
            dsResult.Tables[0].Rows.Remove(dr[0]);
        }
        //-- Accept the dataset changes
        dsResult.AcceptChanges();
        dsResult.WriteXml(XMLfile);
    }
Esempio n. 32
0
		[Test] public void AcceptChanges()
		{
			DataSet ds = new DataSet();
			DataTable dtP = DataProvider.CreateParentDataTable();
			DataTable dtC = DataProvider.CreateChildDataTable();
			ds.Tables.Add(dtP);
			ds.Tables.Add(dtC);
			ds.Relations.Add(new DataRelation("myRelation",dtP.Columns[0],dtC.Columns[0]));

			//create changes
			dtP.Rows[0][0] = "70";
			dtP.Rows[1].Delete();
			dtP.Rows.Add(new object[] {9,"string1","string2"});

			// AcceptChanges
			ds.AcceptChanges();
			Assert.AreEqual(null, dtP.GetChanges(), "DS1");

			//read only exception
			dtP.Columns[0].ReadOnly = true;
			// check ReadOnlyException
			try
			{
				dtP.Rows[0][0] = 99;
				Assert.Fail("DS2: Indexer Failed to throw ReadOnlyException");
			}
			catch (ReadOnlyException) {}
			catch (AssertionException exc) {throw  exc;}
			catch (Exception exc)
			{
				Assert.Fail("DS3: Indexer. Wrong exception type. Got:" + exc);
			}

			// check invoke AcceptChanges
			ds.AcceptChanges();
		}
Esempio n. 33
0
        public void TestMethod2()
        {
            var dataSet = new DataSet("dataSet");
            dataSet.Namespace = "NetFrameWork";
            var table = new DataTable();
            var idColumn = new DataColumn("id", typeof(int));
            idColumn.AutoIncrement = true;

            var itemColumn = new DataColumn("item");
            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);
            dataSet.Tables.Add(table);

            for (int i = 0; i < 2; i++)
            {
                var newRow = table.NewRow();
                newRow["item"] = "item " + i;
                table.Rows.Add(newRow);
            }

            var ctable = new DataTable();
            var cidColumn = new DataColumn("id", typeof(int));
            cidColumn.AutoIncrement = true;
            var cpidColumn = new DataColumn("pid", typeof(int));
            var citemColumn = new DataColumn("item");
            ctable.Columns.Add(cidColumn);
            ctable.Columns.Add(cpidColumn);
            ctable.Columns.Add(citemColumn);
            dataSet.Tables.Add(ctable);

            var relation = dataSet.Relations.Add(idColumn, cpidColumn);
            relation.Nested = true;

            for (int i = 0; i < 4; i++)
            {
                var newRow = ctable.NewRow();
                newRow["item"] = "item " + i;
                newRow["pid"] = i % 2;
                ctable.Rows.Add(newRow);
            }

            dataSet.AcceptChanges();

            var jsonResult = OrbCore.toJson(dataSet);

            // doesn't return the results nested together
            Console.WriteLine(jsonResult);
        }
 private static void SetFirstRowAsHeader(DataSet ds)
 {
     foreach (DataTable table in ds.Tables)
     {
         if (table.Rows.Count == 0) continue;
         foreach (DataColumn dc in table.Columns)
         {
             string colName = table.Rows[0][dc.Ordinal].ToString().Trim();
             if (!string.IsNullOrEmpty(colName) && !table.Columns.Contains(colName))
             {
                 table.Columns[dc.Ordinal].ColumnName = colName;
             }
         }
         table.Rows[0].Delete();
     }
     ds.AcceptChanges();
 }
Esempio n. 35
0
        public DataSet fnGetBenhNhanList(string _strConn)
        {
            var conn = new ConnectionDB(_strConn);
            try
            {
                conn.CallStoredProcedureFromDB("spGetBenhNhanList");
                conn.Reader = conn.Command.ExecuteReader();

                var myTable = new DataTable("GetBenhNhanListTable");
                myTable.Columns.Add("MaBenhNhan", typeof(string));
                myTable.Columns.Add("TenBenhNhan", typeof(string));
                myTable.Columns.Add("CMND", typeof(string));
                myTable.Columns.Add("NgaySinh", typeof(string));
                myTable.Columns.Add("DiaChi", typeof(string));
                myTable.Columns.Add("SDT", typeof(string));
                myTable.Columns.Add("MaPhongKham", typeof(string));

                while (conn.Reader.Read())
                {
                    myTable.Rows.Add(new[]
                                     {
                                         conn.Reader["MaBenhNhan"].ToString(),
                                         conn.Reader["TenBenhNhan"].ToString(),
                                         conn.Reader["CMND"].ToString(),
                                         conn.Reader["NgaySinh"].ToString(),
                                         conn.Reader["DiaChi"].ToString(),
                                         conn.Reader["SDT"].ToString(),
                                         conn.Reader["MaPhongKham"].ToString()
                                     });
                }
                myTable.AcceptChanges();
                var ds = new DataSet();
                ds.Tables.Add(myTable);
                ds.AcceptChanges();
                return ds;
            }
            catch
            {
                return null;
                throw;
            }
            finally
            {
                conn.Connection.Close();
            }
        }
Esempio n. 36
0
        private DataSet BuildInitialDataSet()
        {
            DataSet   initialDataSet = new DataSet();
            DataTable customerTable  = new DataTable("Customer");

            customerTable.Columns.Add(new DataColumn("Id")
            {
                AllowDBNull   = false,
                AutoIncrement = true,
                DataType      = typeof(int)
            });
            customerTable.Columns.Add("FirstName", typeof(string));
            customerTable.Columns.Add("LastName", typeof(string));
            AddCustomerData(customerTable);
            initialDataSet.Tables.Add(customerTable);
            initialDataSet.AcceptChanges();
            return(initialDataSet);
        }
Esempio n. 37
0
        private void BtnActualizar_Click(object sender, EventArgs e)
        {
            try
            {
                //creo commnad builder para generar automaticamente comandos de actualizacion
                System.Data.SqlClient.SqlCommandBuilder _comando = new System.Data.SqlClient.SqlCommandBuilder(_DAautor);

                //actualizar informacion
                _DAautor.Update(_DS.Tables["Autor"]);
                _DS.AcceptChanges();

                //si llego aca, todo ok
                LblError.Text = "Actualizacion Exitosa";
            }
            catch (Exception ex)
            {
                LblError.Text = ex.Message;
            }
        }
        public void MakeFirstTable(long TransCode)
        {
            DataTable table = new DataTable(tablename);

            table.Columns.Add("v1", typeof(int));
            table.Columns.Add("v2", typeof(long));
            table.Columns.Add("v3", typeof(DateTime));
            table.Columns.Add("v4", typeof(string));
            table.Columns.Add("v5", typeof(string));
            table.Columns.Add("v6", typeof(string));
            table.Columns.Add("v7", typeof(string));
            table.Columns.Add("v8", typeof(string));
            table.Columns.Add("v9", typeof(string));
            table.Columns.Add("v10", typeof(string));
            foreach (TransactionLines item in GetAll().Where(line => line.transCode == TransCode))
            {
                table.Rows.Add(item.LineCode, item.transCode, item.LineDate.Value, item.MainType, item.accCode,
                               item.DebitAmount, item.CreditAmount, item.Discription, item.offsetMainType, item.offsetAccCode);
            }
            DataSet = new System.Data.DataSet();
            DataSet.Tables.Add(table);
            DataSet.AcceptChanges();
        }
Esempio n. 39
0
        public int Update(System.Data.DataSet dataSet, string srcTable, bool inclHeader)
        {
            if (inclHeader)
            {
                m_hasheader = true;
            }

            if (dataSet.HasChanges())
            {
                DataTable table;

                try
                {
                    table = dataSet.Tables[srcTable];
                }
                catch
                {
                    //could not find the table specified
                    throw new ArgumentException("srcTable does not exist in specified dataSet");
                }
                //open filestream (overwrite previous file)
                m_writer = new StreamWriter(m_filename, false);

                if (m_hasheader)
                {
                    string columnrow = "";

                    //write header row
                    foreach (DataColumn dc in table.Columns)
                    {
                        //write column name
                        columnrow += dc.ColumnName + m_DelimiterString;
                    }

                    //write assembled column names minus the trailing comma
                    m_writer.WriteLine(columnrow.TrimEnd(m_DelimiterString.ToCharArray()));
                }

                //count the number of rows written
                int rowsaffected = 0;

                //write out all the rows (unless they were deleted)
                foreach (DataRow thisrow in table.Rows)
                {
                    //write all except deleted rows
                    if (thisrow.RowState != DataRowState.Deleted)
                    {
                        //write assembled row minus the trailing comma
                        m_writer.WriteLine(BuildRow(thisrow.ItemArray, m_DelimiterString, m_RemoveDelimiterString));
                        rowsaffected++;
                    }
                }

                //close filestream
                m_writer.Close();

                //mark dataset as up-to-date
                try
                {
                    dataSet.AcceptChanges();
                }
                catch
                {
                }
                //return number of rows written
                return(rowsaffected);
            }
            else
            {
                //no changes - ignore
                return(0);
            }
        }
Esempio n. 40
0
        ///<summary>
        /// using the DataSet and DataTable names.
        ///</summary>
        ///<param name=”dataSet”>A DataSet to fill with records and, if necessary, schema.</param>
        ///<param name=”tableName”>The name of the source table to use for table mapping.</param>
        ///<returns>The number of rows successfully added to or refreshed in the DataSet.
        ///This does not include rows affected by statements that do not return rows.</returns>
        public int Fill(System.Data.DataSet dataSet, string tableName)
        {
            //table within the dataset
            DataTable dt = dataSet.Tables.Add(tableName);
            //store records affected
            int records = 0;
            //raw row
            string rawrow;

            //store the current row
            string[] rowbuffer = new string[0];
            //more records
            bool morerecords = true;

            //open stream to read from file
            m_reader = new StreamReader(m_filename);

            if (m_hasheader)
            {
                //read header row and construct schema
                m_headers = SplitRow(m_reader.ReadLine(), m_DelimiterString);

                foreach (string column in m_headers)
                {
                    //add to columns collection
                    DataColumn dc = dt.Columns.Add(column);
                    dc.DataType    = typeof(string);
                    dc.AllowDBNull = true;
                }

                //read first data row
                rawrow = m_reader.ReadLine();

                //check for null first - avoid throwing exception
                if (rawrow == null | rawrow == String.Empty)
                {
                    morerecords = false;
                }
                else
                {
                    rowbuffer = SplitRow(rawrow, m_DelimiterString);
                }
            }
            else
            {
                //read line
                rawrow = m_reader.ReadLine();

                if (rawrow == null | rawrow == String.Empty)
                {
                    morerecords = false;
                }
                else
                {
                    //read the first row and get the length
                    rowbuffer = SplitRow(rawrow, m_DelimiterString);
                }

                for (int iColumn = 0; iColumn < rowbuffer.Length; iColumn++)
                {
                    //add to columns collection
                    DataColumn dc = dt.Columns.Add("Column" + iColumn.ToString());
                    dc.DataType    = typeof(string);
                    dc.AllowDBNull = true;
                }
            }

            //processing of further rows goes here
            while (morerecords)
            {
                //increment rows affected
                records++;
                //add values to row and insert into table
                dt.Rows.Add(rowbuffer);

                //read the next row
                rawrow = m_reader.ReadLine();

                if (rawrow == null | rawrow == String.Empty)
                {
                    morerecords = false;
                }
                else
                {
                    //read the first row and get the length
                    rowbuffer = SplitRow(rawrow, m_DelimiterString);
                }
            }

            //close stream
            m_reader.Close();

            //mark dataset as up-to-date
            dataSet.AcceptChanges();

            return(records);
        }
Esempio n. 41
0
        /// <summary>
        ///  using the DataSet and DataTable names.
        /// </summary>
        /// <param name="dataSet">A DataSet to fill with records and, if necessary, schema.</param>
        /// <param name="tableName">The name of the source table to use for table mapping.</param>
        /// <returns>The number of rows successfully added to or refreshed in the DataSet. This does not include rows affected by statements that do not return rows.</returns>
        public int Fill(System.Data.DataSet dataSet, string tableName)
        {
            //table within the dataset
            DataTable dt;

            if (dataSet.Tables.Contains(tableName))
            {
                dt = dataSet.Tables[tableName];
            }
            else
            {
                dt = dataSet.Tables.Add(tableName);
            }

            //store records affected
            int records = 0;

            //raw row
            string rawrow;

            //store the current row
            string[] rowbuffer = new string[0];

            //more records
            bool morerecords = true;

            //open stream to read from file
            m_reader = new StreamReader(m_filename);

            if (m_hasheader)
            {
                rawrow = m_reader.ReadLine();
                if (rawrow == null)
                {
                    // no data
                    return(0);
                }

                //read header row and construct schema
                m_headers = SplitRow(rawrow);

                foreach (string column in m_headers)
                {
                    string columnName = column;
                    //add to columns collection
                    if (dt.Columns.Contains(columnName))
                    {
                        int index = 1;
                        do
                        {
                            columnName = column + index.ToString();
                            index++;
                        } while (dt.Columns.Contains(columnName));
                    }
                    DataColumn dc = dt.Columns.Add(columnName);
                    dc.DataType    = typeof(string);
                    dc.AllowDBNull = true;
                }

                //read first data row
                //Updated (Bug# 000091) Failure if only header row present
                rawrow = m_reader.ReadLine();

                //check for null first - avoid throwing exception
                if (rawrow == null | rawrow == String.Empty)
                {
                    morerecords = false;
                }
                else
                {
                    rowbuffer = SplitRow(rawrow);
                }
            }
            else
            {
                //read line
                rawrow = m_reader.ReadLine();

                if (rawrow == null | rawrow == String.Empty)
                {
                    morerecords = false;
                }
                else
                {
                    //read the first row and get the length
                    rowbuffer = SplitRow(rawrow);
                }


                for (int iColumn = 0; iColumn < rowbuffer.Length; iColumn++)
                {
                    //add to columns collection
                    DataColumn dc = dt.Columns.Add("Column " + iColumn.ToString());
                    dc.DataType    = typeof(string);
                    dc.AllowDBNull = true;
                }
            }

            //processing of further rows goes here
            int  newColNum = 0;
            bool addRow    = true;

            while (morerecords)
            {
                //increment rows affected
                if (addRow)
                {
                    records++;
                }
                addRow = true;

                if (rowbuffer.Length != dt.Columns.Count)
                {
                    // support adding new columns at the very end
                    if ((HasHeaderRow) && (string.Compare(rowbuffer[0], dt.Columns[0].ColumnName) == 0))
                    {
                        addRow    = false;
                        newColNum = dt.Columns.Count;
                        while (rowbuffer.Length > dt.Columns.Count)
                        {
                            dt.Columns.Add(rowbuffer[newColNum++]);
                        }
                    }
                    else
                    {
                        // if the column count expanded mid-data, account for it
                        while (rowbuffer.Length > dt.Columns.Count)
                        {
                            dt.Columns.Add(string.Format("New column {0}", ++newColNum));
                        }
                    }
                }
                //add values to row and insert into table
                if (addRow)
                {
                    dt.Rows.Add(rowbuffer);
                }

                //read the next row
                rawrow = m_reader.ReadLine();

                if (rawrow == null | rawrow == String.Empty)
                {
                    morerecords = false;
                }
                else
                {
                    //read the first row and get the length
                    rowbuffer = SplitRow(rawrow);
                }
            }

            //close stream
            m_reader.Close();

            //mark dataset as up-to-date
            dataSet.AcceptChanges();

            return(records);
        }
Esempio n. 42
0
        private void _Toolbar1_Guardar_Click(System.Object sender, System.EventArgs e)
        {
            OleDbDataAdapter dbClientes = new OleDbDataAdapter();

            System.Data.DataSet dbRegistros = null;
            System.Data.DataRow fila        = null;

            string NombreTabla = "tblFactura";



            //Antes de cargar nada fijamos si puede guardarlo en la AFIP sino no sigue con el guardado de la factura
            //ESP La funcion EnviarFacturaAFIP esta en el modulo de AFIP.
            bool bolFactEnAFIP = AFIP.EnviarFacturaAFIP(Imprimir.CargarFactura(gridDatos.Rows.Count - 1), lblToken.Text, lblSign.Text);

            if (bolFactEnAFIP != true)
            {
                Interaction.MsgBox("NO se pudo cargar la factura en AFIP. Intentelo nuevamente", MsgBoxStyle.Information);
                return;
            }



            //Cargo la tabla en la base
            //Facturas A
            if (lblCod_cbe.Text == "01")
            {
                dbClientes = BaseDeDatos.rstTabla("Facturas", "Fecha", "");
                //Facturas B
            }
            else if (lblCod_cbe.Text == "06")
            {
                dbClientes = BaseDeDatos.rstTabla("FacturasB", "Fecha", "");
                //Notas de Credito
            }
            else if (lblCod_cbe.Text == "03")
            {
                dbClientes = BaseDeDatos.rstTabla("NotaCredito", "Fecha", "");
                //Notas de Debito
            }
            else if (lblCod_cbe.Text == "02")
            {
                dbClientes = BaseDeDatos.rstTabla("NotaDebito", "Fecha", "");
            }


            //Asigno un nuevo Data Set
            dbRegistros = new System.Data.DataSet();

            try {
                dbClientes.Fill(dbRegistros, NombreTabla);
            } catch (Exception ex) {
                MessageBox.Show("Error en el llenado:" + Constants.vbCrLf + ex.Message);
            }



            OleDbCommandBuilder cb = new OleDbCommandBuilder(dbClientes);



            miFactura = Imprimir.CargarFactura(gridDatos.Rows.Count - 1);



            fila = dbRegistros.Tables[NombreTabla].NewRow();
            fila.BeginEdit();


            //Cargo el valor del "DOCUMENTO"
            //Facturas A
            if (lblCod_cbe.Text == "01")
            {
                fila["Documento"] = "FC A " + Strings.Format(miFactura.intSucursal, "0000") + "-" + Strings.Format(miFactura.dblNumFact, "00000000");
                //Facturas B
            }
            else if (lblCod_cbe.Text == "06")
            {
                fila["Documento"] = "FC B " + Strings.Format(miFactura.intSucursal, "0000") + "-" + Strings.Format(miFactura.dblNumFact, "00000000");
                //Notas de Credito
            }
            else if (lblCod_cbe.Text == "03")
            {
                fila["Documento"] = "NC " + Strings.Format(miFactura.intSucursal, "0000") + "-" + Strings.Format(miFactura.dblNumFact, "00000000");
                //Notas de Debito
            }
            else if (lblCod_cbe.Text == "02")
            {
                fila["Documento"] = "ND " + Strings.Format(miFactura.intSucursal, "0000") + "-" + Strings.Format(miFactura.dblNumFact, "00000000");
            }

            fila["Sucursal"] = miFactura.intSucursal;
            fila["NumFact"]  = miFactura.dblNumFact;
            fila["Fecha"]    = miFactura.dtFecha;
            //
            fila["IDCliente"]    = miFactura.Cliente.strid;
            fila["Nombre"]       = miFactura.Cliente.strNombre;
            fila["Direccion"]    = miFactura.Cliente.strDireccion;
            fila["Localidad"]    = miFactura.Cliente.strLocalidad;
            fila["Provincia"]    = miFactura.Cliente.strProvincia;
            fila["Tipodecambio"] = miFactura.dblTipoCambio;
            fila["Descuento"]    = Conversion.Str(miFactura.Cliente.dblDescuento);

            fila["Cant1"]           = miFactura.Producto1.intCantidad;
            fila["Detalle1"]        = miFactura.Producto1.strDescripcion;
            fila["PrecioUnitario1"] = miFactura.Producto1.curPrecioNeto;
            fila["PrecioFinal1"]    = miFactura.Producto1.curPrecioTotal;

            fila["Cant2"]           = miFactura.Producto2.intCantidad;
            fila["Detalle2"]        = miFactura.Producto2.strDescripcion;
            fila["PrecioUnitario2"] = miFactura.Producto2.curPrecioNeto;
            fila["PrecioFinal2"]    = miFactura.Producto2.curPrecioTotal;

            fila["Cant3"]           = miFactura.Producto3.intCantidad;
            fila["Detalle3"]        = miFactura.Producto3.strDescripcion;
            fila["PrecioUnitario3"] = miFactura.Producto3.curPrecioNeto;
            fila["PrecioFinal3"]    = miFactura.Producto3.curPrecioTotal;

            fila["Cant4"]           = miFactura.Producto4.intCantidad;
            fila["Detalle4"]        = miFactura.Producto4.strDescripcion;
            fila["PrecioUnitario4"] = miFactura.Producto4.curPrecioNeto;
            fila["PrecioFinal4"]    = miFactura.Producto4.curPrecioTotal;

            fila["Cant5"] = miFactura.Producto5.intCantidad;
            //Cantidad 5
            fila["Detalle5"] = miFactura.Producto5.strDescripcion;
            //Detalle5
            fila["PrecioUnitario5"] = miFactura.Producto5.curPrecioNeto;
            //Precio Unitario 5
            fila["PrecioFinal5"] = miFactura.Producto5.curPrecioTotal;
            //Precio Final 5

            fila["Cant6"] = 0;
            //Cantidad 6
            fila["Detalle6"] = " ";
            //Detalle6
            fila["PrecioUnitario6"] = 0;
            //Precio Unitario 6
            fila["PrecioFinal6"] = 0;
            //Precio Final 6

            fila["SubTotal"] = miFactura.curSubTotal;
            //Sub Total $
            fila["IVA"] = miFactura.curIVA;
            //IVA $
            fila["ImporteFinal"] = miFactura.curTotal;
            //Importe Final $

            fila["Recibo1"] = 0;
            fila["Recibo2"] = 0;
            //Recibo2
            fila["Recibo3"] = 0;
            //Recibo3
            fila["Recibo4"] = 0;
            //Recibo4
            fila["Recibo5"] = 0;
            //Recibo5

            fila["ClienteDe"] = " ";
            //Cliente De

            fila["Remito1"] = miFactura.intRemito1;
            //
            fila["Remito2"] = miFactura.intRemito2;
            //Remito2
            fila["Remito3"] = miFactura.intRemito3;
            //Remito3
            fila["Remito4"] = miFactura.intRemito4;
            //Remito4
            fila["Remito5"] = 0;
            //Remito5

            fila["Observaciones"] = " ";
            //Observaciones

            fila["SubTotalUSS"] = miFactura.curSubTotalUSD;
            //Sub Total USS
            fila["IVAUSS"] = miFactura.curIVAUSD;
            //IVA USS
            fila["ImporteFinalUSS"] = miFactura.curTotalUSD;
            //Importe Final USS

            fila["EnDolar"] = 0.0;
            //En Dolar

            fila["Saldo"] = Strings.Replace(Conversion.Str(miFactura.curTotal), ".", ",");
            //Saldo
            fila["SaldoUSS"] = miFactura.curTotalUSD;
            //SaldoUSS

            fila["Pagado"] = false;

            fila["Dólar"] = true;
            fila["Peso"]  = false;


            fila["Promocion"] = 0;

            fila["CAE"]          = miFactura.strCAE;
            fila["FechaVencCAE"] = miFactura.strFechVtoCAE;


            //Finaliza la edicion
            fila.EndEdit();

            //Añade la fila a la tabla
            dbRegistros.Tables[NombreTabla].Rows.Add(fila);



            //Actualiza la base de datos
            dbClientes.Update(dbRegistros, NombreTabla);


            //acepta los cambios
            dbRegistros.AcceptChanges();



            //MsgBox(miFactura.strTipoFc)
            //MsgBox(miFactura.intSucursal)
            //MsgBox(miFactura.dtFecha)
            Interaction.MsgBox("Factura Cargada");

            //Este modulo edita la tabla de remitos y asigna el valor de la factura y su respectiva
            //sucursal al remito en cuestion
            //eso lo saca de los desplegables de remitos
            ModDocFiscales.EditarRemitos((cmbSucursal.Text), Convert.ToDouble(txtNumFact.Text), Convert.ToDouble(cmbRemito1.Text));
            Interaction.MsgBox("Remito: " + cmbRemito1.Text + ". Modificado");


            //Esto permite que se pueda imprimir
            _Toolbar1_Imprimir.Enabled = true;

            //Esto impide que se vuelva a guardar
            _Toolbar1_Guardar.Enabled = false;
        }
Esempio n. 43
-1
        public void CountDeceasedNameRepeatency()
        {
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("jawiname.xml");
            DataTable original = dataSet.Tables[0];


            DataTable result = new DataTable("jawiname");
            Dictionary<string, character> characters = new Dictionary<string, character>();
            //mount to a relative path
            DirectoryInfo directoryInfo = new DirectoryInfo("..\\..\\..\\..\\..\\JawiName");
            FileInfo[] filesInfo = directoryInfo.GetFiles();
            foreach (FileInfo info in filesInfo)
            {
                string[] rootNames = info.FullName.ToLower()
                    .TrimEnd(new char[] { 's', 'f', '.' })
                    .Split(new char[] { ' ' });
                foreach (string s in rootNames)
                {
                    if (!characters.ContainsKey(s))
                        characters.Add(s, new character(s, GetArabicString(original, s)));
                    else
                        characters[s].counter += 1;
                }
            }

            dataSet.Tables.Add(result);
            dataSet.AcceptChanges();
            dataSet.WriteXml("result.xml");
        }