Insert() public method

Allows the programmer to easily insert into the DB
public Insert ( String tableName, String>.Dictionary data ) : bool
tableName String The table into which we insert the data.
data String>.Dictionary A dictionary containing the column names and data for the insert.
return bool
Beispiel #1
0
        public void AddNewJoke(string message)
        {
            //Create sanitised string with the joke
            List<string> strings = new List<string>(message.Split(' '));
            strings.RemoveAt(0);
            string joke = String.Join(" ", strings.ToArray());
            joke = System.Text.RegularExpressions.Regex.Escape(joke.Replace("'", @"''")) ;

            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<String, String>();
            data.Add("JokeBody", joke);
            try
            {
                db.Insert("Jokes", data);
            }
            catch (Exception crap)
            {
                Logger.GetLogger().Error(crap.Message);
            }
        }
Beispiel #2
0
        public void AddNewTrivia(string message, string author)
        {
            //Create a sanitised string with trivia
            List<string> strings = new List<string>(message.Split(' '));
            strings.RemoveAt(0);
            string trivia = String.Join(" ", strings.ToArray());
            trivia = System.Text.RegularExpressions.Regex.Escape(trivia.Replace("'", @"''"));

            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<String, String>();
            data.Add("Body", trivia);
            data.Add("Author", author);

            try
            {
                db.Insert("Trivia", data);
            }
            catch (Exception crap)
            {
                Logger.GetLogger().Error(crap.Message);
            }
        }
Beispiel #3
0
        private void btn_simpan_Click(object sender, EventArgs e)
        {
            if (ValidateChildren(ValidationConstraints.Enabled))
            {
                SQLiteDatabase db = new SQLiteDatabase();
                Dictionary <String, String> data = new Dictionary <String, String>();
                data.Add("NPSN", LoginInfo.getNPSN());
                data.Add("NAMA_KEGIATAN", txt_kegiatan.Text);
                data.Add("TAHUN", txt_tahun.Text);
                data.Add("JENIS", pnl_jenis.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked).Text.ToLower());
                data.Add("TINGKAT", pnl_tingkat.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked).Text.ToLower());
                data.Add("PENCAPAIAN", pnl_pencapaian.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked).Text.ToLower());

                try
                {
                    db.Insert("prestasi_slta", data);
                    MessageBox.Show("Data prestasi berhasil disimpan", "Sukses", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception crap)
                {
                    MessageBox.Show(crap.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
Beispiel #4
0
        private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
        {
            // vars
            int    timeStampId;
            string firstName;

            // check for user/scanner pressing enter
            if (e.KeyChar.Equals('\r') || e.KeyChar.Equals('\n'))
            {
                // remove leading and trailing spaces
                input = input.Trim();

                // check for existence of card
                if (Helper.EmployeeExists(input, sql))
                {
                    dt          = sql.GetDataTable("select * from employees where employeeID=" + input + ";");
                    timeStampId = int.Parse(dt.Rows[0].ItemArray[6].ToString());
                    firstName   = dt.Rows[0].ItemArray[1].ToString();

                    // check for clock-in or -out
                    if (timeStampId > 0)
                    {
                        try {
                            // clock out
                            Dictionary <String, String> data = new Dictionary <String, String>();
                            data.Add("clockOut", DateTime.Now.ToString(StringFormats.sqlTimeFormat));
                            sql.Update("timeStamps", data, String.Format("timeStamps.id = {0}", timeStampId));
                            sql.ExecuteNonQuery("update employees set currentClockInId = 0 where employeeId=" + input + ";");
                        } catch (Exception err) {
                            MessageBox.Show(this, "There was an error while trying to clock you out.\n\n" + err.Message, "Clock Out Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        // calculate time logged
                        dt = sql.GetDataTable("select strftime('%s', clockOut) - strftime('%s', clockIn) from timeStamps where id=" + timeStampId + ";");
                        TimeSpan diff = TimeSpan.FromSeconds(long.Parse(dt.Rows[0].ItemArray[0].ToString()));

                        // show confirmation
                        LabelStatus.Text           = "Goodbye " + firstName + ".\nYou logged " + GenerateClockedTime(diff) + ".";
                        TimerInputTimeout.Interval = 3000;
                        TimerInputTimeout.Enabled  = true;
                    }
                    else
                    {
                        // clock in
                        try {
                            Dictionary <String, String> data = new Dictionary <String, String>();
                            data.Add("employeeID", input);
                            data.Add("clockIn", DateTime.Now.ToString(StringFormats.sqlTimeFormat));

                            sql.Insert("timeStamps", data);
                            dt = sql.GetDataTable("select seq from sqlite_sequence where name='timeStamps';");

                            data.Clear();
                            data.Add("currentClockInId", dt.Rows[0].ItemArray[0].ToString());

                            sql.Update("employees", data, String.Format("employees.employeeId = {0}", input));
                        } catch (Exception err) {
                            MessageBox.Show(this, "There was an error while trying to clock you in.\n\n" + err.Message, "Clock In Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        // show confirmation
                        LabelStatus.Text           = "Hello " + firstName + "!\nYou're now clocked in.";
                        TimerInputTimeout.Interval = 2500;
                        TimerInputTimeout.Enabled  = true;
                    }
                }
                else
                {
                    // notify user of unrecognized card
                    LabelStatus.Text           = "Unrecognized card!";
                    TimerInputTimeout.Interval = 2500;
                    TimerInputTimeout.Enabled  = true;
                }

                // reset input storage
                LabelInput.Text = "input: ";
                input           = "";
            }
            else if (Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back)
            {
                // add the input
                StoreInput(e.KeyChar);
            }
        }
        public int newUniqueID(MediaStreamingRequest request, bool getIDOnly)
        {
            int newId = IdsAndInputFilesContains(request.InputFile + request.UniekClientID);

            if (request.KeepSameIDForSameInputFile && newId != 0) // != 0 means found as existing id that can be resumed
            {
                var ms = GetStreamerByID(newId);
                if (ms != null && !getIDOnly)
                {
                    //mediaStreamers.Remove(newId);
                    Functions.WriteLineToLogFile("Streamer newId=" + newId + " about to stop (in background), mediaStreamers.ContainsKey(newId) : " +
                                                 mediaStreamers.ContainsKey(newId));
                    StopStreamer(newId, 2);
                    Functions.WriteLineToLogFile("Streamer newId=" + newId + " stopped (in background), mediaStreamers.ContainsKey(newId) : " +
                                                 mediaStreamers.ContainsKey(newId));
                }

                if (!getIDOnly)
                {
                    DeleteStreamingFiles(newId);             //begin anew, s.t. if new quality, this will be used.
                }
                //bump up the id in the database
                db.Delete("IDANDINPUTFILE", String.Format("STREAMID = {0}", "" + newId));
                var item = new Dictionary <string, string>();
                item.Add("STREAMID", "" + newId);
                string i = request.InputFile.Replace("'", "''");
                string u = request.UniekClientID.Replace("'", "''");
                item.Add("INPUTFILE", i + u);
                db.Insert("IDANDINPUTFILE", item);

                return(newId);
            }



            //clean up if database is large
            const int maxFileToRememberResume = 1000;
            int       count = 0;

            Int32.TryParse(db.ExecuteScalar("select COUNT(*) from IDANDINPUTFILE where STREAMID IS NOT NULL;"),
                           out count);
            if (count > maxFileToRememberResume)
            {
                try
                {
                    DataTable tabel;
                    String    query = "select STREAMID, INPUTFILE from IDANDINPUTFILE;";
                    tabel = db.GetDataTable(query);
                    // The results can be directly applied to a DataGridView control
                    //                            recipeDataGrid.DataSource = tabel;
                    // Or looped through for some other reason
                    var i = 0;
                    foreach (DataRow r in tabel.Rows)
                    {
                        if (i < count / 2)
                        {
                            db.ExecuteNonQuery("delete from IDANDINPUTFILE where STREAMID=" + r["STREAMID"] + ";");
                        }
                        else
                        {
                        }
                        i++;
                    }
                }
                catch (Exception fail)
                {
                    String error = "The following error has occurred in cleaning up database : " + db.ToString() + "\n";
                    error += fail.Message;
                    if (Settings.Default.DebugStreaming)
                    {
                        Functions.WriteLineToLogFile("StreamingManager: " + error);
                    }
                }
            }



            do
            {
                var r = new Random();
                //newId = (getIDOnly ? r.Next(100000, 999999) : r.Next(10000, 99999));
                newId = r.Next(10000, 99999);
            } while (mediaStreamers.ContainsKey(newId) || !IdsAndInputFilesContains(newId).Equals(""));

            if (IdsAndInputFilesContains(request.InputFile + request.UniekClientID) == 0 && !request.InputFile.Contains("RMCLiveTV")) //live tv gets a new iD all the time anyway, due to randowm nr in inputfile string
            {
                var item = new Dictionary <string, string>();
                item.Add("STREAMID", "" + newId);
                string i = request.InputFile.Replace("'", "''");
                string u = request.UniekClientID.Replace("'", "''");
                item.Add("INPUTFILE", i + u);
                db.Insert("IDANDINPUTFILE", item);
                //  db.CommitTransaction();
            }
            return(newId);
        }
        public bool Save(int medicationSpreadID, int medicationID)
        {
            SQLiteDatabase sqlDatabase = null;

            try
            {
                Globals dbHelp = new Globals();
                dbHelp.OpenDatabase();
                sqlDatabase = dbHelp.GetSQLiteDatabase();
                if (sqlDatabase != null)
                {
                    if (sqlDatabase.IsOpen)
                    {
                        if (medicationSpreadID == -1)
                        {
                            Log.Info(TAG, "Save (insert): Saving New Medication Spread");
                            ContentValues values = new ContentValues();
                            values.Put("MedicationID", medicationID);
                            values.Put("Dosage", Dosage.ToString());
                            values.Put("FoodRelevance", (int)FoodRelevance);
                            ID = (int)sqlDatabase.Insert("MedicationSpread", null, values);
                            Log.Info(TAG, "Save (insert): Saved Spread with ID - " + ID.ToString() + ", medicationID - " + medicationID.ToString() + ", Dosage - " + Dosage.ToString() + ", Food Relevance - " + StringHelper.MedicationFoodForConstant(FoodRelevance));
                            IsNew   = false;
                            IsDirty = false;
                            if (MedicationTakeTime != null)
                            {
                                MedicationTakeTime.Save(ID);
                            }
                            if (MedicationTakeReminder != null)
                            {
                                MedicationTakeReminder.Save(ID);
                            }
                        }
                        else
                        {
                            ContentValues values = new ContentValues();
                            values.Put("MedicationID", medicationID);
                            values.Put("Dosage", Dosage.ToString());
                            values.Put("FoodRelevance", (int)FoodRelevance);
                            string   whereClause = "ID = ? AND MedicationID = ?";
                            string[] wheres      = new string[]
                            {
                                ID.ToString(),
                                     MedicationID.ToString()
                            };
                            sqlDatabase.Update("MedicationSpread", values, whereClause, wheres);
                            if (MedicationTakeTime != null)
                            {
                                MedicationTakeTime.Save(ID);
                            }
                            if (MedicationTakeReminder != null)
                            {
                                MedicationTakeReminder.Save(ID);
                            }
                            IsDirty = false;
                        }
                        sqlDatabase.Close();
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
                Log.Error(TAG, "Save: Exception - " + e.Message);
                if (sqlDatabase != null && sqlDatabase.IsOpen)
                {
                    sqlDatabase.Close();
                }
                return(false);
            }
        }
Beispiel #7
0
        public void insert_(ProgramSettings program_settings, String template_name)
        {
            db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<String, String>();
            data.Add("f_max", program_settings.f_max.ToString());
            data.Add("template_name", template_name);
            data.Add("t_increase", program_settings.time_incr.ToString());
            data.Add("time_pause", program_settings.t_pause.ToString());
            data.Add("number_of_attempts", program_settings.num_of_attempts.ToString());
            data.Add("allow_digit", program_settings.digitization.ToString());
            data.Add("allow_auto_calculate", program_settings.calculation.ToString());

            data.Add("template_color_num", program_settings.template_color_num.ToString());
            data.Add("template_line_width", program_settings.template_line_width.ToString());
            data.Add("measurement_color_num", program_settings.measurement_color_num.ToString());
            data.Add("measurement_line_width", program_settings.measurement_line_width.ToString());
            data.Add("grid_color_num", program_settings.grid_color_num.ToString());
            data.Add("grid_line_width", program_settings.grid_line_width.ToString());
            data.Add("axis_color_num", program_settings.axis_color_num.ToString());
            data.Add("axis_line_width", program_settings.axis_line_width.ToString());

            try
            {
                db.Insert("settings", data);
            }
            catch (Exception crap)
            {
                MessageBox.Show(crap.Message);
            }
        }
Beispiel #8
0
        public static void category_populate(SQLiteDatabase db)
        {
            string[] categorys = { "Comida", "Combustível", "Pedágio", "Manutenção", "Outros" };

            ContentValues category_values = new ContentValues();

            foreach (string s in categorys)
            {
                category_values.Put("registration_date", DateTime.Now.ToString());
                category_values.Put("lastedit_date", DateTime.Now.ToString());
                category_values.Put("name", s);
                db.Insert("category", null, category_values);
                category_values.Clear();
            }

            //TODO

            ContentValues trip_values = new ContentValues();


            trip_values.Put("reward", 1250);
            trip_values.Put("home", "Leme");
            trip_values.Put("destiny", "Araras");
            trip_values.Put("toll_value", 100);
            trip_values.Put("fuell_value", 200);
            trip_values.Put("freight", "Arroz");
            trip_values.Put("registration_date", DateTime.Now.ToString());
            trip_values.Put("lastedit_date", DateTime.Now.ToString());
            trip_values.Put("complete_date", "");
            db.Insert("trip", null, trip_values);
            trip_values.Clear();

            trip_values.Put("reward", 3000);
            trip_values.Put("home", "Campinas");
            trip_values.Put("destiny", "São Paulo");
            trip_values.Put("toll_value", 100);
            trip_values.Put("fuell_value", 200);
            trip_values.Put("freight", "Arroz");
            trip_values.Put("registration_date", DateTime.Now.ToString());
            trip_values.Put("lastedit_date", DateTime.Now.ToString());
            trip_values.Put("complete_date", "");
            db.Insert("trip", null, trip_values);
            trip_values.Clear();

            trip_values.Put("reward", 4000);
            trip_values.Put("home", "Pernambuco");
            trip_values.Put("destiny", "Amapá");
            trip_values.Put("toll_value", 100);
            trip_values.Put("fuell_value", 200);
            trip_values.Put("freight", "Arroz");
            trip_values.Put("registration_date", DateTime.Now.ToString());
            trip_values.Put("lastedit_date", DateTime.Now.ToString());
            trip_values.Put("complete_date", "");
            db.Insert("trip", null, trip_values);
            trip_values.Clear();

            /*
             *
             * values.Put("reward", this.reward);
             * values.Put("home", this.home);
             * values.Put("destiny", this.destiny);
             * values.Put("toll_value", this.toll_value);
             * values.Put("fuell_value", this.fuell_value);
             * values.Put("freight", this.freight);
             * values.Put("registration_date", DateTime.Now.ToString());
             * values.Put("lastedit_date", DateTime.Now.ToString());
             * values.Put("complete_date", 0);
             */
        }
Beispiel #9
0
        private void bt_save_Click(object sender, EventArgs e)
        {
            if (tb_nom.TextLength < 6)
            {
                MessageBox.Show("Le nom de l'équipe doit comporter au moins 6 caractères !");
                return;
            }
            capitaineId = 0;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if ((Boolean)row.Cells["Capitaine"].Value == true)
                {
                    capitaineId = Int32.Parse(row.Cells["id"].Value.ToString());
                }
            }
            if (playerCount < 6)
            {
                MessageBox.Show("Une équipe doit comporter au minimum 6 joueurs.");
            }
            else if (capitaineId == 0)
            {
                MessageBox.Show("L'équipe doit avoir un capitaine !");
            }
            else
            {
                db = new SQLiteDatabase();
                int idEquipe;
                Dictionary <String, String> data = new Dictionary <String, String>();
                data.Add("nom", this.tb_nom.Text);
                data.Add("capitaine_id", capitaineId.ToString());
                if (this.id_equipe == 0)
                {
                    db.Insert("equipe", data);
                    String query = "select max(id) FROM equipe";
                    idEquipe = Int32.Parse(db.ExecuteScalar(query));
                }
                else
                {
                    db.Update("equipe", data, "id = " + this.id_equipe);
                    idEquipe = this.id_equipe;
                }
                Dictionary <String, String> dataUpdate = new Dictionary <String, String>();
                dataUpdate.Add("equipe_id", "NULL");
                db.Update("personne", dataUpdate, " equipe_id = " + idEquipe);
                string  whereString = " id IN (";
                Boolean first       = true;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if ((Boolean)row.Cells["Selection"].Value)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            whereString += ", ";
                        }
                        whereString += row.Cells["id"].Value.ToString();
                    }
                }
                whereString            += ")";
                dataUpdate["equipe_id"] = idEquipe.ToString();
                db.Update("personne", dataUpdate, whereString);

                this.Close();
            }
        }
 public long insert(string table, ContentValues values)
 {
     return(db.Insert(table, null, values));
 }
Beispiel #11
0
        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            // TODO simplify validation by checking if the input is a number
            bool   containsInvalidChar = false;
            string finalCardID         = TextBoxCardID.Text.Trim();
            string posType             = "";

            // check for invalid chars
            foreach (char invalidChar in invalidChars)
            {
                if (finalCardID.IndexOf(invalidChar) != -1)
                {
                    containsInvalidChar = true;
                    finalCardID.Replace(invalidChar, '_');
                }
            }

            // if there was an invalid char, notify user of ID used in app
            if (containsInvalidChar)
            {
                if (MessageBox.Show(this, "Your card ID format contains invalid characters for use in this program. In the future, when your card is scanned, it will be seen as " + finalCardID + " instead of " + TextBoxCardID.Text + ".", "Card ID Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.Cancel)
                {
                    return;
                }
            }

            // check for blank first name
            if (TextBoxFirstName.Text.Length == 0)
            {
                if (MessageBox.Show(this, "Are you sure you don't want to provide a first name?\nIf yes, your card ID will be used instead.", "Empty First Name", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    TextBoxFirstName.Text = finalCardID;
                }
            }

            // set position type if applicable
            if (RadioButtonFWS.Checked)
            {
                posType = "FWS";
            }
            else if (RadioButtonSWS.Checked)
            {
                posType = "SWS";
            }
            else if (RadioButtonMST.Checked)
            {
                posType = "MST";
            }
            else if (RadioButtonHED.Checked)
            {
                posType = "HED";
            }
            else if (RadioButtonHelp.Checked)
            {
                posType = "Help";
            }
            else if (RadioButtonTutor1.Checked)
            {
                posType = "Tutor1";
            }
            else if (RadioButtonTutor2.Checked)
            {
                posType = "Tutor2";
            }
            else if (RadioButtonTANF.Checked)
            {
                posType = "TANF";
            }

            // verify card ID doesn't already exist
            if (sql.GetDataTable("select * from employees where employeeID=" + TextBoxCardID.Text.Trim() + ";").Rows.Count > 0)
            {
                MessageBox.Show(this, "The Card ID you entered already exists! Please make sure it was entered correctly.", "Duplicate Card ID", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try {
                Dictionary <String, String> data = new Dictionary <String, String>();
                data.Add("employeeID", TextBoxCardID.Text);
                data.Add("firstName", TextBoxFirstName.Text);
                data.Add("lastName", TextBoxLastName.Text);
                data.Add("MiddleName", TextBoxMI.Text);
                data.Add("hourlyRate", NumericUpDownHrRate.Value.ToString());
                data.Add("employeeType", posType);
                data.Add("currentClockInId", "0");

                sql.Insert("employees", data);
            } catch (Exception error) {
                MessageBox.Show("Something went horribly wrong while trying to save your profile!\n" + error.Message);
            }

            Close();
        }
        /// <summary>
        ///     Handles the Click event of the btnOK control. The conference is renamed, the divisions are deleted and recreated, and if any
        ///     teams are left in division IDs that no longer exist, they get reassigned.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
        /// </param>
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            var db = new SQLiteDatabase(MainWindow.CurrentDB);

            if (String.IsNullOrWhiteSpace(txtName.Text))
            {
                txtName.Text = "League";
            }

            MainWindow.Conferences.Single(conference => conference.ID == _curConf.ID).Name = txtName.Text;
            db.Update("Conferences", new Dictionary <string, string> {
                { "Name", txtName.Text }
            }, "ID = " + _curConf.ID);

            MainWindow.Divisions.RemoveAll(division => division.ConferenceID == _curConf.ID);
            db.Delete("Divisions", "Conference = " + _curConf.ID);

            var usedIDs = new List <int>();

            db.GetDataTable("SELECT ID FROM Divisions")
            .Rows.Cast <DataRow>()
            .ToList()
            .ForEach(row => usedIDs.Add(ParseCell.GetInt32(row, "ID")));

            var list = Tools.SplitLinesToList(txtDivisions.Text, false);

            foreach (var newDiv in list)
            {
                var newName = newDiv.Replace(':', '-');
                var i       = 0;
                while (usedIDs.Contains(i))
                {
                    i++;
                }
                MainWindow.Divisions.Add(new Division {
                    ID = i, Name = newName, ConferenceID = _curConf.ID
                });
                usedIDs.Add(i);
            }

            if (MainWindow.Divisions.Any(division => division.ConferenceID == _curConf.ID) == false)
            {
                var i = 0;
                while (usedIDs.Contains(i))
                {
                    i++;
                }
                MainWindow.Divisions.Add(new Division {
                    ID = i, Name = txtName.Text, ConferenceID = _curConf.ID
                });
                usedIDs.Add(i);
            }

            foreach (var div in MainWindow.Divisions.Where(division => division.ConferenceID == _curConf.ID))
            {
                db.Insert(
                    "Divisions",
                    new Dictionary <string, string>
                {
                    { "ID", div.ID.ToString() },
                    { "Name", div.Name },
                    { "Conference", div.ConferenceID.ToString() }
                });
            }

            TeamStats.CheckForInvalidDivisions();

            ListWindow.MustUpdate = true;
            Close();
        }
Beispiel #13
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            try {
                string dayOfWeek = (DayOfWeekComboBox.SelectedIndex + 1).ToString();
                string clockIn   = ClockInTimePicker.Value.ToString("HH:mm");
                string clockOut  = ClockOutTimePicker.Value.ToString("HH:mm");

                Dictionary <String, String> data = new Dictionary <String, String> {
                    { "dayOfWeek", dayOfWeek },
                    { "clockIn", clockIn },
                    { "clockOut", clockOut }
                };

                if (SaveButton.Text == "Save" && AvgHoursGridView.SelectedRows.Count > 0)
                {
                    string entryId = AvgHoursGridView.SelectedRows[0].Cells[0].Value.ToString();

                    if (sql.Update("avgHours", data, String.Format("avgHours.id = {0}", entryId)))
                    {
                        AvgHoursGridView.SelectedRows[0].Cells[1].Value = dayOfWeek;
                        AvgHoursGridView.SelectedRows[0].Cells[2].Value = clockIn;
                        AvgHoursGridView.SelectedRows[0].Cells[3].Value = clockOut;

                        SetAddButton();
                    }
                }
                else if (SaveButton.Text == "Add" && AvgHoursGridView.SelectedRows.Count == 0)
                {
                    // TODO see if count == 0 check is actually necessary
                    data.Add("employeeID", TextBoxCardID.Text.Trim());

                    if (sql.Insert("avgHours", data))
                    {
                        DataTable dt = AvgHoursGridView.DataSource as DataTable;

                        if (dt == null)
                        {
                            dt = new DataTable();
                            dt.Columns.Add("id", typeof(int));
                            dt.Columns.Add("Day", typeof(string));
                            dt.Columns.Add("clockIn", typeof(string));
                            dt.Columns.Add("clockOut", typeof(string));

                            AvgHoursGridView.DataSource         = dt;
                            AvgHoursGridView.Columns[0].Visible = false; // hide ID column
                        }

                        DataRow dr = dt.NewRow();
                        dr[0] = sql.ExecuteScalar("select seq from sqlite_sequence where name='avgHours';");
                        dr[1] = dayOfWeek;
                        dr[2] = clockIn;
                        dr[3] = clockOut;

                        // TODO find out why this event gets deregistered and re-registered (and possibly do whatever it does directly to make it less confusing)
                        AvgHoursGridView.RowStateChanged -= new DataGridViewRowStateChangedEventHandler(AvgHoursGridView_RowStateChanged);

                        dt.Rows.Add(dr);
                        dt.AcceptChanges();
                        AvgHoursGridView.ClearSelection();

                        AvgHoursGridView.RowStateChanged += new DataGridViewRowStateChangedEventHandler(AvgHoursGridView_RowStateChanged);
                    }
                }
            } catch (Exception err) {
                MessageBox.Show(this, "There was an error while trying to save the entry.\n\n" + err.Message, "Save Avg Hours Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #14
0
        private void SaveDataToLocalDataBase()
        {
            EditText     txtproname         = FindViewById <EditText>(Resource.Id.txtbarProjectname);
            EditText     txtclientname      = FindViewById <EditText>(Resource.Id.txtbarClientName);
            EditText     txtlocation        = FindViewById <EditText>(Resource.Id.txtbarLocation);
            EditText     txtquantity        = FindViewById <EditText>(Resource.Id.txtbarquantity);
            EditText     txtUnitCost        = FindViewById <EditText>(Resource.Id.txtbarunitcost);
            EditText     txtbarcodenumber   = FindViewById <EditText>(Resource.Id.txtbarbarcodenumber);
            EditText     txtbaritemname     = FindViewById <EditText>(Resource.Id.txtbaritemname);
            LinearLayout llscanbarcode      = FindViewById <LinearLayout>(Resource.Id.llscanbarcode);
            LinearLayout llafterscanbarcode = FindViewById <LinearLayout>(Resource.Id.llafterscan);

            string projectname   = txtproname.Text;
            string clientname    = txtclientname.Text;
            string location      = txtlocation.Text;
            string quantity      = txtquantity.Text;
            string unitcost      = txtUnitCost.Text;
            string itemname      = txtbaritemname.Text;
            string barcodenumber = txtbarcodenumber.Text;
            string dtnow         = DateTime.Now.ToString("MM-dd-yyyy HH:mm");

            db = this.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
            db.ExecSQL("CREATE TABLE IF NOT EXISTS "
                       + "tbl_Inventory"
                       + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,EmpID INTEGER,ProjectID VARCHAR, ProjectName VARCHAR, ClientName VARCHAR,Location VARCHAR, Image1 VARCHAR , Image2 VARCHAR, Image3 VARCHAR, Image4 VARCHAR," +
                       "ItemDescription VARCHAR, Brand VARCHAR, Quantity VARCHAR, ModelNumber VARCHAR, UnitCost VARCHAR, Notes VARCHAR , Addeddate VARCHAR, AudioFileName VARCHAR,BarCodeNumber VARCHAR,InventoryType VARCHAR" +
                       "" +
                       "" +
                       ");");
            ContentValues values = new ContentValues();

            values.Put("EmpID", empid);
            values.Put("ProjectID", projectid);
            values.Put("ProjectName", projectname);
            values.Put("ClientName", clientname);
            values.Put("Location", location);
            values.Put("Quantity", quantity);
            values.Put("UnitCost", unitcost);
            values.Put("BarCodeNumber", barcodenumber);
            values.Put("AudioFileName", "");
            values.Put("Image1", "");
            values.Put("Image2", "");
            values.Put("Image3", "");
            values.Put("Image4", "");
            values.Put("ItemDescription", "");
            values.Put("Notes", itemname);
            values.Put("Brand", "");
            if (location.Trim() != "")
            {
                if (barcodenumber != "")
                {
                    if (quantity.Trim() != "")
                    {
                        if (unitcost == "")
                        {
                            unitcost = "0";
                        }

                        if (EditInventoryID != "")
                        {
                            db.Update("tbl_Inventory", values, "ID = " + EditInventoryID, null);
                        }
                        else
                        {
                            values.Put("InventoryType", "3");
                            values.Put("Addeddate", dtnow);
                            db.Insert("tbl_Inventory", null, values);
                        }

                        txtquantity.SetText("", TextView.BufferType.Editable);
                        txtUnitCost.SetText("", TextView.BufferType.Editable);
                        txtbarcodenumber.SetText("", TextView.BufferType.Editable);
                        txtbaritemname.SetText("", TextView.BufferType.Editable);
                        llafterscanbarcode.Visibility = ViewStates.Gone;
                        llscanbarcode.Visibility      = ViewStates.Visible;
                        Toast.MakeText(this, "Data saved successfully", ToastLength.Long).Show();
                        EditInventoryID = "";
                        editor.PutString("EditFromItemListForBarcode", "");
                        editor.Commit();
                        editor.Apply();
                    }
                    else
                    {
                        Toast.MakeText(this, "Please enter quantity", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(this, "Please enter barcodenumber", ToastLength.Long).Show();
                }
            }


            if (location.Trim() != "")
            {
            }
            else
            {
                Toast.MakeText(this, "Please enter location name", ToastLength.Long).Show();
            }
        }
 public void TestSQLiteDBInsert()
 {
     db = new SQLiteDatabase();
     Dictionary<string, string> data = new Dictionary<string, string>();
     data.Add("id", "3");
     data.Add("name", "Blue");
     data.Add("hex", "0000ff");
     try
     {
         db.Insert("colors", data);
     }
     catch (Exception ex)
     {
         Console.Write("Error: {0}", ex.Message);
     }
 }
Beispiel #16
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            if (vGridControl3.Rows["editorRow6"].Properties.Value == null)
            {
                dic.Add("iscost", "0");
            }
            else
            {
                dic.Add("iscost", vGridControl3.Rows["editorRow6"].Properties.Value.ToString() == "เตือน"?"1":"0");
            }
            if (vGridControl3.Rows["editorRow7"].Properties.Value == null)
            {
                dic.Add("ismin", "0");
            }
            else
            {
                dic.Add("ismin", vGridControl3.Rows["editorRow7"].Properties.Value.ToString() == "เตือน" ? "1" : "0");
            }
            if (vGridControl3.Rows["editorRow8"].Properties.Value == null)
            {
                dic.Add("islowcost", "0");
            }
            else
            {
                dic.Add("islowcost", vGridControl3.Rows["editorRow8"].Properties.Value.ToString() == "เตือน" ? "1" : "0");
            }
            if (vGridControl3.Rows["editorRow9"].Properties.Value == null)
            {
                dic.Add("ispricechange", "0");
            }
            dic.Add("ispricechange", vGridControl3.Rows["editorRow9"].Properties.Value.ToString() == "เตือน" ? "1" : "0");

            if (ditem.Rows.Count > 0)
            {
                db.ExecuteNonQuery("delete from itemconfig");
            }
            db.Insert("itemconfig", dic);
            dic = new Dictionary <string, string>();


            dic.Add("formtype", vGridControl2.Rows["editorRow1"].Properties.Value.ToString());
            dic.Add("billlock", vGridControl2.Rows["editorRow2"].Properties.Value.ToString() == "ทำงาน" ? "1" : "0");
            dic.Add("saleprice", vGridControl2.Rows["editorRow3"].Properties.Value.ToString());
            dic.Add("costprice", vGridControl2.Rows["editorRow4"].Properties.Value.ToString());
            dic.Add("gp", vGridControl2.Rows["editorRow5"].Properties.Value.ToString());
            dic.Add("autopurch", vGridControl2.Rows["row5"].Properties.Value.ToString() == "ทำงาน" ? "1" : "0");
            dic.Add("docno", vGridControl2.Rows["row7"].Properties.Value.ToString());
            dic.Add("customer", vGridControl2.Rows["row8"].Properties.Value.ToString());

            if (dsale.Rows.Count > 0)
            {
                db.ExecuteNonQuery("delete from saleconfig");
            }
            db.Insert("saleconfig", dic);
            dic = new Dictionary <string, string>();
            if (vGridControl1.Rows["row"].Properties.Value == null)
            {
                dic.Add("companyname", "");
            }
            else
            {
                dic.Add("companyname", vGridControl1.Rows["row"].Properties.Value.ToString());
            }
            if (vGridControl1.Rows["row1"].Properties.Value == null)
            {
                dic.Add("address", "");
            }
            else
            {
                dic.Add("address", vGridControl1.Rows["row1"].Properties.Value.ToString());
            }
            // = dconfig.Rows[0]["address"].ToString();
            if (vGridControl1.Rows["row2"].Properties.Value == null)
            {
                dic.Add("telephone", "");
            }
            else
            {
                dic.Add("telephone", vGridControl1.Rows["row2"].Properties.Value.ToString());
            }
            if (vGridControl1.Rows["row3"].Properties.Value == null)
            {
                dic.Add("province", "");
            }
            else
            {
                dic.Add("province", vGridControl1.Rows["row3"].Properties.Value.ToString());
            }
            if (vGridControl1.Rows["row4"].Properties.Value == null)
            {
                dic.Add("taxid", "");
            }
            else
            {
                dic.Add("taxid", vGridControl1.Rows["row4"].Properties.Value.ToString());
            }
            if (vGridControl1.Rows["row6"].Properties.Value == null)
            {
                dic.Add("taxrate", "");
            }
            else
            {
                dic.Add("taxrate", vGridControl1.Rows["row6"].Properties.Value.ToString());
            }
            if (dconfig.Rows.Count > 0)
            {
                db.ExecuteNonQuery("delete from configuration");
            }

            db.Insert("configuration", dic);
            this.Close();
            this.DialogResult = DialogResult.OK;
        }
Beispiel #17
0
 public long Insert(string tableName, ContentValues contentValues)
 {
     return(db.Insert(tableName, null, contentValues));
 }
Beispiel #18
0
        private void SaveDataToLocalDataBase()
        {
            try
            {
                string   path       = CreateDirectoryForPictures();
                EditText txtproname = FindViewById <EditText>(Resource.Id.txtProjectName);

                EditText txtclientname = FindViewById <EditText>(Resource.Id.txtClientName);

                EditText txtlocation        = FindViewById <EditText>(Resource.Id.txtLocation);
                EditText img1path           = FindViewById <EditText>(Resource.Id.cam1path);
                EditText img2path           = FindViewById <EditText>(Resource.Id.cam2path);
                EditText img3path           = FindViewById <EditText>(Resource.Id.cam3path);
                EditText img4path           = FindViewById <EditText>(Resource.Id.cam4path);
                EditText txtItemDescription = FindViewById <EditText>(Resource.Id.txtItemDescription);
                EditText txtbrand           = FindViewById <EditText>(Resource.Id.txtBrand);
                EditText txtquantity        = FindViewById <EditText>(Resource.Id.txtQuantity);
                EditText txtModelNumber     = FindViewById <EditText>(Resource.Id.txtModelNumber);
                EditText txtUnitCost        = FindViewById <EditText>(Resource.Id.txtUnitCost);
                EditText txtNotes           = FindViewById <EditText>(Resource.Id.txtNotes);

                string projectname = txtproname.Text;
                string clientname  = txtclientname.Text;
                string location    = txtlocation.Text;
                Bitmap image1      = null;
                byte[] image1byte  = null;
                byte[] image2byte  = null;
                byte[] image3byte  = null;
                byte[] image4byte  = null;

                string description = txtItemDescription.Text;
                string brand       = txtbrand.Text;
                string quantity    = txtquantity.Text;
                string model       = txtModelNumber.Text;
                string unitcost    = txtUnitCost.Text;
                string notes       = txtNotes.Text;
                string dtnow       = DateTime.Now.ToString("MM-dd-yyyy HH:mm");

                //description=description.Replace("'","\'");
                //brand=brand.Replace("'","\'");
                //model=model.Replace("'","\'");
                //notes=notes.Replace("'","\'");
                //string img = img1.Background;
                //this.DeleteDatabase ("ImInventory");
                db = this.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                //db.ExecSQL("DROP TABLE IF EXISTS " + "tbl_ManualEntry");
                db.ExecSQL("CREATE TABLE IF NOT EXISTS "
                           + "tbl_Inventory"
                           + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,EmpID INTEGER,ProjectID VARCHAR,ProjectName VARCHAR, ClientName VARCHAR,Location VARCHAR, Image1 VARCHAR , Image2 VARCHAR, Image3 VARCHAR, Image4 VARCHAR," +
                           "ItemDescription VARCHAR, Brand VARCHAR, Quantity VARCHAR, ModelNumber VARCHAR, UnitCost VARCHAR, Notes VARCHAR , Addeddate VARCHAR,BarCodeNumber VARCHAR,AudioFileName VARCHAR,InventoryType VARCHAR" +
                           "" +
                           "" +
                           ");");

                ContentValues values = new ContentValues();
                values.Put("EmpID", empid);
                values.Put("ProjectID", projectid);
                values.Put("ProjectName", projectname);
                values.Put("ClientName", clientname);
                values.Put("Location", location);
                values.Put("AudioFileName", "");
                values.Put("Image1", img1path.Text);
                values.Put("Image2", img2path.Text);
                values.Put("Image3", img3path.Text);
                values.Put("Image4", img4path.Text);
                values.Put("ItemDescription", description);
                values.Put("Brand", brand);
                values.Put("Quantity", quantity);
                values.Put("ModelNumber", model);
                values.Put("UnitCost", unitcost);
                values.Put("BarCodeNumber", "");
                values.Put("Notes", notes);

                //db.ExecSQL("delete from "+ "tbl_ManualEntry");
                if (location.Trim() != "")
                {
                    if (description != "")
                    {
                        try{
                            if (quantity.Trim() != "")
                            {
                                if (unitcost == "")
                                {
                                    unitcost = "0";
                                }
                                if (EditInventoryID != "")
                                {
                                    db.Update("tbl_Inventory", values, "ID = " + EditInventoryID, null);
                                }
                                else
                                {
                                    // db.ExecSQL("INSERT INTO "
                                    //   + "tbl_Inventory"
                                    //	+ " (EmpID,ProjectID,ProjectName, ClientName,Location,Image1,Image2,Image3,Image4,ItemDescription,Brand,Quantity,ModelNumber,UnitCost,Notes,Addeddate,BarCodeNumber,AudioFileName,InventoryType)"
                                    //	+ " VALUES ('" + empid + "','" + projectid + "','" + projectname + "','" + clientname + "','" + location + "','" + img1path.Text + "','" + img2path.Text + "','" + img3path.Text + "','" + img4path.Text + "','" + description + "','" + brand + "','" + quantity + "','" + model + "','" + unitcost + "','" + notes + "','" + dtnow + "','" + "" + "','" + "" + "','1')");
                                    values.Put("InventoryType", "1");
                                    values.Put("Addeddate", dtnow);
                                    db.Insert("tbl_Inventory", null, values);
                                }



                                txtItemDescription.SetText("", TextView.BufferType.Editable);
                                txtbrand.SetText("", TextView.BufferType.Editable);
                                txtquantity.SetText("", TextView.BufferType.Editable);
                                txtModelNumber.SetText("", TextView.BufferType.Editable);
                                txtUnitCost.SetText("", TextView.BufferType.Editable);
                                txtNotes.SetText("", TextView.BufferType.Editable);

                                TextView lblCam1PicName = FindViewById <TextView>(Resource.Id.lblCam1PicName);
                                TextView lblCam2PicName = FindViewById <TextView>(Resource.Id.lblCam2PicName);
                                TextView lblCam3PicName = FindViewById <TextView>(Resource.Id.lblCam3PicName);
                                TextView lblCam4PicName = FindViewById <TextView>(Resource.Id.lblCam4PicName);

                                lblCam1PicName.SetText("", TextView.BufferType.Editable);
                                lblCam2PicName.SetText("", TextView.BufferType.Editable);
                                lblCam3PicName.SetText("", TextView.BufferType.Editable);
                                lblCam4PicName.SetText("", TextView.BufferType.Editable);

                                Cam1.SetImageDrawable(null);
                                Cam2.SetImageDrawable(null);
                                Cam3.SetImageDrawable(null);
                                Cam4.SetImageDrawable(null);


                                Cam1.SetBackgroundResource(Resource.Drawable.icon_camera2x);
                                Cam2.SetBackgroundResource(Resource.Drawable.icon_camera2x);
                                Cam3.SetBackgroundResource(Resource.Drawable.icon_camera2x);
                                Cam4.SetBackgroundResource(Resource.Drawable.icon_camera2x);
                                img1path.SetText("", TextView.BufferType.Editable);
                                img2path.SetText("", TextView.BufferType.Editable);
                                img3path.SetText("", TextView.BufferType.Editable);
                                img4path.SetText("", TextView.BufferType.Editable);

                                Toast.MakeText(this, "Data saved successfully", ToastLength.Long).Show();
                                EditInventoryID = "";
                                editor          = prefs.Edit();
                                editor.PutString("EditFromItemList", "");
                                editor.Commit();
                                editor.Apply();
                            }
                            else
                            {
                                Toast.MakeText(this, "Please enter quantity", ToastLength.Long).Show();
                            }
                        }
                        catch (Exception ex) {
                        }
                    }
                    else
                    {
                        Toast.MakeText(this, "Please enter description", ToastLength.Long).Show();
                    }
                }

                //txtlocation.SetText ("", TextView.BufferType.Editable);

                if (location.Trim() != "")
                {
                }
                else
                {
                    Toast.MakeText(this, "Please enter location name", ToastLength.Long).Show();
                }
            }
            catch (Exception ex)
            {
            }
        }
 private void button_Click(object sender, RoutedEventArgs e)
 {
     var db = new SQLiteDatabase();
     Dictionary<String, String> data = new Dictionary<String, String>();
     data.Add("NAME", nameTextBox.Text);
     data.Add("CLIP", clipBoardTB.Text);
     try
     {
         db.Insert("clipboard", data);
     }
     catch (Exception crap)
     {
         MessageBox.Show(crap.Message);
     }
 }
        public long CreateFile(IOConnectionInfo ioc, String keyFile)
        {
            // Check to see if this filename is already used
            ICursor cursor;

            try {
                cursor = mDb.Query(true, FileTable, new[] { KeyFileId },
                                   KeyFileFilename + "=?", new[] { ioc.Path }, null, null, null, null);
            } catch (Exception) {
                return(-1);
            }

            IOConnectionInfo iocToStore = ioc.CloneDeep();

            if (ioc.CredSaveMode != IOCredSaveMode.SaveCred)
            {
                iocToStore.Password = "";
            }
            if (ioc.CredSaveMode == IOCredSaveMode.NoSave)
            {
                iocToStore.UserName = "";
            }

            iocToStore.Obfuscate(true);

            long result;

            // If there is an existing entry update it
            if (cursor.Count > 0)
            {
                cursor.MoveToFirst();
                long id = cursor.GetLong(cursor.GetColumnIndexOrThrow(KeyFileId));

                var vals = new ContentValues();
                vals.Put(KeyFileKeyfile, keyFile);
                vals.Put(KeyFileUpdated, Java.Lang.JavaSystem.CurrentTimeMillis());

                vals.Put(KeyFileUsername, iocToStore.UserName);
                vals.Put(KeyFilePassword, iocToStore.Password);
                vals.Put(KeyFileCredsavemode, (int)iocToStore.CredSaveMode);

                result = mDb.Update(FileTable, vals, KeyFileId + " = " + id, null);

                // Otherwise add the new entry
            }
            else
            {
                var vals = new ContentValues();
                vals.Put(KeyFileFilename, ioc.Path);
                vals.Put(KeyFileKeyfile, keyFile);
                vals.Put(KeyFileUsername, iocToStore.UserName);
                vals.Put(KeyFilePassword, iocToStore.Password);
                vals.Put(KeyFileCredsavemode, (int)iocToStore.CredSaveMode);
                vals.Put(KeyFileUpdated, Java.Lang.JavaSystem.CurrentTimeMillis());

                result = mDb.Insert(FileTable, null, vals);
            }
            // Delete all but the last five records
            try {
                DeleteAllBut(MaxFiles);
            } catch (Exception ex) {
                Android.Util.Log.Error("ex", ex.StackTrace);
            }

            cursor.Close();

            return(result);
        }
Beispiel #21
0
 public static long insert(this SQLiteDatabase db, string table, string nullColumnHack, ContentValues values)
 {
     return(db.Insert(table, nullColumnHack, values));
 }
Beispiel #22
0
 public void SaveMeasuringToSQLite(string prefix, string numOfTemplate, string number, string lbs)
 {
     // Сохранение результатов измерений
     db = new SQLiteDatabase();
     Dictionary<String, String> data = new Dictionary<String, String>();
     //data.Add("num_of_measurement", "1");
     data.Add("name_of_measurement ", prefix);
     data.Add("num_of_settings_template ", numOfTemplate);
     data.Add("date", DateTime.Now.ToString());
     data.Add("path", lbs + prefix + "_" + number + ".xls");
     try
     {
         db.Insert("measurement_results", data);
     }
     catch (Exception crap)
     {
         MessageBox.Show(crap.Message);
     }
 }
Beispiel #23
0
        public void putRecord(long time, String difficulty, Context context)
        {
            dbHelper = new DBHelper(context);
            ContentValues  cv    = new ContentValues();
            SQLiteDatabase db    = dbHelper.WritableDatabase;
            SQLiteCursor   c     = (SQLiteCursor)db.Query("records", null, " difficulty = ?", new String[] { difficulty }, null, null, null);
            int            count = 1;

            if (c.MoveToFirst())
            {
                int idColIndex   = c.GetColumnIndex("id");
                int timeColIndex = c.GetColumnIndex("time");

                int maxDBindex = c.GetInt(idColIndex);
                int maxDBtime  = c.GetInt(timeColIndex);
                count++;
                while (c.MoveToNext())
                {
                    if (c.GetInt(timeColIndex) > maxDBtime)
                    {
                        maxDBtime  = c.GetInt(timeColIndex);
                        maxDBindex = c.GetInt(idColIndex);
                    }
                    count++;
                }
                if (count == 6)
                {
                    if (time < maxDBtime)
                    {
                        db.Delete("records", " id = ?", new String[] { maxDBindex + "" });
                    }
                    else
                    {
                        c.Close();
                        db.Close();
                        return;
                    }
                }
            }
            cv.Put("time", time);
            cv.Put("difficulty", difficulty);
            db.Insert("records", null, cv);
            cv.Clear();

            SQLiteCursor gc = (SQLiteCursor)db.Query("general", null, "difficulty = ?", new String[] { difficulty }, null, null, null);

            gc.MoveToFirst();
            int avgTimeColIndex    = gc.GetColumnIndex("avgTime");
            int gamesCountColIndex = gc.GetColumnIndex("gamesCount");
            int avgTime            = 0;
            int gamesCount         = 0;

            if (gc.MoveToFirst())
            {
                avgTime    = gc.GetInt(avgTimeColIndex);
                gamesCount = gc.GetInt(gamesCountColIndex);
            }
            int newGamesCount = gamesCount + 1;
            int newAvgTime    = (avgTime * gamesCount / newGamesCount) + (int)(time / newGamesCount);

            cv.Put("difficulty", difficulty);
            cv.Put("avgTime", newAvgTime);
            cv.Put("gamesCount", newGamesCount);
            db.Delete("general", " difficulty = ?", new String[] { difficulty });
            db.Insert("general", null, cv);
            db.Close();
            c.Close();
            gc.Close();
        }
Beispiel #24
0
        public bool Save()
        {
            SQLiteDatabase sqlDatabase = null;

            try
            {
                Globals dbHelp = new Globals();
                dbHelp.OpenDatabase();
                sqlDatabase = dbHelp.GetSQLiteDatabase();
                if (sqlDatabase != null)
                {
                    if (sqlDatabase.IsOpen)
                    {
                        if (IsNew)
                        {
                            Log.Info(TAG, "Save: New Medication item to Save...");
                            ContentValues values = new ContentValues();
                            values.Put("MedicationName", MedicationName.Trim());
                            values.Put("TotalDailyDosage", TotalDailyDosage);
                            ID = (int)sqlDatabase.Insert("Medication", null, values);
                            Log.Info(TAG, "Save: Successfully saved - ID - " + ID.ToString());
                            IsNew   = false;
                            IsDirty = false;
                            if (MedicationSpread != null && MedicationSpread.Count > 0)
                            {
                                foreach (var spread in MedicationSpread)
                                {
                                    spread.Save(spread.ID, ID);
                                    Log.Info(TAG, "Save (insert): Saved Medication Spread with ID - " + spread.ID.ToString());
                                }
                            }
                            if (PrescriptionType != null)
                            {
                                PrescriptionType.Save(ID);
                                Log.Info(TAG, "Save (insert): Saved Prescription Type ID - " + ID.ToString());
                            }
                        }
                        if (IsDirty)
                        {
                            Log.Info(TAG, "LoadMedicationSpreads: Exisitng Medication to Update with ID - " + ID.ToString());
                            ContentValues values = new ContentValues();
                            values.Put("MedicationName", MedicationName.Trim());
                            values.Put("TotalDailyDosage", TotalDailyDosage);
                            string whereClause = "ID = ?";
                            sqlDatabase.Update("Medication", values, whereClause, new string[] { ID.ToString() });
                            Log.Info(TAG, "Save (update): Updated Medication with ID - " + ID.ToString());
                            IsDirty = false;
                            if (MedicationSpread != null && MedicationSpread.Count > 0)
                            {
                                foreach (var spread in MedicationSpread)
                                {
                                    spread.Save(spread.ID, ID);
                                    Log.Info(TAG, "Save (update): Saved Medication Spread with ID - " + spread.ID.ToString());
                                }
                            }
                            if (PrescriptionType != null)
                            {
                                PrescriptionType.Save(ID);
                                Log.Info(TAG, "Save (Update): Saved Prescription type with ID - " + PrescriptionType.ID.ToString());
                            }
                        }
                        sqlDatabase.Close();
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
                Log.Error(TAG, "Save: Exception - " + e.Message);
                if (sqlDatabase != null && sqlDatabase.IsOpen)
                {
                    sqlDatabase.Close();
                }
                return(false);
            }
        }
 


 public void insertVendorInfo(String ivvname, String ivaddr, String ivemail, String ivpn, int ivimg, String ivt1, String ivt2, String ivt3, String ivt4, String ivt5, String ivt6, String ivt7, String ivt8, String ivt9, String ivt10, String ivt11, String ivt12, String ivt13, String ivt14) 

 {
     

 var contentData = new ContentValues(); 

 contentData.Put(vvname, ivvname); 
 contentData.Put(vaddr, ivaddr); 
 contentData.Put(vemail, ivemail); 
 contentData.Put(vpn, ivpn); 
 contentData.Put(vimg, ivimg); 
 contentData.Put(vt1, ivt1); 
 contentData.Put(vt2, ivt2); 
 contentData.Put(vt3, ivt3); 
 contentData.Put(vt4, ivt4); 
 contentData.Put(vt5, ivt5); 
 contentData.Put(vt6, ivt6); 
 contentData.Put(vt7, ivt7); 
 contentData.Put(vt8, ivt8); 
 contentData.Put(vt9, ivt9); 
 contentData.Put(vt10, ivt10); 
 contentData.Put(vt11, ivt11); 
 contentData.Put(vt12, ivt12); 
 contentData.Put(vt13, ivt13); 
 contentData.Put(vt14, ivt14); 
 db.Insert(table_Vendors, null, contentData); 

 }
Beispiel #26
0
        public void Save(SQLiteDatabase sqLiteDatabase)
        {
            if (sqLiteDatabase.IsOpen)
            {
                if (IsNew)
                {
                    try
                    {
                        ContentValues values = new ContentValues();
                        values.Put("AppointmentDate", string.Format("{0:yyyy-MM-dd HH:mm:ss}", AppointmentDate));
                        values.Put("AppointmentType", AppointmentType);
                        values.Put("Location", Location.Trim());
                        values.Put("WithWhom", WithWhom.Trim());
                        values.Put("AppointmentTime", string.Format("{0:yyyy-MM-dd HH:mm:ss}", AppointmentTime));
                        values.Put("Notes", Notes.Trim());
                        AppointmentID = (int)sqLiteDatabase.Insert("Appointments", null, values);

                        IsNew   = false;
                        IsDirty = false;
                    }
                    catch (Exception newE)
                    {
                        throw new Exception("Unable to Save Appointment - " + newE.Message);
                    }
                }

                if (IsDirty)
                {
                    try
                    {
                        string        whereClause = "AppointmentID = " + AppointmentID;
                        ContentValues values      = new ContentValues();

                        values.Put("AppointmentDate", string.Format("{0:yyyy-MM-dd HH:mm:ss}", AppointmentDate));
                        values.Put("AppointmentType", AppointmentType);
                        values.Put("Location", Location.Trim());
                        values.Put("WithWhom", WithWhom.Trim());
                        values.Put("AppointmentTime", string.Format("{0:yyyy-MM-dd HH:mm:ss}", AppointmentTime));
                        values.Put("Notes", Notes.Trim());
                        sqLiteDatabase.Update("Appointments", values, whereClause, null);

                        IsDirty = false;
                    }
                    catch (SQLException dirtyE)
                    {
                        throw new Exception("Unable to Update Appointment Question - " + dirtyE.Message);
                    }
                }

                if (_questions.Count > 0)
                {
                    foreach (var question in _questions)
                    {
                        if (question.IsNew || question.IsDirty)
                        {
                            if (sqLiteDatabase.IsOpen)
                            {
                                if (question.IsNew)
                                {
                                    question.AppointmentID = AppointmentID;
                                }
                                question.Save(sqLiteDatabase);
                            }
                        }
                    }
                }
            }
        }
Beispiel #27
0
        static void Main(string[] args)
        {
            // Initialize the Chrome Driver

            using (var driver = new ChromeDriver())
            {
                // Go to the home page
                driver.Navigate().GoToUrl("http://www.amazon.com/s/ref=lp_2368343011_nr_n_0?rh=n%3A1036592%2Cn%3A%211036682%2Cn%3A1040660%2Cn%3A2368343011%2Cn%3A2368365011&bbn=2368343011&ie=UTF8&qid=1397584947&rnid=2368343011");

                bool pagnNextLink = true;
                #region sample to input a form
                // Get User Name field, Password field and Login Button
                //var userNameField = driver.FindElementById("usr");
                //var userPasswordField = driver.FindElementById("pwd");
                //var loginButton = driver.FindElementByXPath("//input[@value='Login']");

                //// Type user name and password
                //userNameField.SendKeys("admin");
                //userPasswordField.SendKeys("12345");

                //// and click the login button
                //loginButton.Click();
                #endregion

                ReadOnlyCollection <IWebElement> products = driver.FindElementsByClassName("newaps");

                SQLiteDatabase db = new SQLiteDatabase();
                db.ExecuteNonQuery(@"CREATE TABLE IF NOT EXISTS products (id integer primary key, 
                            product varchar(1024), url varchar(1024), price varchar(16), sku varchar(64), description,
                            attribute_key_value_json varchar(2048) , crawled_on datetime

                    )");
                int   page           = 1;
                Int64 total_products = 0;
                total_products += products.Count;

                Console.WriteLine("---------------------------------------------");
                Console.WriteLine("------------------- Page {0} , Products in page {1}, Total Products {2} ", page, products.Count, total_products);
                Console.WriteLine("---------------------------------------------");


                do
                {
                    int index = 0;
                    foreach (IWebElement product in products)
                    {
                        IList <IWebElement> prices = (IList <IWebElement>)driver.FindElementsByCssSelector(".bld.lrg.red,.price.bld");
                        IList <IWebElement> names  = (IList <IWebElement>)driver.FindElementsByCssSelector(".prod.celwidget");
                        IWebElement         anchor = product.FindElement(By.TagName("a"));

                        Dictionary <String, String> data = new Dictionary <String, String>();

                        data.Add("product", product.Text.Replace("'", "''"));
                        data.Add("price", prices[index].Text.Replace("'", "''"));
                        data.Add("sku", names[index].GetAttribute("name").Replace("'", "''"));
                        data.Add("url", anchor.GetAttribute("href").Replace("'", "''"));

                        db.Insert("products", data);
                        Console.WriteLine(names[index].GetAttribute("name").Replace("'", "''"));

                        index++;
                    }
                    total_products += products.Count;
                    if (driver.FindElementById("pagnNextLink") != null)
                    {
                        //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(10));
                        string _nextUrl = driver.FindElementById("pagnNextLink").GetAttribute("href");
                        driver.Navigate().GoToUrl(_nextUrl);


                        products = null;
                        products = driver.FindElementsByClassName("newaps");
                        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                        wait.Until(i => i.FindElement(By.Id("footer")));
                        page++;
                    }
                    else
                    {
                        pagnNextLink = false;
                    }

                    Console.WriteLine("---------------------------------------------");
                    Console.WriteLine("------------------- Page {0} , Products in page {1}, Total Products {2} ", page, products.Count, total_products);
                    Console.WriteLine("---------------------------------------------");
                }while (pagnNextLink);



                Console.WriteLine("Total products : {0},", products.Count);



                // Extract resulting message and save it into result.txt
                //var result = driver.FindElementByXPath("//div[@id='case_login']/h3").Text;
                //sFile.WriteAllText("result.txt", result);

                // Take a screenshot and save it into screen.png
                //driver.GetScreenshot().SaveAsFile(@"screen.png", ImageFormat.Png);
            }
            Console.ReadKey();
        }