예제 #1
0
 public int Getint()
 {
     if (reader.HasRows)
     {
         while (reader.Read())
         {
             if (reader?.GetInt32(0) == null)
             {
                 return(0);
             }
             else
             {
                 return(reader.GetInt32(0));
             }
         }
         reader.Close();
     }
     else
     {
         reader.Close();
         return(0);
     }
     return(0);
 }
    //permet de recuperer tous les reservations d'un client à partir d'une adresseMail
    public static List <Reservation> getReservationClient(string adresseMail)
    {
        List <Reservation> reservations = new List <Reservation>();

        conn.Open();
        MySqlCommand query = new MySqlCommand("select * from ladi.DSMSreservation r,ladi.DSMSpersonne p  where r.idClient=p.idPersonne and r.realisee=0 and p.adresseMail=@adresseMail", conn);

        query.Parameters.AddWithValue("@adresseMail", adresseMail);

        using (MySqlDataReader reader = query.ExecuteReader())
        {
            while (reader.Read())
            {
                reservations.Add(new Reservation(ControleurClient.getClient(adresseMail), ControleurMoniteur.getMoniteur(reader.GetInt32(2)), ControleurVehicule.getVehicule(reader.GetInt32(3)), Outils.convertirStringToDateTime(reader.GetString(4))));
            }
        }

        conn.Close();
        Console.WriteLine("reservations");
        return(reservations);
    }
예제 #3
0
        private void button12_Click(object sender, EventArgs e)
        {
            string _in = "", _srok = "";

            if (_id == 0)
            {
                MessageBox.Show("Сначала выберите помещение");
                return;
            }
            Client w = new Client(sconnect);

            try
            {
                mconnect.Open();
                cmd[0]             = new MySqlCommand();
                cmd[0].Connection  = mconnect;
                cmd[0].CommandText = "SELECT Facility FROM SaleDocument WHERE SaleDocument.Facility = @id";
                cmd[0].Parameters.AddWithValue("@id", _id);
                rdr = cmd[0].ExecuteReader();
                int _sale = 0;
                while (rdr.Read())
                {
                    _sale = rdr.GetInt32(0);
                }
                rdr.Close();
                cmd[0].CommandText = "SELECT household FROM facility WHERE facility.idfacility = @id";
                rdr = cmd[0].ExecuteReader();
                int _hos = 0;
                while (rdr.Read())
                {
                    _hos = rdr.GetInt32(0);
                }
                rdr.Close();
                if (_sale == _id)
                {
                    MessageBox.Show("Это помещение уже продано!");
                }
                else
                {
                    w.ShowDialog();
                    if (w.DialogResult == DialogResult.OK)
                    {
                        w.get_data(out _in, out _srok);
                        if (Convert.ToInt32(_in) == _hos)
                        {
                            MessageBox.Show("Ошибка, выбранный клиент и владелец - один и тот же человек");
                        }
                        else
                        {
                            cmd[1]             = new MySqlCommand();
                            cmd[1].Connection  = mconnect;
                            cmd[1].CommandText = @"REPLACE INTO SaleDocument(idSaleDocument, Saler, Client, Facility, Date)
                                      VALUES(
                                            @idDoc,
                                            @Sl,
                                            @Cl,
                                            @Fac,
                                            @Dat)";
                            cmd[1].Parameters.AddWithValue("@idDoc", KEY_GEN("SELECT idSaleDocument FROM SaleDocument"));
                            cmd[1].Parameters.AddWithValue("@Sl", _hos);
                            cmd[1].Parameters.AddWithValue("@Cl", Convert.ToInt32(_in));
                            cmd[1].Parameters.AddWithValue("@Fac", _id);
                            cmd[1].Parameters.AddWithValue("@Dat", DateTime.Today);
                            cmd[1].ExecuteNonQuery();
                            cmd[1].CommandText = @"UPDATE facility SET household=@Cl WHERE facility.idfacility=@Fac";
                            cmd[1].ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            if (mconnect != null)
            {
                mconnect.Close();
            }
        }
예제 #4
0
        private void button5_Click(object sender, EventArgs e)
        {
            string uno = "", use = "", rprice = "",
                   sprice = "", sq = "", usq = "",
                   rooms = "", housenum = "", dis = "", str = "";

            if (_inn == 0)
            {
                MessageBox.Show("Сначала выберите владельца!");
            }
            else
            {
                try
                {
                    AddFacility w = new AddFacility();
                    w.ShowDialog();
                    if (w.DialogResult == DialogResult.OK)
                    {
                        string s       = "";
                        bool   samestr = false,
                               samedis = false,
                               samenum = false;
                        w.get_data(out uno, out use, out rprice, out sprice, out sq, out usq, out rooms, out housenum, out dis, out str);
                        mconnect.Open();
                        cmd[1]            = new MySqlCommand();
                        cmd[1].Connection = mconnect;
                        cmd[0]            = new MySqlCommand();
                        cmd[0].Connection = mconnect;
                        cmd[0].Prepare();
                        cmd[0].CommandText = @"SELECT Street FROM Streets";
                        rdr = cmd[0].ExecuteReader();
                        while (rdr.Read() && !samestr)
                        {
                            s = rdr.GetString(0);
                            if (s == str)
                            {
                                samestr = true;
                            }
                        }
                        rdr.Close();
                        if (samestr == false)
                        {
                            cmd[0].CommandText = @"INSERT INTO Streets(Street)
                                    VALUES(
                                            @str)";
                            cmd[0].Parameters.AddWithValue("@str", str);
                            cmd[0].Prepare();
                            cmd[0].ExecuteNonQuery();
                        }

                        cmd[2]            = new MySqlCommand();
                        cmd[2].Connection = mconnect;
                        cmd[2].Prepare();
                        cmd[2].CommandText = @"SELECT District FROM Districts";
                        rdr = cmd[2].ExecuteReader();
                        while (rdr.Read() && !samedis)
                        {
                            s = rdr.GetString(0);
                            if (s == dis)
                            {
                                samedis = true;
                            }
                        }
                        rdr.Close();
                        if (samedis == false)
                        {
                            cmd[2].CommandText = @"INSERT INTO Districts(District)
                                    VALUES(
                                            @dis)";
                            cmd[2].Parameters.AddWithValue("@dis", dis);
                            cmd[2].Prepare();
                            cmd[2].ExecuteNonQuery();
                        }
                        if (samestr && samedis)
                        {
                            cmd[2].Prepare();
                            cmd[2].CommandText = @"SELECT * FROM HouseNumber";
                            rdr = cmd[2].ExecuteReader();
                            while (rdr.Read() && !samenum)
                            {
                                s = rdr.GetString(3);
                                if (s == housenum)
                                {
                                    samenum = true;
                                }
                            }
                            rdr.Close();
                        }
                        if (!samenum)
                        {
                            _idhouse           = KEY_GEN(@"SELECT idHouseNumber FROM HouseNumber");
                            cmd[3]             = new MySqlCommand();
                            cmd[3].Connection  = mconnect;
                            cmd[3].CommandText = @"INSERT INTO HouseNumber(idHouseNumber, District_h, Street_h, Number)
                                    VALUES(
                                            @idHN,
                                            @dis,
                                            @str,
                                            @housenum)";
                            cmd[3].Prepare();
                            cmd[3].Parameters.AddWithValue("@idHN", _idhouse);
                            cmd[3].Parameters.AddWithValue("@dis", dis);
                            cmd[3].Parameters.AddWithValue("@str", str);
                            cmd[3].Parameters.AddWithValue("@housenum", housenum);
                            cmd[3].ExecuteNonQuery();
                        }
                        if (samenum)
                        {
                            cmd[3]            = new MySqlCommand();
                            cmd[3].Connection = mconnect;
                            cmd[3].Prepare();
                            cmd[3].CommandText = @"SELECT idHouseNumber FROM HouseNumber WHERE HouseNumber.District_h = @dis AND HouseNumber.Street_h = @str AND HouseNumber.Number = @housenum";
                            cmd[3].Parameters.AddWithValue("@dis", dis);
                            cmd[3].Parameters.AddWithValue("@str", str);
                            cmd[3].Parameters.AddWithValue("@housenum", housenum);
                            rdr = cmd[3].ExecuteReader();
                            while (rdr.Read())
                            {
                                _idhouse = rdr.GetInt32(0);
                            }
                            rdr.Close();
                        }
                        cmd[1].CommandText = @"INSERT INTO facility(numb, usag, RentPrice, SalePrice, Square, UsefulSquare, NumOfRooms, household, house, idfacility)
                                    VALUES(
                                            @uno,
                                            @use,
                                            @rprice,
                                            @sprice,
                                            @sq,
                                            @usq,
                                            @rooms,
                                            @inn,
                                            @idHN,
                                            @k)";
                        cmd[1].Prepare();
                        cmd[1].Parameters.AddWithValue("@uno", uno);
                        cmd[1].Parameters.AddWithValue("@use", use);
                        cmd[1].Parameters.AddWithValue("@rprice", rprice);
                        cmd[1].Parameters.AddWithValue("@sprice", sprice);
                        cmd[1].Parameters.AddWithValue("@sq", sq);
                        cmd[1].Parameters.AddWithValue("@usq", usq);
                        cmd[1].Parameters.AddWithValue("@rooms", rooms);
                        cmd[1].Parameters.AddWithValue("@inn", _inn);
                        cmd[1].Parameters.AddWithValue("@idHN", _idhouse);
                        cmd[1].Parameters.AddWithValue("@k", KEY_GEN(@"SELECT idfacility FROM facility"));
                        cmd[1].ExecuteNonQuery();

                        stm               = "SELECT * FROM facility WHERE facility.household = @inn";
                        cmd[0]            = new MySqlCommand(stm);
                        cmd[0].Connection = mconnect;
                        cmd[0].Prepare();
                        cmd[0].Parameters.AddWithValue("@inn", _inn);
                        da[1] = new MySqlDataAdapter(cmd[0]);
                        ds[1].Clear();
                        da[1].Fill(ds[1], "facility");
                        dataGridView2.DataSource = ds[1].Tables["facility"];
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                if (mconnect != null)
                {
                    mconnect.Close();
                }
            }
        }
예제 #5
0
        private void bookCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    con.Close();
                    string book_code = bookCode.Text;
                    if (!book_code.Equals(""))
                    {
                        try
                        {
                            string query = "SELECT * FROM `book` WHERE `id`='" + book_code + "'";
                            using (command = new MySqlCommand(query, con))
                            {
                                con.Open();
                                reader = command.ExecuteReader();
                                if (reader.Read())
                                {
                                    int          book_no   = reader.GetInt32("id");
                                    string       bname     = firstCharToUpper(reader.GetString("name"));
                                    string       btailbar  = firstCharToUpper(reader.GetString("tailbar"));
                                    int          book_year = reader.GetInt32("year");
                                    byte[]       rawData;
                                    MemoryStream ms;
                                    int          FileSize;
                                    Bitmap       outImage;
                                    FileSize = 10485760;
                                    //FileSize =reader.GetUInt32(reader.GetOrdinal("image"));
                                    rawData = new byte[FileSize];
                                    reader.GetBytes(reader.GetOrdinal("image"), 0, rawData, 0, (int)FileSize);

                                    ms       = new MemoryStream(rawData);
                                    outImage = new Bitmap(ms);
                                    dataGridRent.Rows.Add(book_no, bname, book_year, outImage);

                                    //if (num < userIndex)
                                    //{
                                    //    dataGridRent.Rows.Add(book_no, bname, book_year,outImage);
                                    //    Console.WriteLine("DataGridBook: " + book_no);
                                    //    row[num] = book_no;
                                    //    num++;
                                    //}
                                    //else
                                    //{
                                    //    MessageBox.Show(user_type + " нэг дор " + userIndex + "ш ном авах боломжтой!", "Анхаар!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    //}
                                }
                                con.Close();
                            }
                        }
                        catch (MySqlException ex)
                        {
                            showMessage("Book get data: " + ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    showMessage("Book code: " + ex.Message);
                }
            }
        }
예제 #6
0
        public List <Fornecedor> ListAll()
        {
            /* Recebe a conexão utilizada para acessar o Banco de Dados */

            Database        mercadoBD  = Database.GetInstance();
            MySqlConnection connection = mercadoBD.GetConnection();

            /* Lista de produtos */
            List <Fornecedor> listaFornecedor = new List <Fornecedor>();

            /* Preenchido com as informações do Banco de Dados */
            Fornecedor fornecedor;

            /* String que contém o SQL que será executado */
            string query = "SELECT * FROM Fornecedor";

            /* Responsável pelo comando SQL */
            MySqlCommand command = new MySqlCommand(query, connection);

            try
            {
                /* Abre a conexão */
                if (connection.State != System.Data.ConnectionState.Open)
                {
                    connection.Open();
                }

                /* Responsável pela leitura do Banco de Dados */
                MySqlDataReader dataReader = command.ExecuteReader();

                /* Lê todos os dados na tabela do Banco de Dados */
                while (dataReader.Read())
                {
                    fornecedor          = new Fornecedor();
                    fornecedor.Codigo   = dataReader.GetInt32(0);
                    fornecedor.Cnpj     = dataReader.GetString(1);
                    fornecedor.Nome     = dataReader.GetString(2);
                    fornecedor.Email    = dataReader.GetString(3);
                    fornecedor.Telefone = dataReader.GetString(4);
                    fornecedor.Rua      = dataReader.GetString(5);
                    fornecedor.Numero   = dataReader.GetInt32(6);
                    fornecedor.Cep      = dataReader.GetString(7);
                    fornecedor.Cidade   = dataReader.GetString(8);
                    fornecedor.Estado   = dataReader.GetString(9);

                    listaFornecedor.Add(fornecedor); /* Adiciona na lista */
                }
                dataReader.Close();
            }
            catch (Exception exception)
            {
                /* Se ocorrer alguma exceção mostra uma caixa de texto com o erro */
                MessageBox.Show(exception.ToString(), "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            finally
            {
                /* Fecha a conexão */
                connection.Close();
            }
            return(listaFornecedor); /* Retorna a lista */
        }
예제 #7
0
        private void WorkOrder_Load(object sender, EventArgs e)
        {
            try
            {
                label1.Text = "Сервіс:";
                label2.Text = "Пристрій:";
                label3.Text = "Серійний номер:";
                label4.Text = "Стан:";
                label5.Text = "Комплект:";
                label6.Text = "Опис:";


                MySqlCommand cmd2 = new MySqlCommand
                {
                    Connection  = conn,
                    CommandText = string.Format("SELECT Service.Service_name, Item.Item_name, Manufacturer.M_name, Model.Model_name, Serial.Serial_number, Orders.Appearance, Orders.Complete_set, Orders.Description, Status.Status_name FROM Orders INNER JOIN Service on(Orders.Service_id=Service.Service_id) INNER JOIN Status on(Orders.Status_id=Status.Status_id) INNER JOIN Serial on(Orders.Serial_number=Serial.Serial_number)  INNER JOIN Model on(Model.Model_id=Serial.Model_id) INNER JOIN Item on(Model.Item_id =Item.Item_id) INNER JOIN Manufacturer on(Manufacturer.M_id=Item.M_id) WHERE Orders.Order_id=" + Index + ";")
                };
                MySqlDataReader reader = cmd2.ExecuteReader();
                while (reader.Read())
                {
                    label7.Text       = reader.GetString(0);
                    label8.Text       = reader.GetString(1) + " " + reader.GetString(2) + " " + reader.GetString(3);
                    label9.Text       = reader.GetString(4);
                    label10.Text      = reader.GetString(5);
                    richTextBox1.Text = reader.GetString(6);
                    richTextBox2.Text = reader.GetString(7);
                    StatusName        = reader.GetString(8);
                    label13.Text      = StatusName;
                }
                reader.Close();

                if (label13.Text == "Order processing")
                {
                    label13.ForeColor = Color.Orange;
                }
                else if (label13.Text == "Complete")
                {
                    label13.ForeColor = Color.Green;
                }
                else if (label13.Text == "In the process of repair")
                {
                    label13.ForeColor = Color.Blue;
                }
                else if (label13.Text == "Purchase")
                {
                    label13.ForeColor = Color.Purple;
                }

                listBox1.Items.Clear();
                details.Clear();
                listBox1.Items.Add("Назва -> Країна виробник ->Ціна");
                cmd2 = new MySqlCommand
                {
                    Connection  = conn,
                    CommandText = string.Format("SELECT  Detail.Detail_name, Detail.Prod_country, Detail.Price, Detail.Detail_id FROM Detail INNER JOIN is_for on(Detail.Detail_id = is_for.Detail_id) WHERE is_for.Order_id =" + Index + ";")
                };
                reader = cmd2.ExecuteReader();
                while (reader.Read())
                {
                    listBox1.Items.Add(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2));
                    details.Add(reader.GetInt32(3));
                }
                reader.Close();

                id.Clear();
                price.Clear();
                comboBox1.Items.Clear();
                cmd2 = new MySqlCommand
                {
                    Connection  = conn,
                    CommandText = string.Format("SELECT Detail.Detail_id, Detail.Detail_name, Detail.Prod_country, Detail.Price FROM Detail INNER JOIN consist_of on (Detail.Detail_id = consist_of.Detail_id) INNER JOIN Model on(consist_of.Model_id=Model.Model_id) INNER JOIN Serial on(Model.Model_id = Serial.Model_id) INNER JOIN Orders on(Orders.Serial_number=Serial.Serial_number) WHERE Orders.Order_id=" + Index + ";")
                };
                reader = cmd2.ExecuteReader();
                while (reader.Read())
                {
                    bool flag = true;
                    for (int i = 0; i < details.Count; i++)
                    {
                        if (details[i] == reader.GetInt32(0))
                        {
                            flag = false;
                        }
                    }
                    if (flag)
                    {
                        comboBox1.Items.Add(reader.GetString(1) + " " + reader.GetString(2) + " " + reader.GetString(3));
                        id.Add(reader.GetInt32(0));
                        price.Add(reader.GetInt32(3));
                    }
                }
                reader.Close();
            }
            catch (Exception)
            {
            }
        }
예제 #8
0
        /// <summary>
        /// 根据 来访登记卡,查询来访纪录.  登记完用于显示
        /// </summary>
        /// <param name="card_no"></param>
        /// <returns></returns>
        public static flow_data_362 findByCardAndDate(string card_no)
        {
            flow_data_362 model;

            //并没有建立数据库连接
            MySqlConnection conn = new MySqlConnection(connectStr);

            try
            {
                conn.Open();                                                                                                                                            //建立连接,打开数据库
                card_no = card_no.Replace("'", "‘");                                                                                                                    //防一下sql注入

                string today = DateTime.Today.ToString("yyyy-MM-dd");                                                                                                   //日期格式要确保与mysql存储格式一致。

                string       sqlstr = "select * from flow_data_362 where data_44 = '" + card_no + "' and   left(data_6,10) = '" + today + "'  ORDER BY  run_id desc  "; //SQL语句
                MySqlCommand cmd    = new MySqlCommand(sqlstr, conn);

                //相当于数据读出流  理解为一本书
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())   //遍历表中数据,只取第一条记录
                {
                    //封装属性
                    model = new flow_data_362
                    {
                        #region 封装属性
                        id                  = reader.GetInt32("id"),
                        run_id              = reader.GetInt32("run_id"),
                        begin_time          = reader.GetDateTime("begin_time"),
                        begin_user          = reader.GetString("begin_user"),
                        data_10             = reader.GetString("data_10"),
                        data_11             = reader.GetString("data_11"),
                        data_12             = reader.GetString("data_12"),
                        data_13             = reader.GetString("data_13"),
                        data_14             = reader.GetString("data_14"),
                        data_15             = reader.GetString("data_15"),
                        data_16             = reader.GetString("data_16"),
                        data_17             = reader.GetString("data_17"),
                        data_18             = reader.GetString("data_18"),
                        data_19             = reader.GetString("data_19"),
                        data_20             = reader.GetString("data_20"),
                        data_21             = reader.GetString("data_21"),
                        data_22             = reader.GetString("data_22"),
                        data_22_key         = reader.GetString("data_22_key"),
                        data_23             = reader.GetString("data_23"),
                        data_24             = reader.GetString("data_24"),
                        data_25             = reader.GetString("data_25"),
                        data_27             = reader.GetString("data_27"),
                        data_29             = reader.GetString("data_29"),
                        data_31             = reader.GetString("data_31"),
                        data_32             = reader.GetString("data_32"),
                        data_33             = reader.GetString("data_33"),
                        data_36             = reader.GetString("data_36"),
                        data_38             = reader.GetString("data_38"),
                        data_4              = reader.GetString("data_4"),
                        data_40             = reader.GetString("data_40"),
                        data_41             = reader.GetString("data_41"),
                        data_43             = reader.GetString("data_43"),
                        data_44             = reader.GetString("data_44"),
                        data_45             = reader.GetString("data_45"),
                        data_5              = reader.GetString("data_5"),
                        data_6              = reader.GetString("data_6"),
                        data_8              = reader.GetString("data_8"),
                        data_9              = reader.GetString("data_9"),
                        flow_auto_num       = reader.GetInt32("flow_auto_num"),
                        flow_auto_num_month = reader.GetInt32("flow_auto_num_month"),
                        flow_auto_num_year  = reader.GetInt32("flow_auto_num_year"),
                        run_name            = reader.GetString("run_name")
                                              #endregion
                    };
                }
                else
                {
                    model = null;
                }
                if (!reader.IsClosed)
                {
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(null);
            }
            finally
            {
                conn.Close();   //关闭连接
            }

            return(model);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            MySqlConnection sqlcon = new MySqlConnection(@"server=localhost;user id=root;database=seproject;password=rootpassword");
            MySqlCommand    cmd    = null;
            MySqlDataReader reader = null;

            try
            {
                string sql = "SELECT inGameCurrency FROM seproject.user WHERE username = '******';";

                //sqlcon = new MySqlConnection(Properties.Settings.Default.ConnectionString);
                cmd = new MySqlCommand(sql, sqlcon);

                sqlcon.Open();

                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    val1 = reader.GetInt32("inGameCurrency");
                    //lblContinent.Text = reader.GetInt32("continent");
                    //lblRegion.Text = reader.GetString("region");
                    //lblSurfaceArea.Text = string.Format("{0:0.00}", reader.GetFloat("surfacearea"));
                }
                Console.WriteLine(val1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("An error occurred {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (sqlcon != null)
                {
                    sqlcon.Close();
                }
            }
            try
            {
                string sql = "SELECT realCurrency FROM seproject.user WHERE username = '******';";

                //sqlcon = new MySqlConnection(Properties.Settings.Default.ConnectionString);
                cmd = new MySqlCommand(sql, sqlcon);

                sqlcon.Open();

                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    val2 = reader.GetInt32("realCurrency");
                    //lblContinent.Text = reader.GetInt32("continent");
                    //lblRegion.Text = reader.GetString("region");
                    //lblSurfaceArea.Text = string.Format("{0:0.00}", reader.GetFloat("surfacearea"));
                }
                Console.WriteLine(val2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("An error occurred {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (sqlcon != null)
                {
                    sqlcon.Close();
                }
            }
            MessageBox.Show("Your coins: " + coins.ToString());
            sum1 = val1 + coins;
            sum2 = val2 + tokens;
            try
            {
                sqlcon.Open();

                string          Query1    = "update seproject.user set inGameCurrency = " + "'" + coins + "' where (username = '******');";
                MySqlCommand    cmdInsert = new MySqlCommand(Query1, sqlcon);
                MySqlDataReader reader1   = cmdInsert.ExecuteReader();
                MessageBox.Show("Saved");
                while (reader1.Read())
                {
                }

                //sqlcon.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Insertion failed");
            }
            finally
            {
                sqlcon.Close();
            }
            MessageBox.Show("Your tokens: " + tokens.ToString());
            try
            {
                sqlcon.Open();

                string          Query2     = "update seproject.user set realCurrency = " + "'" + tokens + "' where (username = '******');";
                MySqlCommand    cmdInsert1 = new MySqlCommand(Query2, sqlcon);
                MySqlDataReader reader2    = cmdInsert1.ExecuteReader();
                MessageBox.Show("Saved");
                while (reader2.Read())
                {
                }
                sqlcon.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Insertion failed");
            }
            finally
            {
                sqlcon.Close();
            }
            this.Hide();
            WheelForm wf = new WheelForm(MyVal);

            wf.ShowDialog();
        }
예제 #10
0
        public void LoadUserInfo()
        {
            logger.Info("Чтение информации о пользователе...");
            if (login == "root")
            {
                logger.Info("Вход под root, отмена чтения...");
                Admin       = true;
                Permissions = QSMain.ProjectPermission.ToDictionary(x => x.Key, x => false);
                return;
            }

            string       sql = "SELECT * FROM users WHERE login = @login";
            MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB);

            cmd.Parameters.AddWithValue("@login", login);
            MySqlDataReader rdr = cmd.ExecuteReader();

            if (!rdr.HasRows)
            {
                rdr.Close();
                if (Session.IsSaasConnection)
                {
                    logger.Info("Создаем описание пользователя в базе через SAAS...");
                    var srv = Session.GetSaaSService();
                    if (!srv.createUserInBase(Session.SessionId))
                    {
                        throw new ApplicationException("Сервер SAAS ответил отказом, на попытку добавить пользователя.");
                    }
                }
                else
                {
                    CreateUserRow();
                }
                //Перечитываем инфу.
                rdr = cmd.ExecuteReader();
            }
            if (!rdr.HasRows)
            {
                throw new ApplicationException(String.Format("В БД нет пользователя с логином {0}", Login));
            }

            rdr.Read();

            Name  = rdr ["name"].ToString();
            Id    = rdr.GetInt32("id");
            Admin = rdr.GetBoolean(QSMain.AdminFieldName);
            var fieldNames = Enumerable.Range(0, rdr.FieldCount).Select(i => rdr.GetName(i)).ToArray();

            Permissions = new Dictionary <string, bool> ();
            foreach (KeyValuePair <string, UserPermission> Right in QSMain.ProjectPermission)
            {
                string FieldName = Right.Value.DataBaseName;
                if (fieldNames.Contains(FieldName))
                {
                    Permissions.Add(Right.Key, rdr.GetBoolean(FieldName));
                }
                else
                {
                    Permissions.Add(Right.Key, false);
                }
            }

            rdr.Close();
            Email = tryGetUserEmail();
        }
예제 #11
0
        private void ReportForm_Load(object sender, EventArgs e)
        {
            if (type == 1)
            {
                DataTable table = new DataTable();

                MySqlDataReader reader = null;

                table.Columns.Add("Color", typeof(string));
                table.Columns.Add("Size", typeof(string));
                table.Columns.Add("Article", typeof(string));
                table.Columns.Add("Issued Quantity", typeof(int));

                try
                {
                    reader = DBConnection.getData(qry);

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Object o;

                            try
                            {
                                o = reader.GetString("issued");
                            }
                            catch (Exception)
                            {
                                o = null;
                            }

                            if (o != null)
                            {
                                table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), reader.GetInt32("issued"));
                            }
                            else
                            {
                                table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), 0);
                            }
                        }

                        reader.Close();

                        Report.CrystalReportIssued rpt = new Report.CrystalReportIssued();

                        rpt.Database.Tables["Item"].SetDataSource(table);

                        ExportOptions exportOptions;
                        DiskFileDestinationOptions diskFileDestinationOptions = new DiskFileDestinationOptions();

                        SaveFileDialog sfd = new SaveFileDialog();

                        sfd.Filter = "Pdf Files|*.pdf";

                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            diskFileDestinationOptions.DiskFileName = sfd.FileName;
                        }

                        exportOptions = rpt.ExportOptions;
                        {
                            exportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                            exportOptions.ExportFormatType      = ExportFormatType.PortableDocFormat;
                            exportOptions.DestinationOptions    = diskFileDestinationOptions;
                            exportOptions.ExportFormatOptions   = new PdfRtfWordFormatOptions();
                        }

                        rpt.Export();

                        ItemsCrystalReportViewer.ReportSource = null;
                        ItemsCrystalReportViewer.ReportSource = rpt;
                    }
                    else
                    {
                        reader.Close();

                        MessageBox.Show("No records!", "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex, "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (type == 0)
            {
                DataTable table = new DataTable();

                MySqlDataReader reader = null;

                table.Columns.Add("Color", typeof(string));
                table.Columns.Add("Size", typeof(string));
                table.Columns.Add("Article", typeof(string));
                table.Columns.Add("Total Quantity", typeof(int));
                table.Columns.Add("Issued Quantity", typeof(int));
                table.Columns.Add("Balance Quantity", typeof(int));

                try
                {
                    reader = DBConnection.getData(qry);

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Object o;

                            try
                            {
                                o = reader.GetString("balance");
                            }
                            catch (Exception)
                            {
                                o = null;
                            }

                            if (o != null)
                            {
                                table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), reader.GetInt32("total"), reader.GetInt32("total") - reader.GetInt32("balance"), reader.GetInt32("balance"));
                            }
                            else
                            {
                                table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), reader.GetInt32("total"), 0, reader.GetInt32("total"));
                            }
                        }

                        reader.Close();

                        Report.CrystalReportOfItems rpt = new Report.CrystalReportOfItems();

                        rpt.Database.Tables["Item"].SetDataSource(table);

                        ExportOptions exportOptions;
                        DiskFileDestinationOptions diskFileDestinationOptions = new DiskFileDestinationOptions();

                        SaveFileDialog sfd = new SaveFileDialog();

                        sfd.Filter = "Pdf Files|*.pdf";

                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            diskFileDestinationOptions.DiskFileName = sfd.FileName;
                        }

                        exportOptions = rpt.ExportOptions;
                        {
                            exportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                            exportOptions.ExportFormatType      = ExportFormatType.PortableDocFormat;
                            exportOptions.DestinationOptions    = diskFileDestinationOptions;
                            exportOptions.ExportFormatOptions   = new PdfRtfWordFormatOptions();
                        }

                        rpt.Export();

                        ItemsCrystalReportViewer.ReportSource = null;
                        ItemsCrystalReportViewer.ReportSource = rpt;
                    }
                    else
                    {
                        reader.Close();

                        MessageBox.Show("No records!", "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex, "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (type == 2)
            {
                DataTable table = new DataTable();

                MySqlDataReader reader = null;

                table.Columns.Add("Received", typeof(int));
                table.Columns.Add("Pallekale", typeof(int));
                table.Columns.Add("Henz", typeof(int));
                table.Columns.Add("Balance", typeof(int));

                try
                {
                    reader = DBConnection.getData(qry);

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            /*
                             * Object o;
                             *
                             * try
                             * {
                             *  o = reader.GetString("issued");
                             * }
                             * catch (Exception)
                             * {
                             *  o = null;
                             * }
                             *
                             * if (o != null)
                             *  table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), reader.GetInt32("issued"));
                             * else
                             *  table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), 0);
                             */

                            table.Rows.Add(reader.GetInt32("received"), reader.GetInt32("pallekale"), reader.GetInt32("henz"), reader.GetInt32("balance"));
                        }

                        reader.Close();

                        Report.CrystalReportSummary rpt = new Report.CrystalReportSummary();

                        rpt.Database.Tables["Summary"].SetDataSource(table);

                        ExportOptions exportOptions;
                        DiskFileDestinationOptions diskFileDestinationOptions = new DiskFileDestinationOptions();

                        SaveFileDialog sfd = new SaveFileDialog();

                        sfd.Filter = "Pdf Files|*.pdf";

                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            diskFileDestinationOptions.DiskFileName = sfd.FileName;
                        }

                        exportOptions = rpt.ExportOptions;
                        {
                            exportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                            exportOptions.ExportFormatType      = ExportFormatType.PortableDocFormat;
                            exportOptions.DestinationOptions    = diskFileDestinationOptions;
                            exportOptions.ExportFormatOptions   = new PdfRtfWordFormatOptions();
                        }

                        rpt.Export();

                        ItemsCrystalReportViewer.ReportSource = null;
                        ItemsCrystalReportViewer.ReportSource = rpt;
                    }
                    else
                    {
                        reader.Close();

                        MessageBox.Show("No records!", "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex, "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (type == 3)
            {
                DataTable table    = new DataTable();
                DataTable tableRec = new DataTable();

                MySqlDataReader reader = null;

                tableRec.Columns.Add("Received", typeof(uint));
                table.Columns.Add("Place", typeof(string));
                table.Columns.Add("issued", typeof(uint));

                try
                {
                    reader = DBConnection.getData(qry);

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            /*
                             * Object o;
                             *
                             * try
                             * {
                             *  o = reader.GetString("issued");
                             * }
                             * catch (Exception)
                             * {
                             *  o = null;
                             * }
                             *
                             * if (o != null)
                             *  table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), reader.GetInt32("issued"));
                             * else
                             *  table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), 0);
                             */

                            table.Rows.Add(reader.GetString("place"), reader.GetUInt32("issued"));
                        }

                        reader.Close();

                        reader = DBConnection.getData(qryRec);

                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                /*
                                 * Object o;
                                 *
                                 * try
                                 * {
                                 *  o = reader.GetString("issued");
                                 * }
                                 * catch (Exception)
                                 * {
                                 *  o = null;
                                 * }
                                 *
                                 * if (o != null)
                                 *  table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), reader.GetInt32("issued"));
                                 * else
                                 *  table.Rows.Add(reader.GetString("color"), reader.GetString("size"), reader.GetString("article"), 0);
                                 */

                                tableRec.Rows.Add(reader.GetUInt32("received"));
                            }

                            reader.Close();

                            Report.CrystalReportAdvancedSummary rpt = new Report.CrystalReportAdvancedSummary();

                            rpt.Database.Tables["AdvancedSummary"].SetDataSource(table);
                            rpt.Database.Tables["AdvancedSummaryReceived"].SetDataSource(tableRec);

                            ExportOptions exportOptions;
                            DiskFileDestinationOptions diskFileDestinationOptions = new DiskFileDestinationOptions();

                            SaveFileDialog sfd = new SaveFileDialog();

                            sfd.Filter = "Pdf Files|*.pdf";

                            if (sfd.ShowDialog() == DialogResult.OK)
                            {
                                diskFileDestinationOptions.DiskFileName = sfd.FileName;
                            }

                            exportOptions = rpt.ExportOptions;
                            {
                                exportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                                exportOptions.ExportFormatType      = ExportFormatType.PortableDocFormat;
                                exportOptions.DestinationOptions    = diskFileDestinationOptions;
                                exportOptions.ExportFormatOptions   = new PdfRtfWordFormatOptions();
                            }

                            rpt.Export();

                            ItemsCrystalReportViewer.ReportSource = null;
                            ItemsCrystalReportViewer.ReportSource = rpt;
                        }
                        else
                        {
                            reader.Close();

                            MessageBox.Show("No records!", "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                catch (Exception ex)
                {
                    reader.Close();

                    MessageBox.Show("" + ex, "Items picker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #12
0
        public ReturnValue templateList(double moduleId, double faId, int typeId, double dataTypeId, int u_webFAid)
        {
            ReturnValue     info = new ReturnValue();
            MySqlDataReader rs   = null;
            List <object[]> list = new List <object[]>();

            string[] templateRange = new string[] { "全站", "模块", "频道" };
            //ArrayList list = new ArrayList();

            /*
             * rs = Sql.ExecuteReader("select type from module where id=" + ModuleID);
             * if (rs.Read())
             * {
             *  if (rs[0].ToString() == "False")//虚拟目录
             *  {
             *      ModuleType = false;
             *  }
             * }
             * rs.Close();*/
            if (typeId == 0)
            {
                list.Add(new object[] { 0, "全站", "站点通用模板", "", 1, 0, 0 });
                if (moduleId > 0)
                {
                    list.Add(new object[] { 0, "模块", "模块通用模板", "", 1, moduleId, 0 });
                }
                if (moduleId > 0 && faId != moduleId)
                {
                    list.Add(new object[] { 0, "频道", "频道页模板", "", 1, faId, 0 });
                }
                rs = Sql.ExecuteReader("select B.id,B.updatedate,B.classid from  template B  where B.u_type=0 and B.u_datatypeid=0 and B.u_defaultFlag=1 and B.u_webFAId=@webFAId and B.classid in (0,@moduleId,@id)",
                                       new MySqlParameter[] {
                    new MySqlParameter("id", faId),
                    new MySqlParameter("moduleId", moduleId),
                    new MySqlParameter("webFAId", u_webFAid)
                });
                int index = 0;
                while (rs.Read())
                {
                    if (rs.GetDouble(2) == 0)
                    {
                        index = 0;
                    }
                    else if (rs.GetDouble(2) == moduleId)
                    {
                        index = 1;
                    }
                    else if (rs.GetDouble(2) == faId)
                    {
                        index = 2;
                    }
                    list[index][0] = rs.GetDouble(0);
                    list[index][3] = rs.GetDateTime(1).ToString();
                    list[index][5] = rs.GetDouble(2);
                }
                rs.Close();
            }
            else if (typeId == 1)
            {
                list.Add(new object[] { 0, "全站", "站点通用模板", "", 1, 0, 0 });
                if (moduleId > 0)
                {
                    list.Add(new object[] { 0, "模块", "模块通用模板", "", 1, moduleId, 0 });
                }
                if (faId != moduleId)
                {
                    list.Add(new object[] { 0, "频道", "频道页模板", "", 1, faId, 0 });
                }
                rs = Sql.ExecuteReader("select B.id,B.updatedate,B.classid,B.u_defaultFlag,B.title from  template B  where B.u_type=1 and B.u_datatypeid=0 and B.u_webFAId=@webFAId and B.classid in (0,@moduleId,@id) order by B.classid ",
                                       new MySqlParameter[] {
                    new MySqlParameter("id", faId),
                    new MySqlParameter("moduleId", moduleId),
                    new MySqlParameter("webFAId", u_webFAid)
                });
                int index = 0;
                while (rs.Read())
                {
                    bool defaultFlag = rs.GetInt32(3) == 1;
                    if (rs.GetDouble(2) == 0)
                    {
                        index = 0;
                    }
                    else if (rs.GetDouble(2) == moduleId)
                    {
                        index = 1;
                    }
                    else if (rs.GetDouble(2) == faId)
                    {
                        index = 2;
                    }

                    if (defaultFlag)
                    {
                        list[index][0] = rs.GetDouble(0);
                        list[index][3] = rs.GetDateTime(1).ToString();
                        list[index][5] = rs.GetDouble(2);
                    }
                    else
                    {
                        list.Add(new object[] { rs[0], templateRange[index], rs[4], rs.GetDateTime(1).ToString(), rs.GetDouble(2), 0 });
                    }
                }
                rs.Close();
            }
            else if (typeId == 2)
            {
                List <object[]> datatypeList = new List <object[]>();
                string          sql          = "select SaveDataType from class where moduleid=@moduleId group by SaveDataType";
                if (moduleId == 0)
                {
                    sql = "select SaveDataType from class where moduleId in (select id from module)";
                }

                rs = Sql.ExecuteReader("select id,datatype from datatype where id in (" + sql + ")",
                                       new MySqlParameter[] {
                    new MySqlParameter("moduleId", moduleId)
                });
                while (rs.Read())
                {
                    datatypeList.Add(new object[] { rs.GetDouble(0), rs.GetString(1) });
                }
                rs.Close();
                int templateRangeCount = templateRange.Length;
                if (moduleId == 0)
                {
                    templateRangeCount = 1;
                }
                else if (faId == moduleId)
                {
                    templateRangeCount = 2;
                }
                for (int i1 = 0; i1 < templateRangeCount; i1++)
                {
                    for (int i = 0; i < datatypeList.Count; i++)
                    {
                        double classId = 0;
                        if (i1 == 0)
                        {
                            classId = 0;
                        }
                        else if (i1 == 1)
                        {
                            classId = moduleId;
                        }
                        else if (i1 == 2)
                        {
                            classId = faId;
                        }
                        list.Add(new object[] { 0, templateRange[i1], datatypeList[i][1].ToString() + "模板", "", 1, classId, datatypeList[i][0] });
                    }
                }
                #region 获取默认模板
                for (int i = 0; i < datatypeList.Count; i++)
                {
                    rs = Sql.ExecuteReader("select B.id,B.updatedate,B.classid,B.title,B.u_defaultFlag,B.u_datatypeId from  template B where B.u_type=2 and B.u_datatypeid=@datatypeId and B.u_webFAId=@webFAId and B.u_defaultFlag=1 and B.classid in (0,@moduleId,@id)",
                                           new MySqlParameter[] {
                        new MySqlParameter("id", faId),
                        new MySqlParameter("moduleId", moduleId),
                        new MySqlParameter("datatypeId", datatypeList[i][0]),
                        new MySqlParameter("webFAId", u_webFAid)
                    });
                    int index = 0;
                    while (rs.Read())
                    {
                        if (rs.GetDouble(2) == 0)
                        {
                            index = i;                      //全站
                        }
                        else if (rs.GetDouble(2) == moduleId)
                        {
                            index = datatypeList.Count + i;                                  //模块
                        }
                        else if (rs.GetDouble(2) == faId)
                        {
                            index = datatypeList.Count * 2 + i;//频道
                        }
                        list[index][0] = rs.GetDouble(0);
                        list[index][3] = rs.GetDateTime(1).ToString();
                        list[index][5] = rs.GetDouble(2);
                        list[index][6] = rs.GetDouble(5);
                    }
                    rs.Close();
                }
                #endregion
                rs = Sql.ExecuteReader("select B.id,B.updatedate,B.classid,B.title,B.u_defaultFlag,B.u_datatypeId from  template B where B.u_type=2 and B.u_webFAId=@webFAId and B.u_defaultFlag=0 and B.classid = @id",
                                       new MySqlParameter[] {
                    new MySqlParameter("id", faId),
                    new MySqlParameter("webFAId", u_webFAid)
                });
                while (rs.Read())
                {
                    int index = 0;
                    if (rs.GetDouble(2) == 0)
                    {
                        index = 0;                      //全站
                    }
                    else if (rs.GetDouble(2) == moduleId)
                    {
                        index = 1;                                  //模块
                    }
                    else if (rs.GetDouble(2) == faId)
                    {
                        index = 2;
                    }
                    list.Add(new object[] { rs.GetDouble(0), templateRange[index], rs[3], rs.GetDateTime(1).ToString(), 0, rs.GetDouble(2), 0, rs.GetDouble(5) });
                }
                rs.Close();
            }
            else if (typeId == 3)
            {
                string path = @"/";
                if (faId > 1)
                {
                    rs = Sql.ExecuteReader("select dirname from  class where id = @id", new MySqlParameter[] { new MySqlParameter("id", faId) });
                    if (rs.Read())
                    {
                        path = @"/" + rs.GetString(0) + @"/";
                    }
                    rs.Close();
                }
                rs = Sql.ExecuteReader("select B.id,B.updatedate,B.classid,B.title,B.u_defaultFlag from   template B  where B.u_type=3 and B.u_webFAId=@webFAId  and B.classid = @id",
                                       new MySqlParameter[] {
                    new MySqlParameter("id", faId),
                    new MySqlParameter("webFAId", u_webFAid)
                });
                while (rs.Read())
                {
                    list.Add(new object[] { rs.GetDouble(0), path, rs[3], rs.GetDateTime(1).ToString(), 0, 0 });
                }
                rs.Close();
            }

            info.userData = list;
            return(info);
        }
예제 #13
0
        public void AddClient(ObservableCollection <ViewModel.ClientBinder> UserExist, string nom, string prenom, string pseudo, string mail, string password)
        {
            try
            {
                ConnectionBdd   bdd        = new ConnectionBdd();
                MySqlConnection connection = bdd.getConnection();
                // Ouverture de la connexion SQL
                MySqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT * from client where pseudo=@pseudo or mail=@mail";
                cmd.Parameters.AddWithValue("@pseudo", pseudo);
                cmd.Parameters.AddWithValue("@mail", mail);
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        //redirection user exist

                        int    Id                          = reader.GetInt32(0);
                        string NomProperty                 = reader.GetString(1);
                        string PrenomProperty              = reader.GetString(2);
                        string PseudoProperty              = reader.GetString(3);
                        string MailProperty                = reader.GetString(4);
                        string PasswordProperty            = reader.GetString(5);
                        int    AdminProperty               = reader.GetInt32(6);
                        ViewModel.ClientBinder recupclient = new ViewModel.ClientBinder(Id, NomProperty, PrenomProperty, PseudoProperty, MailProperty, PasswordProperty, AdminProperty);
                        UserExist.Add(recupclient);
                    }
                }
                else
                {
                    connection.Close();
                    ConnectionBdd   bdd2        = new ConnectionBdd();
                    MySqlConnection connection2 = bdd2.getConnection();
                    MySqlCommand    insert      = connection2.CreateCommand();

                    insert.CommandText = "INSERT INTO client (nom,prenom,mail,pseudo,password) VALUES (@nom,@prenom,@mail,@pseudo,@password)";

                    insert.Parameters.AddWithValue("@nom", nom);
                    insert.Parameters.AddWithValue("@prenom", prenom);
                    insert.Parameters.AddWithValue("@mail", mail);
                    insert.Parameters.AddWithValue("@pseudo", pseudo);
                    insert.Parameters.AddWithValue("@password", password);

                    // Exécution de la commande SQL
                    insert.ExecuteNonQuery();

                    // Fermeture de la connexion
                    connection2.Close();
                }
                // Création d'une commande SQL en fonction de l'objet connexion
                connection.Close();
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                case 0:
                    MessageBox.Show("Impossible de se connecter au serveur");
                    break;

                case 1045:
                    MessageBox.Show("Utilisateur ou mot de passe invalide");
                    break;
                }
                // Gestion des erreurs :
                // Possibilité de créer un Logger pour les exceptions SQL reçus
                // Possibilité de créer une méthode avec un booléan en retour pour savoir si le contact à été ajouté correctement.
            }
        }
예제 #14
0
        private void Home_Load(object sender, EventArgs e)
        {
            // inititalmisation des variables :
            int aucuneFactureExiste = -1;
            int villasEnreg         = -1;
            int numNewFacture       = 1;
            List <tabNewInexNumSc>     elementsTab1 = new List <tabNewInexNumSc>();
            List <sousCompteursActifs> elementsTab2 = new List <sousCompteursActifs>();



            if (userLogInfo.roleUser == 1)
            {
                TileGestUser.Visible  = false;
                TileStateList.Visible = false;
                TileHousesRef.Visible = false;
            }

            // si au démarage aucune facture n'existe générer la première facture :
            // test si aucune facture n'existe :
            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();

                // verif si le g�rant existe :
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection  = conn;
                cmd.CommandText = "select count(numFacture) from facture";
                cmd.Prepare();

                aucuneFactureExiste = Convert.ToInt32(cmd.ExecuteScalar());
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            // opérations si aucune facture n'existe :

            if (aucuneFactureExiste == 0)
            {
                // générer la nouvelle fature :
                try
                {
                    // insertion du lib�l� du mois :
                    conn = new MySqlConnection(cs);
                    conn.Open();

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    //insertion des autres informations dans la table sous-compteur :
                    cmd.CommandText = "insert into facture(montantFacture) values(@a)";
                    cmd.Prepare();

                    cmd.Parameters.AddWithValue("@a", 0);

                    cmd.ExecuteNonQuery();

                    // MessageBox.Show(" J'ai bien insérer la facture .....");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }



                // séléction des sous Compteurs actifs à la date de la nouvelle facture :
                try
                {
                    conn = new MySqlConnection(cs);
                    conn.Open();

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    cmd.CommandText = "SELECT numSousCompteur, indexInitial, datePassgeInitial FROM souscompteur where statutSousCompteur = @a";
                    cmd.Parameters.AddWithValue("@a", 1);

                    rdr = cmd.ExecuteReader();

                    while (rdr.Read())
                    {
                        elementsTab1.Add(new tabNewInexNumSc
                        {
                            numSousCompteur   = rdr.GetInt32(0),
                            nouvelIndex       = rdr.GetInt32(1),
                            datePassgeInitial = rdr.GetString(2)
                        });
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (rdr != null)
                    {
                        rdr.Close();
                    }
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }


                // insertion dans la base de donn�es :
                foreach (tabNewInexNumSc unElem in elementsTab1)
                {
                    // Pr�paration des variables :
                    int    ancienIndex        = unElem.nouvelIndex;
                    int    numFact            = 1;
                    int    numUser            = userLogInfo.numUser;
                    int    numSC              = unElem.numSousCompteur;
                    String datePassageInitial = unElem.datePassgeInitial;

                    // insertion dans la base de donn�es :
                    try
                    {
                        conn = new MySqlConnection(cs);
                        conn.Open();

                        MySqlCommand cmd = new MySqlCommand();
                        cmd.Connection = conn;

                        cmd.CommandText = "insert into traiter(numFacture, numSousCompteur, numUtilisateur, ancienIndex, ancienneDatePassage) values(@a, @b, @c, @d, @e)";
                        cmd.Prepare();

                        cmd.Parameters.AddWithValue("@a", numFact);
                        cmd.Parameters.AddWithValue("@b", numSC);
                        cmd.Parameters.AddWithValue("@c", numUser);
                        cmd.Parameters.AddWithValue("@d", ancienIndex);
                        cmd.Parameters.AddWithValue("@e", datePassageInitial.ToString().Substring(6, 4) + '-' + datePassageInitial.ToString().Substring(3, 2) + '-' + datePassageInitial.ToString().Substring(0, 2));

                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            conn.Close();
                        }
                    }
                }
            }
            else
            {
            }



            // on vérifie si on a au moins deux villas enregistrées. si non on grise toutes les tiles sauf enregistrer villa :
            // test :
            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();

                // verif si le g�rant existe :
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection  = conn;
                cmd.CommandText = "select count(numVilla) from villa";
                cmd.Prepare();

                villasEnreg = Convert.ToInt32(cmd.ExecuteScalar());
                //MessageBox.Show(villasEnreg.ToString());
                if (villasEnreg < 2)
                {
                    metroTile1.Enabled    = false;
                    metroTile2.Enabled    = false;
                    metroTile3.Enabled    = false;
                    metroTile5.Enabled    = false;
                    metroTile6.Enabled    = false;
                    TileStateList.Enabled = false;
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            // grise l'enregistrement des index tant que le montant de la facture n'est pas enr.
            //test si le montant de la dernière facture est enregistrée ...
            bool montantDerniereFacureEnreg = true;
            int  numLastBill = -1;

            // test :
            // séléction du numéro de la derniere fact :
            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "select max(numFacture) from facture";
                rdr             = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    numLastBill = rdr.GetInt32(0);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                }
                if (conn != null)
                {
                    conn.Close();
                }
            }
            // sélection du statut d'enreg du montant et reformatage du booléen :
            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "SELECT statutEnregMontant FROM facture where numFacture = @a";
                cmd.Parameters.AddWithValue("@a", numLastBill);

                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    if (rdr.GetInt32(0) == 0)
                    {
                        montantDerniereFacureEnreg = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                }
                if (conn != null)
                {
                    conn.Close();
                }
            }
            if (montantDerniereFacureEnreg == false)
            {
                metroTile2.Enabled = false;
            }
        }
예제 #15
0
        protected override void HandleRequest()
        {
            byte[] status = null;

            string span = "";

            switch (NameValueCollection["timespan"])
            {
            case "week":
                span = "(time >= DATE_SUB(NOW(), INTERVAL 1 WEEK))";
                break;

            case "month":
                span = "(time >= DATE_SUB(NOW(), INTERVAL 1 MONTH))";
                break;

            case "all":
                span = "TRUE";
                break;

            default:
                status = Encoding.UTF8.GetBytes("<Error>Invalid fame list</Error>");
                break;
            }
            string ac = "FALSE";

            if (NameValueCollection["accountId"] != null)
            {
                ac = "(accId=@accId AND chrId=@charId)";
            }

            if (status == null)
            {
                XmlDocument doc  = new XmlDocument();
                var         root = doc.CreateElement("FameList");

                var spanAttr = doc.CreateAttribute("timespan");
                spanAttr.Value = NameValueCollection["timespan"];
                root.Attributes.Append(spanAttr);

                doc.AppendChild(root);

                using (var db = new Database(Program.Settings.GetValue("conn")))
                {
                    using (var cmd = db.CreateQuery())
                    {
                        cmd.CommandText = @"SELECT * FROM death WHERE " + span + @" OR " + ac +
                                          @" ORDER BY totalFame DESC LIMIT 10;";
                        if (NameValueCollection["accountId"] != null)
                        {
                            cmd.Parameters.AddWithValue("@accId", NameValueCollection["accountId"]);
                            cmd.Parameters.AddWithValue("@charId", NameValueCollection["charId"]);
                        }
                        using (MySqlDataReader rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                var elem = doc.CreateElement("FameListElem");

                                var accIdAttr = doc.CreateAttribute("accountId");
                                accIdAttr.Value = rdr.GetInt32("accId").ToString();
                                elem.Attributes.Append(accIdAttr);
                                var chrIdAttr = doc.CreateAttribute("charId");
                                chrIdAttr.Value = rdr.GetInt32("chrId").ToString();
                                elem.Attributes.Append(chrIdAttr);

                                root.AppendChild(elem);

                                var nameElem = doc.CreateElement("Name");
                                nameElem.InnerText = rdr.GetString("name");
                                elem.AppendChild(nameElem);
                                var objTypeElem = doc.CreateElement("ObjectType");
                                objTypeElem.InnerText = rdr.GetString("charType");
                                elem.AppendChild(objTypeElem);
                                var tex1Elem = doc.CreateElement("Tex1");
                                tex1Elem.InnerText = rdr.GetString("tex1");
                                elem.AppendChild(tex1Elem);
                                var tex2Elem = doc.CreateElement("Tex2");
                                tex2Elem.InnerText = rdr.GetString("tex2");
                                elem.AppendChild(tex2Elem);
                                var skinElem = doc.CreateElement("Skin");
                                skinElem.InnerText = rdr.GetString("skin");
                                elem.AppendChild(skinElem);
                                var equElem = doc.CreateElement("Equipment");
                                equElem.InnerText = rdr.GetString("items");
                                elem.AppendChild(equElem);
                                var fameElem = doc.CreateElement("TotalFame");
                                fameElem.InnerText = rdr.GetString("totalFame");
                                elem.AppendChild(fameElem);
                            }
                        }
                    }
                }
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                using (XmlWriter wtr = XmlWriter.Create(ListenerContext.Response.OutputStream))
                    doc.Save(wtr);
            }
        }
예제 #16
0
        /// <summary>
        /// 登入按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btEnter_Click(object sender, EventArgs e)
        {
            string Query;

            string connStr = "server=" + dbHost + ";port=" + dbPort + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            //("server=127.0.0.1;user=root;database=test;port=3306;password=1111;")

            MySqlConnection conn = new MySqlConnection(connStr);

            //-- 連線到資料庫
            try
            {
                conn.Open();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Connect_flag = false;
                lbInfo.Text  = "Error";

                switch (ex.Number)
                {
                case 0:
                    lbInfo.Text = (MultipleLangString.GetString("_connectfail"));
                    break;

                case 1045:
                    lbInfo.Text = (MultipleLangString.GetString("_relogin"));
                    break;

                default:
                    lbInfo.Text = ex.Message;
                    break;
                }
            }

            //-- 伺服器連線成功
            if (Connect_flag)
            {
                Login_flag = false;

                //-- 命令與伺服器連線,通過命令來對資料庫進行存取
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                //-- 進行使用者帳號密碼認證
                try
                {
                    Query           = "select * from SVS.account where Uid='" + tbUid.Text + "'and Password='******';";
                    cmd.CommandText = Query;
                    MySqlDataReader Account = cmd.ExecuteReader();

                    //-- 如果沒有資料,顯示沒有資料的訊息
                    if (!Account.HasRows)
                    {
                        lbInfo.Text = (MultipleLangString.GetString("_relogin"));
                        Account.Close();
                    }
                    else
                    {
                        //-- 使用者登入成功
                        Login_flag = true;
                        Account.Close();
                        lbInfo.Text = MultipleLangString.GetString("_loginSuccess");

                        //-- 讀取使用者名稱並且顯示出來
                        Query           = "select UserName from SVS.account where Uid='" + tbUid.Text + "'and Password='******';";
                        cmd.CommandText = Query;
                        MySqlDataReader UserName = cmd.ExecuteReader();
                        while (UserName.Read())
                        {
                            lbInfo.Text = lbInfo.Text + '\n' + UserName.GetString(0);
                            Console.WriteLine("DBDBDBDBDB USER NAME: " + UserName.GetString(0));
                            //-- 記錄使用者名稱
                            TemplateData.FileName = UserName.GetString(0);
                        }
                        UserName.Close();

                        //-- 讀取最低建議分數並且顯示出來
                        Query           = "select ScoreLow from SVS.account where Uid='" + tbUid.Text + "'and Password='******';";
                        cmd.CommandText = Query;
                        MySqlDataReader Score_L = cmd.ExecuteReader();
                        while (Score_L.Read())
                        {
                            //-- 讀取最低建議分數
                            Score[0] = Score_L.GetDouble(0);
                        }
                        Score_L.Close();

                        //-- 讀取建議分數並且顯示出來
                        Query           = "select ScoreHigh from SVS.account where Uid='" + tbUid.Text + "'and Password='******';";
                        cmd.CommandText = Query;
                        MySqlDataReader Score_H = cmd.ExecuteReader();
                        while (Score_H.Read())
                        {
                            //-- 讀取最低建議分數
                            Score[1] = Score_H.GetDouble(0);
                        }
                        Score_H.Close();

                        //-- 讀取簽名花費時間並且顯示出來
                        Query           = "select CostTime from SVS.account where Uid='" + tbUid.Text + "'and Password='******';";
                        cmd.CommandText = Query;
                        MySqlDataReader CostTime = cmd.ExecuteReader();
                        while (CostTime.Read())
                        {
                            TemplateData.CostTime = CostTime.GetDouble(0);
                            Console.WriteLine("DBDBDBDBDB CostTime: " + Convert.ToString(CostTime.GetDouble(0)));
                        }
                        CostTime.Close();

                        //-- 讀取SID
                        Query           = "select SID from SVS.account where Uid='" + tbUid.Text + "'and Password='******';";
                        cmd.CommandText = Query;
                        MySqlDataReader SID_t = cmd.ExecuteReader();
                        while (SID_t.Read())
                        {
                            SID = SID_t.GetInt32(0);
                            //MessageBox.Show(SID.ToString());
                        }
                        SID_t.Close();
                    }
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    MessageBox.Show("Error " + ex.Number + " : " + ex.Message);
                }


                if (Login_flag)
                {
                    int             Len = 0;
                    MySqlDataReader DataReader;

                    //-- X, 讀資料長度
                    Query           = "select Len from SVS.feature_x where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select X" + i.ToString() + " from SVS.feature_x where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_X.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- Y, 讀資料長度
                    Query           = "select Len from SVS.feature_y where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select Y" + i.ToString() + " from SVS.feature_y where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_Y.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- P, 讀資料長度
                    Query           = "select Len from SVS.feature_P where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select P" + i.ToString() + " from SVS.feature_p where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_P.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- Vx, 讀資料長度
                    Query           = "select Len from SVS.feature_vx where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select Vx" + i.ToString() + " from SVS.feature_vx where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_Vx.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- Vy, 讀資料長度
                    Query           = "select Len from SVS.feature_vy where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select Vy" + i.ToString() + " from SVS.feature_vy where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_Vy.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- Ax, 讀資料長度
                    Query           = "select Len from SVS.feature_ax where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select Ax" + i.ToString() + " from SVS.feature_ax where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_Ax.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- Ay, 讀資料長度
                    Query           = "select Len from SVS.feature_ay where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select Ay" + i.ToString() + " from SVS.feature_ay where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_Ay.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }
                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//
                    //-- A, 讀資料長度
                    Query           = "select Len from SVS.feature_a where SID='" + SID.ToString() + "';";
                    cmd.CommandText = Query;
                    DataReader      = cmd.ExecuteReader();
                    while (DataReader.Read())
                    {
                        Len = DataReader.GetInt32(0);
                        //MessageBox.Show(Len.ToString());
                    }
                    DataReader.Close();

                    for (int i = 1; i <= Len; i++)
                    {
                        Query           = "select A" + i.ToString() + " from SVS.feature_a where SID='" + SID.ToString() + "';";
                        cmd.CommandText = Query;
                        DataReader      = cmd.ExecuteReader();
                        while (DataReader.Read())
                        {
                            TemplateData.Feature_A.Add(DataReader.GetDouble(0));
                            //MessageBox.Show(SID.ToString());
                        }
                        DataReader.Close();
                    }

                    //-------------------------------------------------------------------------------------------------------------//
                    //-------------------------------------------------------------------------------------------------------------//

                    //-- 取得該帳號之訊號後,傳入比對程式中
                    ParameterPass.Score    = Score;
                    ParameterPass.Template = TemplateData;

                    //-- 關閉其餘表單
                    Form[] aryf = this.Parent.FindForm().MdiChildren;
                    foreach (Form f in aryf)
                    {
                        if (f.Name != this.Name)
                        {
                            f.Close();
                        }
                    }

                    //-- 成功登入後,進入訊號比對畫面
                    MainFigure MainProcess = new MainFigure();
                    MainProcess.MdiParent   = this.MdiParent;
                    MainProcess.WindowState = FormWindowState.Maximized;
                    this.MdiParent.Size     = MainProcess.Size;
                    MainProcess.Show();

                    //-- 關閉其餘功能選項
                    ParameterPass.MainFugure_flag = true;

                    conn.Close();
                    this.Close();
                }
            }

            conn.Close();
        }
예제 #17
0
        //根据证件号,查询来访纪录
        public static flow_data_362 findByIdNumber(string idNumber)
        {
            flow_data_362 model;

            //证件号码最少输入6位
            if (idNumber.Length < 6)
            {
                return(null);
            }

            //并没有建立数据库连接
            MySqlConnection conn = new MySqlConnection(connectStr);

            try
            {
                conn.Open();                                          //建立连接,打开数据库
                idNumber = idNumber.Replace("'", "‘");                //防一下sql注入
                string today = DateTime.Today.ToString("yyyy-MM-dd"); //日期格式要确保与mysql存储格式一致。

                // string sqlstr = "select * from flow_data_362 where data_11 = '" + idNumber + "' and  left(data_6,10) = '" + today + "'";   //SQL语句
                string       sqlstr = "select * from flow_data_362 where data_11 like '%" + idNumber + "%' and  left(data_6,10) = '" + today + "'"; //SQL语句
                MySqlCommand cmd    = new MySqlCommand(sqlstr, conn);

                //相当于数据读出流  理解为一本书
                MySqlDataReader reader = cmd.ExecuteReader();
                //reader.Read();  //读取下一页数据 ,读取成功,返回true,下一页没有数据则返回false表示到了最后一页

                if (reader.Read())   //遍历表中数据,只取第一条记录
                {
                    //Console.WriteLine(reader.GetInt32("id") + reader.GetString("name") + reader.GetString("age"));
                    //封装属性
                    model = new flow_data_362
                    {
                        #region 封装属性
                        id                  = reader.GetInt32("id"),
                        run_id              = reader.GetInt32("run_id"),
                        begin_time          = reader.GetDateTime("begin_time"),
                        begin_user          = reader.GetString("begin_user"),
                        data_10             = reader.GetString("data_10"),
                        data_11             = reader.GetString("data_11"),
                        data_12             = reader.GetString("data_12"),
                        data_13             = reader.GetString("data_13"),
                        data_14             = reader.GetString("data_14"),
                        data_15             = reader.GetString("data_15"),
                        data_16             = reader.GetString("data_16"),
                        data_17             = reader.GetString("data_17"),
                        data_18             = reader.GetString("data_18"),
                        data_19             = reader.GetString("data_19"),
                        data_20             = reader.GetString("data_20"),
                        data_21             = reader.GetString("data_21"),
                        data_22             = reader.GetString("data_22"),
                        data_22_key         = reader.GetString("data_22_key"),
                        data_23             = reader.GetString("data_23"),
                        data_24             = reader.GetString("data_24"),
                        data_25             = reader.GetString("data_25"),
                        data_27             = reader.GetString("data_27"),
                        data_29             = reader.GetString("data_29"),
                        data_31             = reader.GetString("data_31"),
                        data_32             = reader.GetString("data_32"),
                        data_33             = reader.GetString("data_33"),
                        data_36             = reader.GetString("data_36"),
                        data_38             = reader.GetString("data_38"),
                        data_4              = reader.GetString("data_4"),
                        data_40             = reader.GetString("data_40"),
                        data_41             = reader.GetString("data_41"),
                        data_43             = reader.GetString("data_43"),
                        data_44             = reader.GetString("data_44"),
                        data_45             = reader.GetString("data_45"),
                        data_5              = reader.GetString("data_5"),
                        data_6              = reader.GetString("data_6"),
                        data_8              = reader.GetString("data_8"),
                        data_9              = reader.GetString("data_9"),
                        flow_auto_num       = reader.GetInt32("flow_auto_num"),
                        flow_auto_num_month = reader.GetInt32("flow_auto_num_month"),
                        flow_auto_num_year  = reader.GetInt32("flow_auto_num_year"),
                        run_name            = reader.GetString("run_name")
                                              #endregion
                    };
                }
                else
                {
                    model = null;
                }
                if (!reader.IsClosed)
                {
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(null);
            }
            finally
            {
                conn.Close();   //关闭连接
            }
            return(model);
        }
예제 #18
0
        public void ExecuteQuery()
        {
            ArrayList solutions = new ArrayList();

            if (SolutionIsPossible)
            {
                MySqlDataReader dataReader = null;
                try {
                    dataReader = itsTriples.ExecuteSqlQuery(itsQuerySql);
                    while (dataReader.Read())
                    {
                        QuerySolution solution = new QuerySolution();
                        int           col      = 0;
                        foreach (Variable var in itsSelectedVariables)
                        {
                            object resourceHash = dataReader.GetValue(col);
                            if (!resourceHash.Equals(DBNull.Value))
                            {
                                Resource resource = new Resource(Convert.ToInt32(resourceHash));
                                solution[var.Name] = resource;

                                int    nodeHash     = dataReader.GetInt32(col + 1);
                                char   nodeType     = dataReader.GetChar(col + 2);
                                string lexicalValue = dataReader.GetString(col + 3);
                                object rawSubValue  = dataReader.GetValue(col + 4);
                                string subValue     = null;
                                if (!rawSubValue.Equals(DBNull.Value))
                                {
                                    subValue = (string)rawSubValue;
                                }

                                GraphMember node = null;
                                switch (nodeType)
                                {
                                case 'u':
                                    node = new UriRef(lexicalValue);
                                    break;

                                case 'b':
                                    node = new BlankNode(nodeHash);
                                    break;

                                case 'p':
                                    node = new PlainLiteral(lexicalValue, subValue);
                                    break;

                                case 't':
                                    node = new TypedLiteral(lexicalValue, subValue);
                                    break;
                                }

                                solution.SetNode(var.Name, node);
                            }
                            col += 5;
                        }
                        solutions.Add(solution);
                    }
                }
                catch (MySqlException e) {
                    throw new ApplicationException("Error executing '" + itsQuerySql + "' for query " + itsQuery, e);
                }
                finally {
                    if (null != dataReader)
                    {
                        dataReader.Close();
                    }
                }
            }

            itsSolutions = solutions.GetEnumerator();
        }
예제 #19
0
        private static int CapsuleMachineGetItem(Account User, int MachineItemNum, int MachineKindID, CapsuleMachineInfo infos, List <CapsuleMachineItem> CapsuleMachineItem, out byte ret)
        {
            int TotalCount = infos.TotalItemCount;
            //int itemnum = 0;
            CapsuleMachineItem ItemInfo = new CapsuleMachineItem();
            //ItemInfo = CapsuleMachineItem.Where(w => w.Level == 1).FirstOrDefault();

            double UserLucky = (double)User.Luck;
            double CapsuleMachineRateLuckyDiv = 200; //DB
            int    CapsuleMachineMaxDice      = 10;  //DB

            int ItemLevel       = 6;
            int ItemLevelBefore = 0;
            int DrawTime        = 1;

            DrawTime = (int)(UserLucky / CapsuleMachineRateLuckyDiv + 1.0);
            if (DrawTime > CapsuleMachineMaxDice)
            {
                DrawTime = CapsuleMachineMaxDice;
            }

            while (DrawTime > 0)
            {
drawtart:
                Random rnd = new Random(Guid.NewGuid().GetHashCode());
                int rndnum = rnd.Next(1, TotalCount + 1);
                int min = 1, max = 1;
                foreach (var item in CapsuleMachineItem.OrderBy(o => o.ItemMax))
                {
                    max += item.ItemMax;
                    if (min <= rndnum && rndnum < max)
                    {
                        if (item.ItemCount <= 0)
                        {
                            goto drawtart; //redraw
                        }
                        ItemLevelBefore = ItemLevel;
                        if (ItemLevelBefore >= item.Level)
                        {
                            ItemLevel = item.Level;
                            ItemInfo  = item;
                        }
                        break;
                    }
                    min = max;
                }

                DrawTime--;
            }

            ret = 0;
            bool isReset = false;
            int  resultItemNum = 0;
            int  level = 0;
            int  PriceType = 0, cost = 0;

            try
            {
                using (var con = new MySqlConnection(Conf.Connstr))
                {
                    con.Open();
                    var cmd = new MySqlCommand(string.Empty, con);
                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "usp_capsuleMachineSelect";
                    cmd.Parameters.Add("machineNum", MySqlDbType.Int32).Value    = infos.RealMachineNum;
                    cmd.Parameters.Add("machineKind", MySqlDbType.Int32).Value   = infos.RealMachineNumKind;
                    cmd.Parameters.Add("itemNum", MySqlDbType.Int32).Value       = ItemInfo.ItemNum;
                    cmd.Parameters.Add("userNum", MySqlDbType.Int32).Value       = User.UserNum;
                    cmd.Parameters.Add("selectTime", MySqlDbType.DateTime).Value = DateTime.Now;
                    cmd.Parameters.Add("resetCount", MySqlDbType.Int32).Value    = infos.ResetCount;
                    MySqlDataReader reader = cmd.ExecuteReader();
                    reader.Read();
                    ret = (byte)reader.GetInt32("retval");
                    if (ret == 0)
                    {
                        resultItemNum = reader.GetInt32("resultItemNum");
                        level         = reader.GetInt32("level");
                        isReset       = reader.GetBoolean("isReset");
                        cost          = reader.GetInt32("cost");
                        //myAsset = reader.GetInt32("myAsset");
                        PriceType = Convert.ToInt32(reader["PriceType"]);
                    }
                    else
                    {
                        Console.WriteLine("RET: {0}", ret);
                    }
                    cmd.Dispose();
                    reader.Close();
                    con.Close();
                }
                if (ret == 0)
                {
                    if (level < 3)
                    {
                        Task.Run(() =>
                        {
                            foreach (var ac in ClientConnection.CurrentAccounts.Values)
                            {
                                ac.Connection.SendAsync(new CapsuleMachineNotice(ac, (byte)level, MachineItemNum, resultItemNum, User.NickName));
                            }
                        });
                    }

                    if (isReset)
                    {
                        string MachineNum = CapsuleMachineHolder.UpdateCapsuleMachineInfo(MachineItemNum, infos.RealMachineNum, infos.isRotate);
                        if (infos.isRotate)
                        {
                            Task.Run(() =>
                            {
                                foreach (var ac in ClientConnection.CurrentAccounts.Values)
                                {
                                    ac.Connection.SendAsync(new RoatateMachineNotice(ac, MachineNum));
                                }
                            });
                        }
                    }
                    else
                    {
                        CapsuleMachineHolder.CapsuleMachineItems[MachineItemNum].Where(w => w.ItemNum == ItemInfo.ItemNum).ToList()
                        .ForEach(f => f.ItemCount -= 1);
                    }

                    if (PriceType == 0) //TR
                    {
                        User.TR -= cost;
                    }
                    else if (PriceType == 1) //點數
                    {
                        User.Cash -= cost;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error on capsule machine get item: {0}", ex.Message);
                ret = 1;
            }
            return(resultItemNum);
        }
예제 #20
0
        public Char LoadCharacter(Account acc, int charId)
        {
            MySqlCommand cmd = CreateQuery();

            cmd.CommandText = "SELECT * FROM characters WHERE accId=@accId AND charId=@charId;";
            cmd.Parameters.AddWithValue("@accId", acc.AccountId);
            cmd.Parameters.AddWithValue("@charId", charId);
            Char ret;

            using (MySqlDataReader rdr = cmd.ExecuteReader())
            {
                if (!rdr.HasRows)
                {
                    return(null);
                }
                rdr.Read();
                int[] stats = Utils.FromCommaSepString32(rdr.GetString("stats"));
                ret = new Char
                {
                    ObjectType     = (short)rdr.GetInt32("charType"),
                    CharacterId    = rdr.GetInt32("charId"),
                    Level          = rdr.GetInt32("level"),
                    Exp            = rdr.GetInt32("exp"),
                    CurrentFame    = rdr.GetInt32("fame"),
                    _Equipment     = rdr.GetString("items"),
                    Backpack       = 1,
                    MaxHitPoints   = stats[0],
                    HitPoints      = rdr.GetInt32("hp"),
                    MaxMagicPoints = stats[1],
                    MagicPoints    = rdr.GetInt32("mp"),
                    Attack         = stats[2],
                    Defense        = stats[3],
                    Speed          = stats[4],
                    HpRegen        = stats[5],
                    MpRegen        = stats[6],
                    Dexterity      = stats[7],
                    Tex1           = rdr.GetInt32("tex1"),
                    Tex2           = rdr.GetInt32("tex2"),
                    Dead           = rdr.GetBoolean("dead"),
                    Pet            = rdr.GetInt32("pet"),
                    PCStats        = rdr.GetString("fameStats"),
                    FameStats      = new FameStats()
                };
                if (!string.IsNullOrEmpty(ret.PCStats) && ret.PCStats != "FameStats")
                {
                    try
                    {
                        ret.FameStats.Read(
                            ZlibStream.UncompressBuffer(
                                Convert.FromBase64String(ret.PCStats.Replace('-', '+').Replace('_', '/'))));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            ret.Backpacks   = GetBackpacks(ret, acc);
            ret._Equipment += ", " + Utils.GetCommaSepString(ret.Backpacks[1]);
            cmd.Dispose();
            return(ret);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //Check sessions of uid and dheyaemail of user
            if (Session["uid"] != null && Session["dheyaEmail"] != null)
            {
                //CDF own referrals month-wise
                chart_bind();
                //All CDF referrals month-wise
                chart_bind2();
                //CDF record count
                bindgrid();
                //News Feed Method
                newsFeed();
                //New Updates from Dheya (individual)
                dheyaUpdates();

                //CDF own referrals month-wise - converted and created
                chart_bind_both();
                // lead converted
                bindgrid_lead_converted();
                // lead created
                bindgrid_lead_created();

                string constr = ConfigurationManager.ConnectionStrings["CRM_ConnectionString"].ConnectionString;
                using (MySqlConnection con = new MySqlConnection(constr))
                {
                    DataTable dt2     = new DataTable();
                    string    strcmd1 = "SELECT count(id) FROM suitecrm.leads as A inner join suitecrm.leads_cstm as B on A.id=B.id_c where A.refered_by='" + Session["dheyaEmail"].ToString() + "' and deleted=0";
                    con.Open();
                    MySqlCommand    cmd = new MySqlCommand(strcmd1, con);
                    MySqlDataReader dr1 = cmd.ExecuteReader();
                    //Check if table has rows for required query
                    if (dr1.HasRows)
                    {
                        dr1.Read();
                        Int32 s = dr1.GetInt32(0);
                        //leads_count.Text = " " + s;
                        //session_count.Text = " " + s * 0;
                        // revenue_count.Text = "" + s * 0;
                    }
                }
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    //Check payment status of respective user from tblPayment table
                    string     query_visit = "  select COUNT(log_id) as count from tblLog where uId='" + Session["uid"].ToString() + "' and log_type = 'in'";
                    SqlCommand cmdvisit    = new SqlCommand(query_visit, connection);
                    //visits_count.Text = cmdvisit.ExecuteScalar().ToString();


                    try
                    {
                        string     queryLastVisit = " SELECT TOP 1 log_time FROM (select top 2 log_time, log_id from tblLog where log_type = 'in' and uId = '" + Session["uid"].ToString() + "' order by log_id desc)t ORDER BY log_id";
                        SqlCommand cmdLastVisit   = new SqlCommand(queryLastVisit, connection);
                        string     date1          = cmdLastVisit.ExecuteScalar().ToString();
                        DateTime   dt             = Convert.ToDateTime(date1);
                        //visits_count.ToolTip = "Last Vist: " + dt.ToString("dd'/'MM'/'yyyy HH:mm:ss tt");
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }

                    int uid = Convert.ToInt32(HttpContext.Current.Session["uid"].ToString());


                    string str = ""
                                 + "select count(uId) FROM tblUserMaster where uId=" + uid + ";"
                                 + "select count(uId)FROM tblUserDetails where uId = " + uid + ";"
                                 + "select count(DISTINCT uId) FROM tblEducation where uId = " + uid + ";"
                                 + "select count(DISTINCT uId) FROM tblExperience where uId = " + uid + "";

                    SqlDataAdapter da = new SqlDataAdapter(str, connection);
                    DataSet        ds = new DataSet();
                    da.Fill(ds);
                    double count           = 0;
                    double total           = 4;
                    double profileComplete = 0;
                    //profile complete status
                    for (int i = 0; i < total; i++)
                    {
                        count = count + Convert.ToInt32(ds.Tables[i].Rows[0][0]);
                    }
                    profileComplete = (count / total) * 100;
                    profilec.Text   = profileComplete.ToString();
                }
            }
            else
            {
                Response.Redirect("~/login.aspx", false);
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex);
        }
    }
예제 #22
0
        protected override void HandleRequest()
        {
            OfferList list = new OfferList();

            using (Database db = new Database())
            {
                MySqlCommand cmd = db.CreateQuery();
                Account      acc = db.Verify(Query["guid"], Query["password"], Program.GameData);

                cmd.CommandText = "SELECT * FROM market WHERE status=0 ORDER BY id DESC";
                if (acc != null && Query["filter"] == "mine")
                {
                    cmd.CommandText = "SELECT * FROM market WHERE accId=@accId ORDER BY id DESC";
                    cmd.Parameters.AddWithValue("@accId", int.Parse(acc.AccountId));
                }

                ushort[]   offerSearch  = new ushort[0];
                ItemData[] offerSearchD = new ItemData[0];
                if (Query["offerItems"] != null && Query["offerItems"] != "")
                {
                    offerSearch  = Utils.FromCommaSepString16z(Query["offerItems"]);
                    offerSearchD = new ItemData[offerSearch.Length];
                    if (Query["offerData"] != "")
                    {
                        offerSearchD = ItemDataList.CreateData(Query["offerData"]);
                    }
                }

                ushort[]   reqSearch  = new ushort[0];
                ItemData[] reqSearchD = new ItemData[0];
                if (Query["requestItems"] != null && Query["requestItems"] != "")
                {
                    reqSearch  = Utils.FromCommaSepString16z(Query["requestItems"]);
                    reqSearchD = new ItemData[reqSearch.Length];
                    if (Query["requestData"] != "")
                    {
                        reqSearchD = ItemDataList.CreateData(Query["requestData"]);
                    }
                }
                using (MySqlDataReader rdr = cmd.ExecuteReader())
                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            if (offerSearch.Length > 0)
                            {
                                List <ushort> offerItems = new List <ushort>(Utils.FromCommaSepString16z(rdr.GetString("offerItems")));
                                ItemData[]    offerData  = ItemDataList.CreateData(rdr.GetString("offerData"));
                                bool          success    = false;
                                for (int i = 0; i < offerSearch.Length; i++)
                                {
                                    int res = -1;
                                    if ((res = offerItems.IndexOf(offerSearch[i])) == -1)
                                    {
                                        continue;
                                    }
                                    success = true;
                                    break;
                                }
                                if (!success)
                                {
                                    continue;
                                }
                            }

                            if (reqSearch.Length > 0)
                            {
                                List <ushort> reqItems = new List <ushort>(Utils.FromCommaSepString16z(rdr.GetString("requestItems")));
                                ItemData[]    reqData  = ItemDataList.CreateData(rdr.GetString("requestData"));
                                bool          success  = false;
                                for (int i = 0; i < reqSearch.Length; i++)
                                {
                                    int res = -1;
                                    if ((res = reqItems.IndexOf(reqSearch[i])) == -1)
                                    {
                                        continue;
                                    }
                                    success = true;
                                    break;
                                }
                                if (!success)
                                {
                                    continue;
                                }
                            }

                            list.Offers.Add(new Offer
                            {
                                Id    = rdr.GetInt32("id"),
                                AccId = rdr.GetInt32("accId"),

                                Mine   = acc != null ? rdr.GetInt32("accId") == int.Parse(acc.AccountId) : false,
                                Status = rdr.GetInt32("status"),

                                _OfferItems = rdr.GetString("offerItems"),
                                _OfferData  = rdr.GetString("offerData"),

                                _RequestItems = rdr.GetString("requestItems"),
                                _RequestData  = rdr.GetString("requestData")
                            });
                        }
                    }
            }
            if (Query["filter"] != "mine" && Query["filter"] != "searched")
            {
                if (list.Offers.Count > 50)
                {
                    list.Offers.RemoveRange(50, list.Offers.Count - 50);
                }
            }

            XmlSerializer serializer = new XmlSerializer(list.GetType(), new XmlRootAttribute("Offers")
            {
                Namespace = ""
            });
            XmlWriterSettings xws = new XmlWriterSettings();

            xws.OmitXmlDeclaration = true;
            xws.Encoding           = Encoding.UTF8;
            xws.Indent             = true;
            XmlWriter xtw = XmlWriter.Create(Context.Response.OutputStream, xws);

            serializer.Serialize(xtw, list, list.Namespaces);
        }
예제 #23
0
        //Methods for adding data
        public void add()
        {
            bool boolemail         = true;
            bool boolposition      = true;
            bool boolpostaladdress = true;
            bool boolphonenumber   = true;
            bool boolyear          = true;
            bool boolbirthday      = true;

            MySqlDataReader reader = null;

            addDico.Clear();

            //if the Name and Company fields are filled and checked correctly
            if (isLettersAndSpaces(NewContactFirstNameTxtBox.Text) && isLettersAndSpaces(NewContactFirstNameTxtBox.Text) && isLettersDigitsAndSpaces(NewContactCompanyNameTxtBox.Text))
            {
                reader = mySimpleDataSource.Query("SELECT * FROM ContactDirectory WHERE FirstName='" + NewContactFirstNameTxtBox.Text + "' AND LastName='" + NewContactLastNameTxtBox.Text + "'  AND Company='" + NewContactCompanyNameTxtBox.Text + "'");
                if (reader.Read())
                {
                    reader.Close();
                    MessageBox.Show("The Contact already exist! ");
                }
                else
                {
                    reader.Close();

                    //I add the other information
                    addgender();
                    boolemail         = addemail();
                    boolposition      = addposition();
                    boolpostaladdress = addpostaladdress();
                    boolphonenumber   = addphonenumber();
                    boolyear          = addyear();
                    boolbirthday      = addbirthday();
                    addnotes();

                    if (boolemail && boolbirthday && boolphonenumber && boolposition && boolpostaladdress && boolyear)
                    {
                        mySimpleDataSource.Update("INSERT INTO ContactDirectory(id, FirstName, LastName, Company) VALUES(null, '" + NewContactFirstNameTxtBox.Text + "', '" + NewContactLastNameTxtBox.Text + "', '" + NewContactCompanyNameTxtBox.Text + "')");


                        //I get the Contact ID back in idnew
                        int idnew = 0;

                        reader = mySimpleDataSource.Query("SELECT * FROM ContactDirectory WHERE FirstName='" + NewContactFirstNameTxtBox.Text + "' AND LastName= '" + NewContactLastNameTxtBox.Text + "' AND Company='" + NewContactCompanyNameTxtBox.Text + "'");
                        if (reader.Read())
                        {
                            idnew = reader.GetInt32(0);
                        }
                        reader.Close();


                        mySimpleDataSource.NonQueryPreparedStatement("INSERT INTO ContactDetails (idkey, idcontact, iddictionary, data) VALUES(null," + idnew + ", @iddictionary, @data)", addDico);

                        MessageBox.Show("The contact has been successfully added to your database! ");
                        resetTxtBox();
                    }
                }
            }
            else
            {
                MessageBox.Show("You did not enter good values for the names and company! \n Be carefull to only use letters and spaces for the names. You can also have digits in the company name.");
            }
        }
예제 #24
0
파일: MySQL.cs 프로젝트: Landrut/CherryRP
        public static bool Login_Account(Client player, string inputPassword)
        {
            connection          = new MySqlConnection(myConnectionString);
            command             = connection.CreateCommand();
            command.CommandText = "SELECT * FROM accounts";
            connection.Open();
            Reader = command.ExecuteReader();
            while (Reader.Read())
            {
                string name         = Reader.GetString("Name");
                string password     = Reader.GetString("Password");
                int    cash         = Reader.GetInt32("Cash");
                int    bank         = Reader.GetInt32("BankMoney");
                int    rights       = Reader.GetInt32("Rights");
                int    gender       = Reader.GetInt32("Gender");
                int    fraction     = Reader.GetInt32("Fraction");
                int    fractionrank = Reader.GetInt32("FractionRank");
                int    job          = Reader.GetInt32("Job");
                int    jobrank      = Reader.GetInt32("JobRank");
                int    gang         = Reader.GetInt32("Gang");
                int    gangrank     = Reader.GetInt32("GangRank");
                int    onduty       = Reader.GetInt32("OnDuty");

                //int Mask = Reader.GetInt32("Mask");
                int Torso              = Reader.GetInt32("Torso");
                int Legs               = Reader.GetInt32("Legs");
                int Leg_Texture        = Reader.GetInt32("LegTexture");
                int Bag                = Reader.GetInt32("Bag");
                int Feet               = Reader.GetInt32("Feet");
                int Feet_Texture       = Reader.GetInt32("FeetTexture");
                int Accessorie         = Reader.GetInt32("Accessorie");
                int Accessorie_Texture = Reader.GetInt32("AccessorieTexture");
                int Undershirt         = Reader.GetInt32("Undershirt");
                int Undershirt_Texture = Reader.GetInt32("UndershirtTexture");
                int Decal              = Reader.GetInt32("Decal");
                int Top                = Reader.GetInt32("Top");
                int Top_Texture        = Reader.GetInt32("TopTexture");

                // prop's
                int Hat             = Reader.GetInt32("Hat");
                int Hat_Texture     = Reader.GetInt32("HatTexture");
                int Glasses         = Reader.GetInt32("Glasses");
                int Glasses_Texture = Reader.GetInt32("GlassesTexture");
                int Ears            = Reader.GetInt32("Ears");
                int Watches         = Reader.GetInt32("Watches");
                int Braceletes      = Reader.GetInt32("Braceletes");

                if (player.name == name && inputPassword == password)
                {
                    Debug(0, "Авторизация пользователя [" + name + "]" + " [" + player.address + "] " + "прошла успешно | " + password);

                    connection.Close();
                    player.setData("InGame", 1);
                    customskin_main.LoadCharacter(player);
                    Read_Licenses(player);

                    API.shared.setEntityPosition(player, new Vector3(-1037.747f, -2737.992f, 20.16927f));
                    API.shared.setEntityRotation(player, new Vector3(0, 0, -32.2951f));
                    //API.shared.setCameraBehindPlayer(player);

                    player.setData("cash_amount", cash);
                    player.setData("bank_amount", bank);
                    player.setData("rights_level", rights);
                    player.setData("gender_id", gender);
                    player.setData("fraction_id", fraction);
                    player.setData("fractionrank_id", fractionrank);
                    player.setData("job_id", job);
                    player.setData("jobrank_id", jobrank);
                    player.setData("gang_id", gang);
                    player.setData("gangrank_id", gangrank);
                    player.setData("onduty_status", onduty);

                    //player.setData("mask_id", Mask);
                    player.setData("torso_id", Torso);
                    player.setData("legs_id", Legs);
                    player.setData("legstexture_id", Leg_Texture);
                    player.setData("bag_id", Bag);
                    player.setData("feet_id", Feet);
                    player.setData("feettexture_id", Feet_Texture);
                    player.setData("accessorie_id", Accessorie);
                    player.setData("accessorietexture_id", Accessorie_Texture);
                    player.setData("undershirt_id", Undershirt);
                    player.setData("undershirttexture_id", Undershirt_Texture);
                    player.setData("decal_id", Decal);
                    player.setData("top_id", Top);
                    player.setData("toptexture_id", Top_Texture);
                    player.setData("hat_id", Hat);
                    player.setData("hattexture_id", Hat_Texture);
                    player.setData("glasses_id", Glasses);
                    player.setData("glassestexture_id", Glasses_Texture);
                    player.setData("ears_id", Ears);
                    player.setData("watches_id", Watches);
                    player.setData("braceletes_id", Braceletes);

                    API.shared.triggerClientEvent(player, "UpdateMoneyHUD", Convert.ToString(cash));
                    player.freeze(false);
                    API.shared.setEntityTransparency(player, 255);
                    return(true);
                }
            }
            player.setData("InGame", 0);
            Debug(1, "Неудачная попытка авторизации [" + player.name + "]" + " [" + player.address + "] " + "| неверный пароль");
            PlayerFunctions.Player.Login(player);
            API.shared.sendNotificationToPlayer(player, "~r~Неверный пароль!");
            Save_Account(player);
            connection.Close();
            return(false);
        }
예제 #25
0
        private void userRegid_TextChanged(object sender, EventArgs e)
        {
            string regid = userRegid.Text;

            if (!regid.Equals(""))
            {
                try
                {
                    string query = "SELECT * FROM `users` WHERE `regid` LIKE '" + regid + "%'";
                    using (command = new MySqlCommand(query, con))
                    {
                        con.Open();
                        reader = command.ExecuteReader();

                        if (reader.Read())
                        {
                            user_id = reader.GetInt32("id");
                            string lname = firstCharToUpper(reader.GetString("last_name"));
                            string fname = firstCharToUpper(reader.GetString("first_name"));
                            char   type  = reader.GetChar("type");
                            Console.WriteLine("User type: " + type);
                            switch (type)
                            {
                            case 't':
                                userIndex = 5;
                                user_type = "Багш";
                                returnDay = 21;
                                break;

                            case 's':
                                userIndex = 3;
                                user_type = "Оюутан";
                                returnDay = 14;
                                break;
                            }
                            int phone = reader.GetInt32("phone");
                            lbLname.Text = "Овог: " + lname;
                            lbFname.Text = "Нэр: " + fname;
                            lbPhone.Text = "Утас: " + phone;
                            lbType.Text  = "Төлөв: " + user_type + " нэг дор " + userIndex + "ш ном " + returnDay + " хоног авах боломжтой.";

                            // Users calculator return day
                            startDate  = DateTime.Parse(currentDate);
                            expiryDate = DateTime.Today.AddDays(returnDay);

                            // Current Year, Month, Day
                            DateTime startDateValue = (Convert.ToDateTime(startDate.ToString()));
                            string   cY             = startDateValue.Year.ToString();
                            string   cM             = startDateValue.Month.ToString();
                            string   cD             = startDateValue.Day.ToString();

                            // Expiry Year, Month, Day
                            DateTime expiryDateValue = (Convert.ToDateTime(expiryDate.ToString()));
                            string   fY = expiryDateValue.Year.ToString();
                            string   fM = expiryDateValue.Month.ToString();
                            string   fD = expiryDateValue.Day.ToString();

                            lbReturnTime.Text = "Буцаах хугацаа: " + cY + "." + cM + "." + cD + " - " + fY + "." + fM + "." + fD;

                            row = new int[userIndex];
                        }
                        con.Close();
                    }
                }
                catch (MySqlException ex)
                {
                    Console.WriteLine("User get data: " + ex.Message);
                }
            }
            else
            {
                lbLname.Text = "Овог: ";
                lbFname.Text = "Нэр: ";
                lbPhone.Text = "Утас: ";
                lbType.Text  = "Төлөв: ";
            }
        }
예제 #26
0
        public EditarPacienteModel ConsultarPacienteID(int idPaciente)
        {
            try {
                MySqlConnection connection = new MySqlConnection(getStringConnection());
                connection.Open();

                //----- Consulta OS DADOS PESSOAS DO PACIENTE -----

                var          DALSQL      = new PacienteDALSQL();
                MySqlCommand cmdPaciente = new MySqlCommand(DALSQL.ConsultarPacienteID(), connection);
                cmdPaciente.Parameters.AddWithValue("@IDPACIENTE", idPaciente);
                MySqlDataReader readerPaciente = cmdPaciente.ExecuteReader();

                EditarPacienteModel pacienteCompleto = new EditarPacienteModel();
                pacienteCompleto.Pessoa = new Models.Paciente.EditarPacienteModel.DadosPessoais();

                if (readerPaciente.HasRows)
                {
                    while (readerPaciente.Read())
                    {
                        pacienteCompleto.Pessoa.IdPessoa        = readerPaciente.GetInt32(0);
                        pacienteCompleto.Pessoa.Nome            = readerPaciente.GetString(1);
                        pacienteCompleto.Pessoa.CPF             = readerPaciente.GetString(2);
                        pacienteCompleto.Pessoa.RG              = readerPaciente.GetString(3);
                        pacienteCompleto.Pessoa.Sexo            = readerPaciente.GetString(4);
                        pacienteCompleto.Pessoa.DataNascimento  = readerPaciente.GetDateTime(5);
                        pacienteCompleto.Pessoa.Logradouro      = readerPaciente.GetString(6);
                        pacienteCompleto.Pessoa.Numero          = readerPaciente.GetInt32(7);
                        pacienteCompleto.Pessoa.Bairro          = readerPaciente.GetString(8);
                        pacienteCompleto.Pessoa.Cidade          = readerPaciente.GetString(9);
                        pacienteCompleto.Pessoa.Uf              = readerPaciente.GetString(10);
                        pacienteCompleto.Pessoa.TelefoneCelular = readerPaciente.GetString(11);
                        pacienteCompleto.Pessoa.Email           = readerPaciente.GetString(12);
                        pacienteCompleto.Pessoa.Status          = readerPaciente.GetInt32(13).ToString();
                    }
                }
                readerPaciente.Close();

                //----- -----

                //----- CONSULTA OS DADOS DA CONSULTA DO PACIENTE -----

                MySqlCommand cmdConsultaPaciente = new MySqlCommand(DALSQL.ConsultarPacienteConsulta(), connection);
                cmdConsultaPaciente.Parameters.AddWithValue("@IDPACIENTECONSULTA", idPaciente);
                MySqlDataReader readerConsultaPaciente = cmdConsultaPaciente.ExecuteReader();

                pacienteCompleto.Consulta = new List <DadosConsulta>();

                if (readerConsultaPaciente.HasRows)
                {
                    while (readerConsultaPaciente.Read())
                    {
                        DadosConsulta consulta = new DadosConsulta();

                        consulta.idConsulta         = readerConsultaPaciente.GetInt32(0);
                        consulta.idPacienteConsulta = readerConsultaPaciente.GetInt32(1);
                        consulta.dataConsulta       = readerConsultaPaciente.GetDateTime(2);
                        consulta.finalizada         = readerConsultaPaciente.GetInt32(3);

                        pacienteCompleto.Consulta.Add(consulta);
                    }
                    readerConsultaPaciente.NextResult();
                }
                readerConsultaPaciente.Close();
                //----- -----

                connection.Close();
                return(pacienteCompleto);
            } catch (Exception ex) {
                throw ex;
            }
        }
예제 #27
0
        private void button6_Click(object sender, EventArgs e)
        {
            string s = "", d = "";

            try
            {
                mconnect.Open();
                string stm = "SELECT house FROM facility WHERE facility.idfacility = @_id";
                cmd[0] = new MySqlCommand(stm, mconnect);
                cmd[0].Parameters.AddWithValue("@_id", _id);
                cmd[0].Parameters.AddWithValue("@_idhouse", _idhouse);
                rdr = cmd[0].ExecuteReader();
                while (rdr.Read())
                {
                    _idhouse = rdr.GetInt32(0);
                }
                rdr.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            try
            {
                cmd[0].CommandText = "DELETE FROM Metro WHERE Metro.facility_m = @_id";
                cmd[0].ExecuteNonQuery();

                cmd[0].CommandText = "DELETE FROM facility WHERE facility.idfacility = @_id";
                cmd[0].ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            try
            {
                cmd[0].CommandText = "SELECT Street_h FROM HouseNumber WHERE HouseNumber.idHouseNumber = @_idhouse";
                rdr = cmd[0].ExecuteReader();
                while (rdr.Read())
                {
                    s = rdr.GetString(0);
                }
                rdr.Close();

                cmd[0].CommandText = "SELECT District_h FROM HouseNumber WHERE HouseNumber.idHouseNumber = @_idhouse";
                rdr = cmd[0].ExecuteReader();
                while (rdr.Read())
                {
                    d = rdr.GetString(0);
                }
                rdr.Close();

                string stm2 = "DELETE FROM HouseNumber WHERE HouseNumber.idHouseNumber = @_idhouse";
                cmd[1] = new MySqlCommand(stm2, mconnect);
                cmd[1].Parameters.AddWithValue("@_idhouse", _idhouse);
                cmd[1].ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            try
            {
                cmd[0].CommandText = "DELETE FROM Districts WHERE Districts.District = @_d";
                cmd[0].Parameters.AddWithValue("@_d", d);
                cmd[0].ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            try
            {
                cmd[0].CommandText = "DELETE FROM Streets WHERE Streets.Street = @_s";
                cmd[0].Parameters.AddWithValue("@_s", s);
                cmd[0].ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            try
            {
                ds[1].Clear();
                da[1].Fill(ds[1], "facility");
                dataGridView2.DataSource = ds[1].Tables[0];
                ds[6].Clear();
                da[6].Fill(ds[6], "HouseNumber");
                dataGridView7.DataSource = ds[6].Tables[0];
                ds[7].Clear();
                da[7].Fill(ds[7], "Metro");
                dataGridView8.DataSource = ds[7].Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            if (mconnect != null)
            {
                mconnect.Close();
            }
        }
예제 #28
0
        public RelatorioPacienteModel RelatorioPaciente(RelatorioPacienteModel paciente, int idMedico)
        {
            try {
                var DALSQL = new PacienteDALSQL();
                using (MySqlConnection connection = new MySqlConnection(getStringConnection())) {
                    connection.Open();

                    MySqlCommand cmdPaciente = new MySqlCommand(DALSQL.RelatorioPaciente(paciente), connection);

                    cmdPaciente.Parameters.Add("@IDMEDICO", MySqlDbType.Int32).Value = idMedico;

                    if (paciente.psqNome != string.Empty && paciente.psqNome != null)
                    {
                        cmdPaciente.Parameters.Add("@NOME", MySqlDbType.String).Value = paciente.psqNome;
                    }
                    if (paciente.psqCPF != string.Empty && paciente.psqCPF != null)
                    {
                        cmdPaciente.Parameters.Add("@CPF", MySqlDbType.String).Value = paciente.psqCPF;
                    }
                    if (paciente.psqCPF != string.Empty && paciente.psqTelefoneCelular != null)
                    {
                        cmdPaciente.Parameters.Add("@TELEFONECELULAR", MySqlDbType.String).Value = paciente.psqTelefoneCelular;
                    }

                    var teste2 = getGeneratedSql(cmdPaciente);

                    MySqlDataReader reader = cmdPaciente.ExecuteReader();

                    RelatorioPacienteModel relatorioPacienteModel = new RelatorioPacienteModel();
                    relatorioPacienteModel.ListaPacientes = new List <ListPaciente>();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            ListPaciente pacienteModel = new ListPaciente();

                            pacienteModel.idPaciente      = reader.GetInt32(0);
                            pacienteModel.nome            = reader.GetString(1);
                            pacienteModel.cpf             = reader.GetString(2);
                            pacienteModel.telefoneCelular = reader.GetString(3);

                            relatorioPacienteModel.ListaPacientes.Add(pacienteModel);
                        }
                        reader.NextResult();
                    }
                    else
                    {
                        reader.Close();
                        connection.Close();
                        return(null);
                    }

                    reader.Close();
                    connection.Close();

                    return(relatorioPacienteModel);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #29
0
파일: Mon.cs 프로젝트: RogersNL/Epicodemons
        public List <MonType> GetMonTypes()
        {
            MySqlConnection conn = DB.Connection();

            conn.Open();
            MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;

            cmd.CommandText = @"SELECT types.* FROM mons
      JOIN mons_types ON (mons.id = mons_types.mons_id)
      JOIN types ON (mons_types.types_id = types.id)
      WHERE mons.id = @MonId;";

            cmd.Parameters.Add(new MySqlParameter("@MonId", _monId));

            MySqlDataReader rdr      = cmd.ExecuteReader() as MySqlDataReader;
            List <MonType>  monTypes = new List <MonType> {
            };

            while (rdr.Read())
            {
                int     typesId    = rdr.GetInt32(0);
                string  typesName  = rdr.GetString(1);
                int     fairy      = rdr.GetInt32(2);
                int     steel      = rdr.GetInt32(3);
                int     dark       = rdr.GetInt32(4);
                int     dragon     = rdr.GetInt32(5);
                int     ghost      = rdr.GetInt32(6);
                int     rock       = rdr.GetInt32(7);
                int     bug        = rdr.GetInt32(8);
                int     psychic    = rdr.GetInt32(9);
                int     flying     = rdr.GetInt32(10);
                int     ground     = rdr.GetInt32(11);
                int     poison     = rdr.GetInt32(12);
                int     fighting   = rdr.GetInt32(13);
                int     ice        = rdr.GetInt32(14);
                int     grass      = rdr.GetInt32(15);
                int     electric   = rdr.GetInt32(16);
                int     water      = rdr.GetInt32(17);
                int     fire       = rdr.GetInt32(18);
                int     normal     = rdr.GetInt32(19);
                MonType newMonType = new MonType(typesName, fairy, steel, dark, dragon, ghost, rock, bug, psychic, flying, ground, poison, fighting, ice, grass, electric, water, fire, normal, typesId);
                monTypes.Add(newMonType);
            }
            conn.Close();
            if (conn != null)
            {
                conn.Dispose();
            }
            return(monTypes);
            // return new List<MonType>{};
        }
예제 #30
0
        private T CreateModel <T>(MySqlDataReader dataReader)
        {
            Type modelType = typeof(T);

            if (modelType == typeof(UserModel))
            {
                UserModel user = new UserModel();
                user.Id   = dataReader.GetInt32(0);
                user.Name = dataReader.GetString(1);
                user.Pswd = dataReader.GetString(2);

                user.Privileges = (UserModel.UserPrivileges)
                                  Enum.Parse(typeof(UserModel.UserPrivileges), dataReader.GetString(4));
                return((T)Convert.ChangeType(user, typeof(T)));
            }
            else if (modelType == typeof(ProjectModel))
            {
                ProjectModel projectModel = new ProjectModel();
                projectModel.Id          = dataReader.GetInt32(0);
                projectModel.Name        = dataReader.GetString(1);
                projectModel.Description = dataReader.IsDBNull(2) ? null : dataReader.GetString(2);
                return((T)Convert.ChangeType(projectModel, typeof(T)));
            }
            else if (modelType == typeof(ActivityModel))
            {
                ActivityModel activity = new ActivityModel();
                activity.Id            = dataReader.GetInt32(0);
                activity.Name          = dataReader.GetString(1);
                activity.Description   = dataReader.IsDBNull(2) ? null : dataReader.GetString(2);
                activity.PlannedStart  = dataReader.GetDateTime(3);
                activity.PlannedFinish = dataReader.GetDateTime(4);
                activity.ActualStart   = dataReader.IsDBNull(5) ?  (DateTime?)null : dataReader.GetDateTime(5);
                activity.ActualFinish  = dataReader.IsDBNull(6) ? (DateTime?)null : dataReader.GetDateTime(6);
                activity.projectid     = dataReader.GetInt32(7);
                return((T)Convert.ChangeType(activity, typeof(T)));
            }
            else if (modelType == typeof(ProjectUser))
            {
                ProjectUser projectUser = new ProjectUser();
                projectUser.Project.Id          = dataReader.GetInt32(0);
                projectUser.Project.Name        = dataReader.GetString(1);
                projectUser.Project.Description = dataReader.IsDBNull(2) ? null : dataReader.GetString(2);
                projectUser.Project.Active      = dataReader.GetBoolean(3);

                projectUser.User.Name = dataReader.IsDBNull(5) ? null : dataReader.GetString(5);


                projectUser.User.Id = dataReader.IsDBNull(4)? (int?)null : dataReader.GetInt32(4);

                projectUser.User.Privileges = dataReader.IsDBNull(6) ? (UserModel.UserPrivileges?) null:
                                              (UserModel.UserPrivileges)Enum.Parse(typeof(UserModel.UserPrivileges), dataReader.GetString(6));

                projectUser.Role = dataReader.IsDBNull(7) ?(Role?)null :
                                   (Role)Enum.Parse(typeof(Role), dataReader.GetString(7));

                projectUser.User.Active = dataReader.IsDBNull(8) ? false : dataReader.GetBoolean(8);



                return((T)Convert.ChangeType(projectUser, typeof(T)));
            }
            else if (modelType == typeof(UserActivity))
            {
                UserActivity userAct = new UserActivity();
                userAct.UserId     = dataReader.GetInt32(0);
                userAct.ActivityId = dataReader.GetInt32(1);
                userAct.ProjectId  = dataReader.GetInt32(2);
                userAct.Progress   = dataReader.GetInt32(3);
                userAct.Comments   = dataReader.IsDBNull(4) ? null : dataReader.GetString(4);

                return((T)Convert.ChangeType(userAct, typeof(T)));
            }

            return(default(T));
        }