public static int SaveRecord(string sql)
        {
            const int rv = 0;
            try
            {
                string connectionString = ConfigurationManager.ConnectionStrings["LA3Access"].ConnectionString;
                using (var conn = new OleDbConnection(connectionString))
                {
                    conn.Open();
                    var cmGetID = new OleDbCommand("SELECT @@IDENTITY", conn);
                    var comm = new OleDbCommand(sql, conn) { CommandType = CommandType.Text };
                    comm.ExecuteNonQuery();

                    var ds = new DataSet();
                    var adapt = new OleDbDataAdapter(cmGetID);
                    adapt.Fill(ds);
                    adapt.Dispose();
                    cmGetID.Dispose();

                    return int.Parse(ds.Tables[0].Rows[0][0].ToString());

                }
            }
            catch (Exception)
            {
            }
            return rv;
        }
 protected void LinkButton5_Click(object sender, EventArgs e)
 {
     OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(@"App_Data\db.mdb")+";Persist Security Info=True");
     OleDbCommand cmd = new OleDbCommand("insert into siparis (UYEID,ADRES,TEL,DURUMU) values (@UYEID,@ADRES,@TEL,@DURUMU)",baglanti);
     cmd.Parameters.AddWithValue("@UYEID",((DataTable)(Session["UYE"])).Rows[0][0].ToString());
      cmd.Parameters.AddWithValue("@ADRES",TextBox1.Text);
      cmd.Parameters.AddWithValue("@TEL",TextBox2.Text);
      cmd.Parameters.AddWithValue("@DURUMU","Beklemede");
      baglanti.Open();
      cmd.ExecuteNonQuery();
      baglanti.Close();
      OleDbDataAdapter da = new OleDbDataAdapter("select ID from siparis where [email protected] order by ID DESC",baglanti);
      da.SelectCommand.Parameters.AddWithValue("@UYEID",((DataTable)(Session["UYE"])).Rows[0][0].ToString());
      DataTable dt = new DataTable();
      da.Fill(dt);
     DataTable sdt=((DataTable)(Session["SEPET"]));
     for (int i = 0; i < sdt.Rows.Count; i++)
         {
             OleDbCommand scmd = new OleDbCommand("insert into sepet (SIPID,URUNID,URUN,FIYAT,ADET,TOPLAM) VALUES (@SIPID,@URUNID,@URUN,@FIYAT,@ADET,@TOPLAM)",baglanti);
             scmd.Parameters.Clear();
             scmd.Parameters.AddWithValue("@SIPID",dt.Rows[0][0].ToString());
         scmd.Parameters.AddWithValue("@URUNID",sdt.Rows[i]["ID"].ToString());
         scmd.Parameters.AddWithValue("@URUN",sdt.Rows[i]["URUN"].ToString());
         scmd.Parameters.AddWithValue("@FIYAT",sdt.Rows[i]["FIYAT"].ToString());
         scmd.Parameters.AddWithValue("@ADET",sdt.Rows[i]["ADET"].ToString());
         scmd.Parameters.AddWithValue("@TOPLAM", sdt.Rows[i]["TOPLAM"].ToString());
         baglanti.Open();
         scmd.ExecuteNonQuery();
         baglanti.Close();
         }
     Label2.Text = "Sipariş Takip Numarasınız : "+dt.Rows[0][0].ToString();
 }
Example #3
0
    protected void onClick_login(object sender, EventArgs e)
    {
        connection = new OleDbConnection(path);
        connection.Open();

        cmd = new OleDbCommand("SELECT COUNT(*) FROM tblProfiles WHERE user_name = '" + inputUsername.Text + "';", connection);
        cmd.ExecuteNonQuery();

        int compareUsername = Convert.ToInt32(cmd.ExecuteScalar().ToString());

        connection.Close();

        if (compareUsername == 1)
        {
            connection.Open();

            cmd = new OleDbCommand("SELECT user_password FROM tblProfiles WHERE user_name = '" + inputUsername.Text + "';", connection);
            cmd.ExecuteNonQuery();

            string comparePassword = cmd.ExecuteScalar().ToString();

            connection.Close();

            if (comparePassword == inputPassword.Text)
            {
                Session["username"] = inputUsername.Text;
                Server.Transfer("main.aspx");
            }
            else
                errorPassword.Visible = true;
        }
        else
            errorUsername.Visible = true;
    }
Example #4
0
        //Create an Excel file with 2 columns: name and score:
        //Write a program that reads your MS Excel file through
        //the OLE DB data provider and displays the name and score row by row.

        static void Main()
        {
            OleDbConnection dbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" +
            @"Data Source=D:\Telerik\DataBases\HW\ADONET\06. ReadExcel\Table.xlsx;Extended Properties=""Excel 12.0 XML;HDR=Yes""");
            OleDbCommand myCommand = new OleDbCommand("select * from [Sheet1$]", dbConn);
            dbConn.Open();
            //First way
            //using (dbConn) - I think it is better to use dbConn in using clause, but for the demo issues i dont use using.
            //{
            OleDbDataReader reader = myCommand.ExecuteReader();

            while (reader.Read())
            {
                string name = (string)reader["Name"];
                double score = (double)reader["Score"];
                Console.WriteLine("{0} - score: {1}", name, score);
            }
            //}

            dbConn.Close();
            //Second way
            dbConn.Open();
            Console.WriteLine();
            Console.WriteLine("Second Way");
            Console.WriteLine("----------");
            DataTable dataSet = new DataTable();
            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [Sheet1$]", dbConn);
            adapter.Fill(dataSet);

            foreach (DataRow item in dataSet.Rows)
            {
                Console.WriteLine("{0}|{1}", item.ItemArray[0], item.ItemArray[1]);
            }
            dbConn.Close();
        }
Example #5
0
        private void AddUser_Click(object sender, EventArgs e)
        {
            comboBox1.SelectedItem = "caissier";
            string newuser = textBox1.Text;
            string newmdp = textBox2.Text;
            string test = "select username from Users where username='" + textBox1.Text + "'";
            OleDbConnection userhandlingconn = new OleDbConnection(connexionstring);
            OleDbCommand cmduserhandling = new OleDbCommand();

            try
            {

                if (textBox1.Text.Length ==0 || textBox2.Text.Length ==0|| comboBox1.SelectedItem.ToString().Length ==0)
                {
                    MessageBox.Show("Un ou plusieur champs sont vides !!!");
                }

                else
                {
                    try
                    {
                        cmduserhandling = new OleDbCommand(test, userhandlingconn);
                        userhandlingconn.Open();
                        string verif = cmduserhandling.ExecuteScalar().ToString();
                        userhandlingconn.Close();
                        if (verif.Length > 0)
                        {
                            MessageBox.Show("Cet utilisateur existe deja dans la base de données");
                        }

                    }
                    catch (NullReferenceException)
                    {
                        userhandlingconn.Close();
                        string adduser = "INSERT INTO Users ( username, [password], last_connexion, type_user ) values ('" + newuser + "','" + newmdp + "',Date(),'" + comboBox1.SelectedItem.ToString() + "');";
                        userhandlingconn.Open();
                        cmduserhandling = new OleDbCommand(adduser, userhandlingconn);
                        cmduserhandling.ExecuteNonQuery();
                        MessageBox.Show("Ajout effectué");
                        userhandlingconn.Close();
                    }

                }
            }
            catch(Exception ex)
            {
                //MessageBox.Show("Erreur !!!");
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                textBox1.Text = "";
                textBox2.Text = "";
                comboBox1.SelectedItem = "";
                DataReload();
            }
        }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        OleDbConnectionStringBuilder sb = new OleDbConnectionStringBuilder();
        sb.Provider = "Microsoft.ACE.OLEDB.12.0";
        sb.DataSource = Server.MapPath("/vedb01/uploads/db1.accdb");
        OleDbConnection conn = new OleDbConnection(sb.ConnectionString);
        conn.Open();
        string checkUser = "select count(*) from UserData where UserName='" + txtUserName.Text + "'";
        
        OleDbCommand com = new OleDbCommand(checkUser, conn);
        
        
        int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
        conn.Close();
        if (temp == 1)
        {
            conn.Open();
            string checkPassword = "select password from UserData where UserName='" + txtUserName.Text + "'";
            
            OleDbCommand passcom = new OleDbCommand(checkPassword, conn);
            
            string password = passcom.ExecuteScalar().ToString().Replace(" ", "");


            string checkAdmin = "select usergroup from UserData where UserName='" + txtUserName.Text + "'";
            OleDbCommand usercon = new OleDbCommand(checkAdmin, conn);
            int veriAdmin =Convert.ToInt32( usercon.ExecuteScalar().ToString());

           // conn.Close();
            if (password == txtPass.Text && veriAdmin == 1)
            {
                
                
                //if (veriAdmin == "admin")
                //{
                    Session["UserName"] = txtUserName.Text;
                    Response.Write("Login Successful! Welcome " + Session["UserName"] + "!");
              
                    
                    
                  //  Response.Redirect("~/Admin/Intro.aspx");
                    Response.AppendHeader("Refresh", "3;url=Intro.aspx");
            }
            else
            {
                Response.Write("Password is incorrect");
            }
        }
        else
        {
            Response.Write("User Name is incorrect");
        }


    }
Example #7
0
        // Completely Remove an Area from the database.
        public static void DeleteArea(int iAreaID)
        {
            // Configure database connection elements.
            OleDbDataAdapter da = new OleDbDataAdapter();

            OleDbConnection connection = new OleDbConnection();
            connection.ConnectionString = database.getConnectionString();

            // Delete All Rooms in the Area.
            try
            {
                connection.Open();

                // Create query.
                string strSQL = string.Empty;
                strSQL += " delete ";
                strSQL += " from   [Room] ";
                strSQL += " where  [RoomAreaID] = " + iAreaID.ToString() + " ";

                da.InsertCommand = new OleDbCommand(strSQL);
                da.InsertCommand.Connection = connection;

                da.InsertCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                string strError = ex.Message;
            }
            connection.Close();

            // Delete the Area.
            try
            {
                connection.Open();

                // Create query.
                string strSQL = string.Empty;
                strSQL += " delete ";
                strSQL += " from   [Area] ";
                strSQL += " where  [AreaID] = " + iAreaID.ToString() + " ";

                da.InsertCommand = new OleDbCommand(strSQL);
                da.InsertCommand.Connection = connection;

                da.InsertCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                string strError = ex.Message;
            }

            connection.Close();
            connection.Dispose();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            
            string chaine = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/dhib/Desktop/Professeur.accdb";
            OleDbConnection con = new OleDbConnection(chaine);
            OleDbCommand cmd = con.CreateCommand();
            OleDbCommand cmd1 = con.CreateCommand();

            cmd.CommandText = "Insert into etudiant values (" + Convert.ToInt32(txt_cin.Text) + ",'" + txt_nom.Text + "','" + txt_prenom.Text + "','" + comboBox1.Text + "')";
            

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Ajout Module Réussi");
                con.Close();

                new acceuil(login).Show();
                this.Hide();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Erreur" + ex.Message);
                con.Close();
            }



            //ckecked lisT 
             foreach(object itemChecked in checkedListBox1.CheckedItems) {
                 cmd1.CommandText = "Insert into assiste(cin,id_module,date_present) values(" + Convert.ToInt32(txt_cin.Text) + "," + hash[(string)itemChecked] + ",'" + DateTime.Now.ToString("dd-MM-yyyy") + "')";
                 try
                 {
                     con.Open();
                     cmd1.ExecuteNonQuery();
                     con.Close();


                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("Erreur" + ex.Message);
                     con.Close();
                 }
             }





        }
    protected void LoadData()
    {
        string strsql = "select * from customers where custnumber = " + Session["custid"];
        OleDbConnection myConn = new OleDbConnection();
        myConn.ConnectionString = System.Web.Configuration.WebConfigurationManager.
        ConnectionStrings["AcmeShoppeConnectionString"].ConnectionString;
        OleDbCommand myCmd = new OleDbCommand(strsql, myConn);
        OleDbDataReader myReader;
        if (myConn.State == ConnectionState.Closed) myConn.Open();
            myReader = myCmd.ExecuteReader();

            if (myReader.HasRows)
            {
                myReader.Read();
                this.lblFName.Text = myReader["FirstName"].ToString();
                this.lblLName.Text = myReader["LastName"].ToString();
                this.txtAddress.Text = myReader["Address"].ToString();
                this.txtCity.Text = myReader["City"].ToString();
                this.txtZip.Text = myReader["ZipCode"].ToString();
                this.DropDownList1.SelectedValue = myReader["State"].ToString();
            }
            else
                this.lblerr.Text = "error";
         myReader.Close();
         myCmd.CommandText = "select sum(extension) from cart_view01 " +
                                    "where cartnumber = " + Session["cartnumber"];
         decimal decSubtotal = 0;
         double decSalesTax = 0;
         double decTotal = 0;
         double decShip = 3.25;
         if (myConn.State == ConnectionState.Closed) myConn.Open();
         myReader = myCmd.ExecuteReader();
         if (myReader.HasRows)
         {
             myReader.Read();
             if (myReader[0] != DBNull.Value)
             {
                 decSubtotal = Convert.ToDecimal(myReader[0].ToString());
                 this.lblSubtotal.Text = decSubtotal.ToString("c");
             }
             decSalesTax = Convert.ToDouble(decSubtotal) * .05;
             Math.Round(decSalesTax, 2);
             decTotal = Convert.ToDouble(decSubtotal) + decSalesTax + decShip;
             Math.Round(decTotal, 2);
             this.lblTax.Text = decSalesTax.ToString("c");
             this.lblTotal.Text = decTotal.ToString("c");
             this.lblShipping.Text = decShip.ToString("c");
         }
         else
             this.lblerr.Text = "error";
         myConn.Close();
    }
Example #10
0
        public static System.Data.DataSet Excel2Dataset(string fileName, string tableName)
        {
            bool isOpen = true;
            try
            {
                return DataSet2CSV.ConverCSV2DataSet(fileName, tableName);
            }
            catch (System.Exception) { }

            OleDbConnection connStr = new OleDbConnection();
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
            connStr.ConnectionString = strConn;
            try
            {
                connStr.Open();
            }
            catch (System.Exception)
            {
                isOpen = false;
            }

            if (!isOpen)
            {
                isOpen = true;
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
                connStr.ConnectionString = strConn;
                try
                {
                    connStr.Open();
                }
                catch (System.Exception)
                {
                    isOpen = false;
                }
            }

            if (!isOpen)
                return null;

            //动态表名
            DataTable tblSchema = connStr.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            string sheetName = tblSchema.Rows[0]["TABLE_NAME"].ToString();
            OleDbDataAdapter cmd = new OleDbDataAdapter("select * from [" + sheetName + "]", connStr);

            DataSet ds = new DataSet();
            cmd.Fill(ds, tableName);

            connStr.Close();
            connStr = null;
            return ds;
        }
Example #11
0
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (MainMenu.SelectedValue.ToString() == "")
        {
            LblError.Text = "من فضلك قم بأختيار خيار من القائمه";
            LblError.ForeColor = System.Drawing.Color.Red;
            LblError.Visible = true;
        }
        string Path = string.Empty;
        OleDbConnection Con = new OleDbConnection(constr);
        OleDbCommand CMD = new OleDbCommand("SELECT Data_Path FROM MenuItem Where ItemID = " + MainMenu.SelectedValue.ToString(), Con);
        try
        {
            Con.Open();
            Path = CMD.ExecuteScalar().ToString();

        }
        catch { }
        Con.Close();
        if (Path == string.Empty)
        {
            //Path = MapPath("~/QAData/QAData" + QAMainMenu.SelectedValue.ToString() + ".QA");
            Path = String.Format("../ItemData/Data{0}{1}{2}{3}.Dat", MainMenu.SelectedValue, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
        }
        try
        {
            CMD.CommandText = String.Format("Update MenuItem Set Data_Path = '{0}' Where ItemID = {1}", Path, MainMenu.SelectedValue);
            Con.Open();
            CMD.ExecuteNonQuery();
            Path = MapPath(Path);
            //if (File.Exists(Path))
            //{
            //    File.Delete(Path);
            //}
            File.Create(Path).Close();
            TextWriter TW = new StreamWriter(Path, false);
            TW.Write(Request.Form["editor1"]);
            TW.Flush();
            TW.Close();
            LblError.Text = "تم الحفــــظ";
            LblError.ForeColor = System.Drawing.Color.Green;
            LblError.Visible = true;
        }
        catch (Exception ex)
        {
            LblError.Text = ex.Message.ToString();
            LblError.ForeColor = System.Drawing.Color.Red;
            LblError.Visible = true;
        }
        Con.Close();
    }
Example #12
0
    public int GetExcelDistictBTNCOunt_Sales(string sFileName)
    {
        Int32 NORec;
        DataSet objDataset1 = new DataSet();
        int count = 0;
        OleDbConnection objConn = new OleDbConnection();
        try
        {
             string FileExt = System.IO.Path.GetExtension(sFileName);
             if (FileExt == ".xls")
             {
                 //Excell connection
                 string Xls_Con = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sFileName + ";Extended Properties=\"Excel 8.0;HDR=YES; IMEX=1;ImportMixedTypes=Text\"";
                 objConn.ConnectionString = Xls_Con;
                 //Dim objConn As New OleDbConnection(Xls_Con)
                 objConn.Open();
                 DataTable ExcelSheets = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                 string SpreadSheetName = "[" + ExcelSheets.Rows[0]["TABLE_NAME"].ToString() + "]";

                 OleDbDataAdapter objAdapter1 = new OleDbDataAdapter("SELECT distinct(Phoneno) FROM " + SpreadSheetName, objConn);
                 objAdapter1.Fill(objDataset1, "XLData");

                 count = Convert.ToInt32(objDataset1.Tables[0].Rows.Count);
             }
             else if (FileExt == ".xlsx")
             {
                 //Excell connection
                 string Xls_Con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                 objConn.ConnectionString = Xls_Con;
                 //Dim objConn As New OleDbConnection(Xls_Con)
                 objConn.Open();
                 DataTable ExcelSheets = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                 string SpreadSheetName = "[" + ExcelSheets.Rows[0]["TABLE_NAME"].ToString() + "]";

                 OleDbDataAdapter objAdapter1 = new OleDbDataAdapter("SELECT distinct(Phoneno) FROM " + SpreadSheetName, objConn);
                 objAdapter1.Fill(objDataset1, "XLData");

                 count = Convert.ToInt32(objDataset1.Tables[0].Rows.Count);
             }
            objConn.Close();
        }
        catch (Exception ex)
        {
            throw ex;
            //Redirecting to error message page

            // Redirect(ConstantClass.StrErrorPageURL);
        }
        return count;
    }
Example #13
0
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        string Path = string.Empty;
        OleDbConnection Con = new OleDbConnection(constr);
        OleDbCommand CMD = new OleDbCommand("SELECT Contain FROM NewsData Where ID = " + Request.QueryString["ID"].ToString(), Con);
        try
        {
            Con.Open();
            Path = CMD.ExecuteScalar().ToString();

        }
        catch { }
        Con.Close();
        if (Path == string.Empty)
        {
            //Path = MapPath("~/QAData/QAData" + QAMainMenu.SelectedValue.ToString() + ".QA");
            if (!Directory.Exists(MapPath("../ItemData/")))
            {
                Directory.CreateDirectory(MapPath("../ItemData/"));
            }
            Path = String.Format("../ItemData/Data{0}{1}{2}{3}.Dat", Request.QueryString["ID"], DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
        }
        try
        {
            CMD.CommandText = String.Format("Update NewsData Set Contain = '{0}' Where ID = {1}", Path, Request.QueryString["ID"]);
            Con.Open();
            CMD.ExecuteNonQuery();
            Path = MapPath(Path);
            //if (File.Exists(Path))
            //{
            //    File.Delete(Path);
            //}
            File.Create(Path).Close();
            TextWriter TW = new StreamWriter(Path, false);
            TW.Write(txt1.Html);
            TW.Flush();
            TW.Close();
            LblError.Text = "تم الحفــــظ";
            LblError.ForeColor = System.Drawing.Color.Green;
            LblError.Visible = true;
        }
        catch (Exception ex)
        {
            LblError.Text = ex.Message.ToString();
            LblError.ForeColor = System.Drawing.Color.Red;
            LblError.Visible = true;
        }
        Con.Close();
    }
Example #14
0
        public static List<Dictionary<string, string>> GetDataFromExcel(string FilePath, string Extension, string isHDR)
        {
            var list = new List<Dictionary<string, string>>();

            string conStr = "";
            switch (Extension)
            {
                case ".xls": //Excel 97-03
                    conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                    break;
                case ".xlsx": //Excel 07
                    conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                    break;
            }
            conStr = String.Format(conStr, FilePath, isHDR);
            OleDbConnection connExcel = new OleDbConnection(conStr);
            OleDbCommand cmdExcel = new OleDbCommand();
            OleDbDataAdapter oda = new OleDbDataAdapter();
            DataTable dt = new DataTable();
            cmdExcel.Connection = connExcel;

            //Get the name of First Sheet
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();

            //Read Data from First Sheet
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
            oda.SelectCommand = cmdExcel;
            oda.Fill(dt);
            connExcel.Close();

            foreach (DataRow row in dt.Rows)
            {
                var obj = new Dictionary<string, string>();
                foreach (var col in dt.Columns)
                {
                    var key = Regex.Replace(col.ToString(), @"\s+", "");
                    obj.Add(key, row[col.ToString()].ToString());
                }
                list.Add(obj);
            }

            return list;
        }
    public void count()
    {
        OleDbConnection conn = new OleDbConnection(connstr);
        OleDbCommand cmdread = new OleDbCommand("SELECT count FROM main WHERE id=1", conn);
        try
        {
            conn.Open();
            p = (int)cmdread.ExecuteScalar();
            conn.Close();
            label1.Text = p.ToString();
            if (p < 10)
                label1.Text = "000" + label1.Text;
            else if (p < 100)
                label1.Text = "00" + label1.Text;
            else if (p < 1000)
                label1.Text = "0" + label1.Text;

            if ((int)Application["numVisitors"] != 0)
            {
                c = (int)Application["numVisitors"];
                int r = p + c;

                OleDbCommand cmd = new OleDbCommand("UPDATE main SET [count][email protected]", conn);  /*"UPDATE main SET [count][email protected] WHERE [id]=1"*/

                cmd.Parameters.AddWithValue("count", r);

                /*p = (int)cmd.Parameters.AddWithValue("@count", 4).Value;*/

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

                label1.Text = r.ToString();
                if (r < 10)
                    label1.Text = "000" + label1.Text;
                else if (r < 100)
                    label1.Text = "00" + label1.Text;
                else if (r < 1000)
                    label1.Text = "0" + label1.Text;

                Application["numVisitors"] = 0;
            }
        }
        finally
        {
            conn.Close();
        }
    }
Example #16
0
        private void FormFirma_Load(object sender, EventArgs e)
        {
            PutBaze = System.IO.File.ReadAllText(Application.StartupPath + "\\Ponuda\\BazaPonuda.txt");
            string PutKriterij =System.IO.File.ReadAllText(@"privPonuda.txt");

            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+PutBaze;

            //----------SQL instrukcija-----------\\

            string sql = "SELECT * FROM sve WHERE Firma LIKE '" + PutKriterij + "%'";

            //klase za povezivanje na ACCESS bazu podataka//
            OleDbConnection conn = new OleDbConnection(connString);
            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
            //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

             ds = new DataSet();         //kreira noi objekt(kopiju) DataSet()-a
            conn.Open();                        //otvara spoj s bazom podataka

            adapter.Fill(ds, "sve");       //puni se DataSet s podacima tabele t_razred
            conn.Close();                       //zatvara se baza podataka

            //nakon zatvaanja BP imamo odgovarajuće podatke u ds objektu ( DataSet() )
            dataGridView2.DataSource = ds;      //upisivanje podataka id ds u dataGridView2
            dataGridView2.DataMember = "sve";
            ukupnaCijenaDataGridViewTextBoxColumn.DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("de-DE");

            this.dataGridView2.Sort(firmaDataGridViewTextBoxColumn, ListSortDirection.Ascending);
            System.IO.File.Delete(@"privPonuda.txt");
        }
Example #17
0
    public void updateProductPrice(ProductInBag Product)
    {
        OleDbConnection myConn = new OleDbConnection(Connstring.getConnectionString());
        OleDbCommand myCmd;
        OleDbDataAdapter myDataAdapter = new OleDbDataAdapter();
        try
        {
            myCmd = new OleDbCommand("UpdateUnitPrice", myConn);
            myCmd.CommandType = CommandType.StoredProcedure;
            OleDbParameter objParam;

            objParam = myCmd.Parameters.Add("@UnitPrice", OleDbType.Decimal);
            objParam.Direction = ParameterDirection.Input;
            objParam.Value = Product.Price;

            objParam = myCmd.Parameters.Add("@ProductID", OleDbType.Integer);
            objParam.Direction = ParameterDirection.Input;
            objParam.Value = Product.ProdID;

            myConn.Open();
            myCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            myConn.Close();
        }
    }
    // Gets all the countries that start with the typed text, taking paging into account
    protected DataTable GetCountries(string text, int startOffset, int numberOfItems)
    {
        OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/continent.mdb"));
        myConn.Open();

        string whereClause = " WHERE CountryName LIKE @CountryName";
        string sortExpression = " ORDER BY CountryName";

        string commandText = "SELECT TOP " + numberOfItems + " CountryID, CountryName FROM Country";
        commandText += whereClause;
        if (startOffset != 0)
        {
            commandText += " AND CountryID NOT IN (SELECT TOP " + startOffset + " CountryID FROM Country";
            commandText += whereClause + sortExpression + ")";
        }

        commandText += sortExpression;

        OleDbCommand myComm = new OleDbCommand(commandText, myConn);
        myComm.Parameters.Add("@CountryName", OleDbType.VarChar).Value = text + '%';

        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        da.SelectCommand = myComm;
        da.Fill(ds, "Country");

        myConn.Close();

        return ds.Tables[0];
    }
Example #19
0
        public void update(string query)
        {
            OleDbConnection connection = new OleDbConnection();
            string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string path = (System.IO.Path.GetDirectoryName(executable));
            AppDomain.CurrentDomain.SetData("DataDirectory", path);
            connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/LMS.accdb";

            OleDbCommand command;
            command = connection.CreateCommand();
            try
            {
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                connection.Open();
                //SqlCommand comm = new SqlCommand(query, connection);

                command.ExecuteNonQuery();

            }
            catch (Exception)
            {
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection();
        Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("app_data/productsdb.mdb");
        Conn.Open();
        //Response.Write(Conn.State);

        System.Data.OleDb.OleDbCommand Comm = new System.Data.OleDb.OleDbCommand();
        System.Data.OleDb.OleDbDataReader dr;
        Comm.Connection = Conn;

        Comm.CommandText = "select productid, productname, productiondescription, price, qoh, imagelocation from products";

        if (Request.Params["categoryid"] != null && Request.Params["categoryid"].Length >0)
        {
            Comm.CommandText += " where categoryid = ?" ;
            Comm.Parameters.AddWithValue("anything", Request.Params["categoryid"].ToString());
        }

        dr = Comm.ExecuteReader();
        bool firstone = true;
        Response.Write("{\"product\":[");
        while (dr.Read())
        {
             if (!firstone)
            {
                Response.Write(",");
            }
            Response.Write(dr[0].ToString());

            firstone = false;

        }
        Response.Write("]}");
    }
Example #21
0
 private void fill_form(string p_id)
 {
     String strQuery = String.Empty;
     OleDbConnection sqlConn = new OleDbConnection();
     OleDbCommand sqlComm = new OleDbCommand();
     OleDbDataReader sqlRead;// = new OleDbDataReader();
     DateTime strReturn = DateTime.Now;
     //
     sqlConn.ConnectionString = PCPUB.m_oledb_connection.ToString();
     sqlConn.Open();
     //
     strQuery = String.Empty;
     strQuery += " SELECT";
     strQuery += " [yarn_count_id],";
     strQuery += " [yarn_count_name]";
     strQuery += " FROM [tis_yarn_count]";
     strQuery += " WHERE [yarn_count_id] = '" + p_id + "'";
     //
     sqlComm.Connection = sqlConn;
     sqlComm.CommandText = strQuery.ToString();
     sqlRead = sqlComm.ExecuteReader();
     //
     if (sqlRead.Read())
     {
         txt_yarn_count_id.Text = sqlRead["yarn_count_id"].ToString();
         txt_yarn_count_name.Text = sqlRead["yarn_count_name"].ToString();
     }
     //
     sqlRead.Close();
     sqlConn.Close();
     sqlRead.Dispose();
     sqlComm.Dispose();
     sqlConn.Dispose();
 }
Example #22
0
 private void btn_Browser_Click(object sender, EventArgs e)
 {
     OpenFileDialog P_open = new OpenFileDialog();//创建打开文件对话框对象
     P_open.Filter = "文本文件|*.txt|所有文件|*.*";//设置筛选字符串
     if (P_open.ShowDialog() == DialogResult.OK)
     {
         txt_Path.Text = P_open.FileName;//显示文件路径
         string conn = string.Format(//创建连接字符串
              @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=text",
              P_open.FileName.Substring(0,P_open.FileName.LastIndexOf(@"\")));
         OleDbConnection P_OleDbConnection = new OleDbConnection(conn);//创建连接对象
         try
         {
             P_OleDbConnection.Open();//打开连接
             OleDbCommand cmd = new OleDbCommand(//创建命令对象
                 string.Format("select * from {0}",
                 P_open.FileName.Substring(P_open.FileName.LastIndexOf(@"\"),
                 P_open.FileName.Length - P_open.FileName.LastIndexOf(@"\"))),
                 P_OleDbConnection);
             OleDbDataReader oda = cmd.ExecuteReader();//得到数据读取器对象
             while (oda.Read())
             {
                txt_Message.Text  += oda[0].ToString();//得到文本文件中的字符串
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);//弹出消息对话框
         }
         finally
         {
             P_OleDbConnection.Close();//关闭连接
         }
     }
 }
Example #23
0
    public DataSet GetDataSet(string filepath, string excelFileExtension)
    {
        try {
            System.Data.OleDb.OleDbConnection oledbcon = null;
            string strConn = string.Empty;
            switch (excelFileExtension.Trim()) {
                case "xls":
                    oledbcon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;MaxScanRows=0;\"");
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties=Excel 8.0;";
                    break;
                case "xlsx":
                    oledbcon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath
                   + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1'");
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath
                   + ";Extended Properties=Excel 12.0;";
                    break;
            }

            //excel
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
            string sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString();
            System.Data.OleDb.OleDbDataAdapter oledbAdaptor = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", oledbcon);
            //select
            DataSet ds = new DataSet();
            oledbAdaptor.Fill(ds);
            oledbcon.Close();
            return ds;
        } catch (Exception ex) {
            throw ex;
        }
    }
    public string LoadContain()
    {
        if (Request.QueryString["CourseId"] == null)
        {
            return string.Empty;
        }

        string ThePath = string.Empty;
        string RetData = string.Empty;
        using (OleDbConnection Con = new OleDbConnection(constr))
        {
            OleDbCommand cmd = new OleDbCommand(String.Format("SELECT TOP 1 DataPath FROM CoursenotimeDataPath WHERE CourseId = {0}", Request.QueryString["CourseId"]), Con);
            try
            {
                Con.Open();
                ThePath = cmd.ExecuteScalar().ToString();
                //if (ThePath != string.Empty)
                //    ThePath = MapPath(DB.CourseNoTimeFileDir + ThePath);
                ThePath = DB.CourseNoTimeFileDir + ThePath;

                TextReader TR = new StreamReader(ThePath);
                RetData = TR.ReadToEnd();
                TR.Close();
                TR.Dispose();

            }
            catch (Exception ex)
            {
                RetData = ex.Message;
            }
            Con.Close();
        }

        return HttpUtility.HtmlDecode(RetData);
    }
Example #25
0
        private static void PrintSpreadsheet(OleDbConnectionStringBuilder connestionString)
        {
            DataSet sheet1 = new DataSet();
            using (OleDbConnection connection = new OleDbConnection(connestionString.ConnectionString))
            {
                connection.Open();
                string selectSql = @"SELECT * FROM [Sheet1$]";
                using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
                {
                    adapter.Fill(sheet1);
                }
                connection.Close();
            }
            
            var table = sheet1.Tables[0];

            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn column in table.Columns)
                {
                    Console.Write("{0, -20} ", row[column]);
                }

                Console.WriteLine();
            }
        }
Example #26
0
        public override List<DomainAlias> GetDomainAliases(string domainName)
        {
            var _tmp = new List<DomainAlias>();

            using (OleDbConnection _conn = new OleDbConnection(Settings.Default.connectionString))
            {
                _conn.Open();
                using (OleDbCommand _cmd = new OleDbCommand(@"SELECT domain_aliases.name AS alias, domains.name AS [domain], domain_aliases.status
                                                                FROM (domain_aliases INNER JOIN
                                                            domains ON domain_aliases.dom_id = domains.id)
                                                                WHERE (domain_aliases.status = 0) AND (domains.name = ?)", _conn))
                {
                    _cmd.CommandType = CommandType.Text;
                    _cmd.Parameters.AddWithValue("NAME", domainName);

                    using (OleDbDataReader _read = _cmd.ExecuteReader())
                    {
                        while (_read.Read())
                        {
                            var _d = new DomainAlias();
                            _d.Domain = _read["domain"].ToString();
                            _d.Alias = _read["alias"].ToString();

                            _tmp.Add(_d);
                        }
                    }
                }
                _conn.Close();
            }

            return _tmp;
        }
Example #27
0
        public DataTable sepetcevir(string uyeID, string map)
        {

            OleDbConnection cnn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + map);
            cnn.Open();
            OleDbCommand cmd = new OleDbCommand("select sepet from uyeler where uyeid=" + uyeID, cnn);
            OleDbDataReader rdr = cmd.ExecuteReader();
            rdr.Read();
            string[] urunler = rdr[0].ToString().Split(',');

            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("fid"), new DataColumn("aciklama"), new DataColumn("fiyat") });

            if (rdr[0].ToString() != "")
            {
                foreach (string item in urunler)
                {
                    cmd.Dispose();
                    string fid = item;

                    cmd = new OleDbCommand("select * from fotolar where fot_id=" + fid, cnn);
                    OleDbDataReader rdr2 = cmd.ExecuteReader();
                    rdr2.Read();
                    string ack = rdr2[5].ToString();
                    string fiyat = rdr2[6].ToString();

                    dt.Rows.Add(fid, ack, fiyat);
                }
            }

            cnn.Close();

            return dt;
        }
    protected void btTaiLen_Click1(object sender, EventArgs e)
    {
        if (Request.Cookies["ADMIN"] == null) return;
        if (FileUpload1.HasFile)
            try
            {
                string path = Server.MapPath(@"EXCEL\") + "Question_" + DateTime.Now.ToString("yyMMdd_HHmmss") + ".xlsx";
                FileUpload1.SaveAs(path);
                string txt = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0 Xml;", path);
                OleDbConnection con = new OleDbConnection(txt);
                con.Open();
                txt = "Select * FROM [Sheet1$]";
                OleDbDataAdapter da = new OleDbDataAdapter(txt, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                con.Close();

                gvCauHoi.DataSource = ds;
                gvCauHoi.DataBind();
                string temp;
                foreach (GridViewRow dr in gvCauHoi.Rows)
                {
                    temp = Server.HtmlDecode(dr.Cells[0].Text);
                    if (temp.StartsWith("#"))
                        dr.CssClass = "Q1";
                    else if (temp.StartsWith("$")) // Không đảo phương án trả lời
                        dr.CssClass = "Q2";
                    else if (temp.StartsWith("*")) // Phương án trả lời đúng
                        dr.CssClass = "A1";
                }
            }
            catch (Exception ex) { lbError.Text = ex.Message; }
    }
Example #29
0
        public bool InsertFtpRecord(FileDetail fileDetail)
        {
            var lcsql =
                "insert into MasterFtp(FileName, CreateTime, Folder, Records, DlTime) values ( ?, ?,?,?,?)";


            var connectionString = ConfigurationManager.ConnectionStrings["vfpConnectionString"].ConnectionString;
            using (var connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SET NULL OFF";

                    command.ExecuteNonQuery();
                }
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = lcsql;
                    command.Parameters.AddWithValue("FileName", fileDetail.FileName);
                    command.Parameters.AddWithValue("CreateTime", fileDetail.FileDate);
                    command.Parameters.AddWithValue("Folder", fileDetail.Folder);
                    command.Parameters.AddWithValue("Records", fileDetail.Records);
                    command.Parameters.AddWithValue("DlTime", fileDetail.DownloadTime);

                    //connection.Open();
                    var retval = command.ExecuteNonQuery();
                    var success = (retval == 1);
                    return success;
                }
            }


        }
Example #30
0
        private void addToDatabase(string sql)
        {
            OleDbConnection db = null;

            try
            {
                db = new OleDbConnection();
                db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + mFileName;
                db.Open();

                OleDbCommand command = new OleDbCommand(sql, db);
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                showErrorMessage(ex.Message);
            }
            finally
            {
                if (db != null)
                {
                    db.Close();
                }
            }
        }