Exemplo n.º 1
0
        public IActionResult Main()
        {
            ViewBag.LogErrors = new List <string>();
            string email = HttpContext.Session.GetString("userpass");

            if (email == null)
            {
                ViewBag.LogErrors.Add("You need to log in first");
                TempData["LogErrors"] = ViewBag.LogErrors;
                return(RedirectToAction("Index"));
            }
            else
            {
                ViewBag.MessageErrors = TempData["MessageErrors"];
                ViewBag.CommentErrors = TempData["CommentErrors"];
                if (ViewBag.MessageErrors == null)
                {
                    ViewBag.MessageErrors = new List <string>();
                }
                if (ViewBag.CommentErrors == null)
                {
                    ViewBag.CommentErrors = new List <string>();
                }
                string selectQuery    = $"SELECT id FROM users WHERE email = '{email}'";
                var    younow         = MySqlConnector.Query(selectQuery);
                string selectMessages = $"SELECT users.firstName AS firstName,users.LastName AS lastName,messages.id AS id,messages.message AS message, messages.user_id AS message_user_id, messages.created_at AS created_at,messages.updated_at AS updated_at FROM users JOIN messages ON users.id = messages.user_id";
                string selectComments = $"SELECT users.firstName AS user_firstName,users.LastName AS user_lastName,messages.id AS message_id,messages.message AS message, messages.user_id AS message_user_id,messages.created_at AS message_created_at,messages.updated_at AS message_updated_at,comments.id AS comment_id,comments.comment AS comment, comments.message_id AS comment_message_id,comments.user_id AS comment_user_id, comments.created_at AS comment_created_at,comments.updated_at AS comment_updated_at FROM users JOIN comments ON users.id = comments.user_id JOIN messages ON comments.message_id = messages.id";
                var    messages       = MySqlConnector.Query(selectMessages);
                var    comments       = MySqlConnector.Query(selectComments);
                ViewBag.userid      = (int)younow[0]["id"];
                ViewBag.MessageList = messages;
                ViewBag.CommentList = comments;
                return(View("Main"));
            }
        }
Exemplo n.º 2
0
        public IActionResult quotes()
        {
            var allQuotes = MySqlConnector.Query("SELECT * FROM comments");

            ViewBag.quotes = allQuotes;
            return(View("quotes"));
        }
Exemplo n.º 3
0
        public static UserAccount Create(string username, string password, bool admin)
        {
            string role = (admin ? "admin" : "user");

            if (username.Length > 16 || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            if (Find(username) != null)
            {
                return(null);
            }

            MySqlConnection connection = MySqlConnector.GetConnection();

            if (connection != null)
            {
                MySqlCommand command = new MySqlCommand("INSERT INTO `users` VALUES(NULL, @username, @password, NOW(), NOW(), @role)", connection);
                command.Prepare();
                command.Parameters.AddWithValue("@username", username);
                command.Parameters.AddWithValue("@password", Hash(password));
                command.Parameters.AddWithValue("@role", role);
                command.ExecuteReader();
                connection.Close();
                return(Find(username));
            }

            return(null);
        }
Exemplo n.º 4
0
        public ActionResult Post(string tablename, [FromBody] object value)
        {
            ActionResult result = null;

            try
            {
                JArray array = (JArray)value;

                MySqlConnector connector = new MySqlConnector(_connectionString);

                foreach (JObject jObject in array.Children())
                {
                    Dictionary <string, string> updateSet = GetValues(jObject);

                    connector.InsertSingleRecord(tablename, updateSet);
                }



                result = NoContent();
            }
            catch (Exception ex)
            {
                result = StatusCode(500, new { Error = ex.Message });
            }

            return(result);
        }
Exemplo n.º 5
0
        public bool Exists(string name)
        {
            bool retVal = false;

            MySqlConnection connection = MySqlConnector.GetConnection();

            if (connection != null)
            {
                MySqlCommand command = new MySqlCommand("SELECT `id` FROM `channels` WHERE `channel_name`=@channel_name ORDER BY `id` ASC LIMIT 1", connection);
                command.Prepare();
                command.Parameters.AddWithValue("@channel_name", name);

                try
                {
                    MySqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        retVal = true;
                    }
                }
                catch
                {
                    Console.WriteLine("channels table: could not SELECT " + name);
                }
                connection.Close();
            }

            return(retVal);
        }
Exemplo n.º 6
0
        public IActionResult CreateQuote(string author, string content)
        {
            string query = $"INSERT INTO quotes (content, author, created_at, updated_at) VALUES ('{content}', '{author}', NOW(), NOW())";

            MySqlConnector.Execute(query);
            return(RedirectToAction("Quotes"));
        }
Exemplo n.º 7
0
        public static MySqlProviderAdapter GetInstance(string name)
        {
            if (name == ProviderName.MySqlConnector)
            {
                if (_mysqlConnectorInstance == null)
                {
                    lock (_mysqlConnectorSyncRoot)
                        if (_mysqlConnectorInstance == null)
                        {
                            _mysqlConnectorInstance = MySqlConnector.CreateAdapter();
                        }
                }

                return(_mysqlConnectorInstance);
            }
            else
            {
                if (_mysqlDataInstance == null)
                {
                    lock (_mysqlDataSyncRoot)
                        if (_mysqlDataInstance == null)
                        {
                            _mysqlDataInstance = MySqlData.CreateAdapter();
                        }
                }

                return(_mysqlDataInstance);
            }
        }
Exemplo n.º 8
0
        public void Store(TalkyChannel channel, bool writeToDB)
        {
            lock (_lock)
            {
                _channels.Add(channel);


                string lobbyString  = (channel is LobbyChannel ? "true" : "false");
                string lockedString = (channel.Locked ? "true" : "false");

                if (true == writeToDB)
                {
                    MySqlConnection connection = MySqlConnector.GetConnection();
                    if (connection != null)
                    {
                        MySqlCommand command = new MySqlCommand("INSERT INTO `channels` VALUES(NULL, @channel_name, @lobby_type, @locked)", connection);
                        command.Prepare();
                        command.Parameters.AddWithValue("@channel_name", channel.Name);
                        command.Parameters.AddWithValue("@lobby_type", lobbyString);
                        command.Parameters.AddWithValue("@locked", lockedString);
                        try
                        {
                            command.ExecuteReader();
                        }
                        catch
                        {
                            Console.WriteLine("channels table: could not INSERT " + channel.Name);
                        }
                        connection.Close();
                    }
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Load all tables list for the connection (oracle does not apply)
        /// </summary>
        /// <returns>List for all tables name</returns>
        public List <string> initAllTable(string scheme)
        {
            List <string> schemes = new List <string>();

            try
            {
                // An attempt to perform a database operation is considered incorrect if an exception is thrown
                if (DATABASE_TYPE == DataBaseType.MySql)
                {
                    MySqlConnector connector = MySqlConnector.GetInstance(IP, PORT, USER_NAME, PASSWORD, scheme);
                    DataTable      tb        = connector.ExecuteDataTable(Database.MYSQL_ALL_TABLES_SCRIPT);
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        schemes.Add(tb.Rows[i][0].ToString());
                    }
                }
                else if (DATABASE_TYPE == DataBaseType.SqlServer)
                {
                    // unsupport
                }
                else if (DATABASE_TYPE == DataBaseType.Oracle)
                {
                    // unsupport
                }
                else
                {
                    // unknow database, return the false
                }
            } catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }
            return(schemes);
        }
        public IActionResult Index()
        {
            var allNotes = MySqlConnector.Query("SELECT * FROM notes");

            ViewBag.allNotes = allNotes;
            return(View());
        }
Exemplo n.º 11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string _UserRut = HttpContext.Current.Session["_UserRut"].ToString();

            DataTable      dt    = new DataTable();
            MySqlConnector mysql = new MySqlConnector();

            mysql.ConnectionString = HttpContext.Current.Session["cnString"].ToString();

            mysql.AddProcedure("GetEmpresaByRut");
            mysql
            .AddParameter("_UserRut", _UserRut);
            // string x = mysql.ExecQuery().ToJson();
            dt = mysql.ExecQuery().ToDataTable();


            DropEmpresa.DataTextField  = "RAZON_SOCIAL";
            DropEmpresa.DataValueField = "ID_EMP";

            DropEmpresa.DataSource = dt;
            DropEmpresa.DataBind();

/*
 *          DropAmbiente.Items.Insert(0,new ListItem("Certificacion", "CERT"));
 *          DropAmbiente.Items.Insert(1, new ListItem("Produccion", "PROD"));*/
        }
Exemplo n.º 12
0
 /// <summary>
 /// Check if the current connection information is connected
 /// </summary>
 /// <param name="ip">Ip address</param>
 /// <param name="port">Port</param>
 /// <param name="userName">User name</param>
 /// <param name="password">Password</param>
 /// <param name="dbType">Type of DataBaseType</param>
 /// <returns>Returns true if it can connect, otherwise returns false</returns>
 public bool connect()
 {
     try
     {
         // An attempt to perform a database operation is considered incorrect if an exception is thrown
         if (DATABASE_TYPE == DataBaseType.MySql)
         {
             MySqlConnector connector = MySqlConnector.GetInstance(IP, PORT, USER_NAME, PASSWORD, "");
             DataTable      tb        = connector.ExecuteDataTable(Database.MYSQL_ALL_DATABASE_SCRIPT);
             tb.Rows[0]["Database"].ToString();
         }
         else if (DATABASE_TYPE == DataBaseType.SqlServer)
         {
             SqlServerConnector connector = SqlServerConnector.GetInstance(IP, USER_NAME, PASSWORD, "");
             DataTable          tb        = connector.ExecuteDataTable(Database.SQLSERVER_ALL_TABLE_SCRIPT);
             tb.Rows[0]["NAME"].ToString();
         }
         else if (DATABASE_TYPE == DataBaseType.Oracle)
         {
             OracleConnector connector = OracleConnector.GetInstance(IP, USER_NAME, PASSWORD);
             DataTable       tb        = connector.ExecuteDataTable(Database.ORACLE_ALL_USER_SCRIPT);
             tb.Rows[0][0].ToString();
         }
         else
         {
             // unknow database, return the false
             return(false);
         }
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 13
0
        public void GetViews()
        {
            MySqlConnector connector = new MySqlConnector(this.config);
            var            views     = connector.GetViews("sakila").Result.ToList();

            CollectionAssert.Contains(views, "actor_info");
        }
Exemplo n.º 14
0
        public void GetTables()
        {
            MySqlConnector connector = new MySqlConnector(this.config);
            var            tables    = connector.GetTables("sakila").Result.ToList();

            CollectionAssert.Contains(tables, "actor");
        }
Exemplo n.º 15
0
        public void GetDatabases()
        {
            MySqlConnector connector = new MySqlConnector(this.config);
            var            databases = connector.GetDatabases().Result.ToList();

            CollectionAssert.Contains(databases, "sakila");
        }
Exemplo n.º 16
0
        public MainViewModel()
        {
            SendCmd = new SendCmd(this);

            dbConnector = new MySqlConnector();
            Users       = dbConnector.GetAllUsers();
        }
Exemplo n.º 17
0
        protected void Login_Click(object sender, EventArgs e)
        {
            string _rut  = string.Empty;
            string _pass = string.Empty;

            _rut  = rut.Value;
            _pass = inputPassword.Value;

            DataTable      dt    = new DataTable();
            MySqlConnector mysql = new MySqlConnector();

            Session.Clear();
            HttpContext.Current.Session["cnString"] = cnString;
            mysql.ConnectionString = HttpContext.Current.Session["cnString"].ToString();

            mysql.AddProcedure("Login");
            mysql
            .AddParameter("Rut", _rut)
            .AddParameter("Contrasenia", _pass);



            dt = mysql.ExecQuery().ToDataTable();

            if (dt.Rows[0][0].ToString() == "FALSE")
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                HttpContext.Current.Session["_UserRut"] = _rut;
            }
            Response.Redirect("SeleccionEmpresa.aspx");
        }
Exemplo n.º 18
0
 public IActionResult addUser(string firstName, string lastName, int?age, string email, string password, string pw_confirm)
 {
     ViewBag.Errors = new List <string>();
     if (firstName == null || firstName.Length < 4)
     {
         ViewBag.Errors.Add("First name field has to have at least 4 characters.");
     }
     if (lastName == null || lastName.Length < 4)
     {
         ViewBag.Errors.Add("Last name field has to have at least 4 characters.");
     }
     if (age == null)
     {
         ViewBag.Errors.Add("You have to provide your age.");
     }
     if (email == null)
     {
         ViewBag.Errors.Add("You have to provide an e-mail address");
     }
     else
     {
         if (isValidEmail(email) == false)
         {
             ViewBag.Errors.Add("The email format provided is not correct");
         }
     }
     if (password == null || password.Length < 8)
     {
         ViewBag.Errors.Add("You have to provide a password");
     }
     if (pw_confirm == null || pw_confirm != password)
     {
         ViewBag.Errors.Add("Password and password confirmation do not match");
     }
     if (ViewBag.Errors.Count > 0)
     {
         TempData["Errors"] = ViewBag.Errors;
         return(RedirectToAction("Index"));
     }
     else
     {
         string selectQuery = $"SELECT * FROM users WHERE email = '{email}'";
         var    emailVal    = MySqlConnector.Query(selectQuery);
         if (emailVal.Count > 0)
         {
             ViewBag.Errors.Add("This e-mail already belongs to a registered user");
             TempData["Errors"] = ViewBag.Errors;
             return(RedirectToAction("Index"));
         }
         else
         {
             string rightNow = DateTime.Now.ToString("yyyyMMddHHmmss");
             string query    = $"INSERT INTO users (firstName,lastName,age,email,password,created_at,updated_at) VALUES ('{firstName}','{lastName}','{age}','{email}','{password}',{rightNow},{rightNow})";
             MySqlConnector.Execute(query);
             HttpContext.Session.SetString("userpass", (string)email);
             return(RedirectToAction("Index"));
         }
     }
 }
Exemplo n.º 19
0
        public IActionResult quote()
        {
            string query  = "SELECT * FROM quotes";
            var    quotes = MySqlConnector.Query(query);

            ViewBag.quotes = quotes;
            return(View("quotes"));
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Get()
        {
            // IEnumerable<Product> result = await _productService.GetProducts();
            MySqlConnector conn = new MySqlConnector();
            List <Sales>   list = conn.GetSalesData();

            return(Ok(list));
        }
Exemplo n.º 21
0
        public void Ping()
        {
            MySqlConnector sql = new MySqlConnector();

            sql.LoadConfig("IASERVER");
            string    query = @"UPDATE  `aoidata`.`maquina` SET  `ping` =  NOW() WHERE  `id` = " + mysql_id + " LIMIT 1;";
            DataTable sp    = sql.Query(query);
        }
Exemplo n.º 22
0
        private Response SavePfx(structCertificadoDigital certificadoDigital)
        {
            Response r = new Response();

            try
            {
                //paso 1 verificamos que el certificado y la password sean validos
                byte[] Cert         = System.Convert.FromBase64String(certificadoDigital.Base64);
                bool   _PASSWORD_OK = Utilities.VerifyPassword(Cert, certificadoDigital.Password);

                //paso 2 si la password del certificado es ok seguimos con el proceso
                if (_PASSWORD_OK == true)
                {
                    string RutaCertificado = WebConfigurationManager.AppSettings["Certificados"];
                    //RutaCertificado = RutaCertificado + certificadoDigital.RutEmpresa+".pfx";
                    //creamos la carpeta de la empresa utilizando el rut de la empresa como nombre
                    String rutaGuardado = RutaCertificado + certificadoDigital.RutEmpresa + "\\" + certificadoDigital.RutEmpresa + ".pfx";

                    MySqlConnector mysql = new MySqlConnector();
                    mysql.ConnectionString = WebConfigurationManager.ConnectionStrings["MySqlProvider"].ConnectionString;
                    mysql.AddProcedure("sp_ins_certificado_digital");
                    mysql.
                    AddParameter("rutEmpresa", certificadoDigital.RutEmpresa)
                    .AddParameter("Pwd", Utilities.Encryption(certificadoDigital.Password))
                    .AddParameter("Path", rutaGuardado)
                    .AddParameter("TypeFile", certificadoDigital.TypeFile);

                    DataTable dt = new DataTable();
                    dt = mysql.ExecQuery().ToDataTable();



                    if (dt.Rows[0]["InsertStatus"].ToString() == "OK")
                    {
                        Directory.CreateDirectory(RutaCertificado + certificadoDigital.RutEmpresa);
                        File.WriteAllBytes(rutaGuardado, Convert.FromBase64String(certificadoDigital.Base64));
                    }

                    r.code           = Code.OK;
                    r.type           = Type.text;
                    r.ObjectResponse = "Se ha ingresado el certificado correctamente!";
                }
                else
                {
                    r.code           = Code.ERROR;
                    r.type           = Type.text;
                    r.ObjectResponse = "La contraseña ingresada no es valida!";
                }
                return(r);
            }
            catch (Exception ex)
            {
                r.code           = Code.ERROR;
                r.type           = Type.text;
                r.ObjectResponse = ex.ToString();
                return(r);
            }
        }
        public static string sel_unidadmedida()
        {
            MySqlConnector mysql = new MySqlConnector();

            mysql.ConnectionString = HttpContext.Current.Session["cnString"].ToString();
            mysql.AddProcedure("sp_sel_unidadmedida");

            return(mysql.ExecQuery().ToJson());
        }
 public IActionResult Register(User user)
 {
     if (ModelState.IsValid)
     {
         MySqlConnector.Execute($"INSERT INTO logregusers (first_name, last_name, email, password, created_at, updated_at) VALUES ('{user.firstName}', '{user.lastName}', '{user.email}', '{user.password}', NOW(), NOW())");
         return(View("success"));
     }
     return(View("index"));
 }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            var sql = new MySqlConnector("Server=localhost;Database=timelinelogger;Uid=root;Pwd=qL26^N6lp&WU2#a3in#9%qOG$Y^sQ^uO");

            Console.WriteLine("Please enter Your MySql statement");
            var queryString = Console.ReadLine();

            sql.QueryDB(queryString);
            Console.ReadKey();
        }
Exemplo n.º 26
0
        public IActionResult Quotes()
        {
            string query  = "SELECT * FROM quotes";
            var    quotes = MySqlConnector.Query(query);

            ViewBag.Quotes = quotes;
            Console.WriteLine("test");
            Console.WriteLine(ViewBag.Quotes);
            return(View());
        }
Exemplo n.º 27
0
        public void MySqlExecuteQueryTest()
        {
            var sqlhelper = new Initializer();

            Connector mySqlConnector = new MySqlConnector("Server=127.0.0.1;Database=dboptimove;Uid=astro;Pwd=1qazxc;Allow Zero Datetime=False;Convert Zero Datetime=True");
            var dt = (System.Data.DataTable)sqlhelper.ExecuteQuery("SELECT * FROM promotions;", mySqlConnector);

            Assert.IsNotNull(dt);
            //Assert.AreEqual(2, dt.Rows.Count);
        }
        public static string GetReceptorByRut(string RutReceptor)
        {
            MySqlConnector mysql = new MySqlConnector();

            mysql.ConnectionString = HttpContext.Current.Session["cnString"].ToString();
            mysql.AddProcedure("sp_sel_receptorByRut");

            mysql.AddParameter("RutReceptor", RutReceptor);

            return(mysql.ExecQuery().ToJson());
        }
        public static string GetProductoByIdDte(string IdDte)
        {
            MySqlConnector mysql = new MySqlConnector();

            mysql.ConnectionString = HttpContext.Current.Session["cnString"].ToString();
            mysql.AddProcedure("sp_sel_detalle_productoByIdDte");

            mysql.AddParameter("IdDte", IdDte);

            return(mysql.ExecQuery().ToJson());
        }
        public static string GetRegion(string json)
        {
            //sp_sel_comuna
            MySqlConnector mysql = new MySqlConnector();

            mysql.ConnectionString = HttpContext.Current.Session["cnString"].ToString();
            mysql.AddProcedure("sp_sel_region");
            mysql.ParametersFromJson(json);

            return(mysql.ExecQuery().ToJson());
        }
Exemplo n.º 31
0
 private void connectdatabase_Click(object sender, EventArgs e)
 {
     try
     {
         connector = new MySqlConnector("127.0.0.1", "robottesting", "root", "");
     }
     catch (Exception er)
     {
         Console.WriteLine(er.Message);
     }
 }
Exemplo n.º 32
0
        public Form1(string version, bool restartWhenDone)
        {
            status = Status.Connecting;
            allowedToClose = false;
            currentGameVersion = version;
            connector = null;
            fileList = new DataTable();
            receivedSize = 0;
            restart = restartWhenDone;

            InitializeComponent();
            UpdateProgress();

            Shown += Form1_Shown;
        }
Exemplo n.º 33
0
 bool OpenMysqlConnection()
 {
     try
     {
         connector = new MySqlConnector(connectionString);
         connector.OpenConnection();
         return true;
     }
     catch (Exception e)
     {
         Console.WriteLine("Error: {0}", e.ToString());
         return false;
     }
 }