Exemplo n.º 1
0
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
		treeView.AppendColumn("id",new CellRendererText(),"text",0);
		treeView.AppendColumn("nombre",new CellRendererText(),"text",1);
		
		listStore = new ListStore (typeof(string),typeof(string));
		
		treeView.Model=listStore;
		
		mySqlConnection= new MySqlConnection(
			"server = localhost; Database=bdproductos; user id = root; password=sistemas");
		mySqlConnection.Open();
		
		MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
		mySqlCommand.CommandText = "select * from categoria";
		
		MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
		
		while(mySqlDataReader.Read()){
			object id = mySqlDataReader["id"].ToString();
			object nombre = mySqlDataReader["nombre"];
			listStore.AppendValues(id,nombre);
	
		}
	}
Exemplo n.º 2
0
        public string AddUser(string ime, string ura, string minuta)
        {
            try
            {
                string myConnection = "SERVER=studsrv.uni-mb.si;" + "DATABASE=varnepoti;" + "UID=ronzyfonzy;" + "PASSWORD=snopy02;";
                connect = new MySqlConnection(myConnection);
                connect.Open();

                /*maxInserts = connect.CreateCommand();
                maxInserts.CommandText = "SELECT MAX(id) AS max FROM EXT_REMINDER;";
                dataReader = maxInserts.ExecuteReader();
                dataReader.Read();
                int max = Convert.ToInt32(dataReader["max"].ToString());
                dataReader.Close();*/

                insertAlarm = connect.CreateCommand();
                //INSERT INTO `EXT_REMINDER` (`ime`, `ura`, `minuta`) VALUES ('test1', '23', '12')
                //insertAlarm.CommandText = "INSERT INTO EXT_REMINDER VALUES(" + 1 + ", '" + ime + "', '" + ura + "', '" + minuta + "');";
                insertAlarm.CommandText = "INSERT INTO `EXT_REMINDER` (`ime`, `ura`, `minuta`) VALUES ('" + ime + "', '" + ura + "', '" + minuta + "');";
                insertAlarm.ExecuteNonQuery();
                connect.Close();

                return "narejeno";
            }
            catch (Exception e)
            {
                return "ni_narejeno";
            }
        }
        public void CreateTableAndInsertData(MySqlConnection conn)
        {
            using (var command = conn?.CreateCommand())
            {
                //command to drop a table named "inventory" if it exists
                command.CommandText = "DROP TABLE IF EXISTS inventory;";
                //command execution
                command.ExecuteNonQuery();
                Notification.Print("Finished dropping table (if existed)");

                //command to create a table named "inventory"
                command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
                //command execution
                command.ExecuteNonQuery();
                Notification.Print("Finished creating table");

                //command to insert an item into a table
                command.CommandText = @"INSERT INTO inventory (name, quantity) VALUES (@name1, @quantity1),
                        (@name2, @quantity2), (@name3, @quantity3);";

                //parameter substitution
                command.Parameters.AddWithValue("@name1", "banana");
                command.Parameters.AddWithValue("@quantity1", 150);
                command.Parameters.AddWithValue("@name2", "orange");
                command.Parameters.AddWithValue("@quantity2", 154);
                command.Parameters.AddWithValue("@name3", "apple");
                command.Parameters.AddWithValue("@quantity3", 100);

                //command execution
                int rowCount = command.ExecuteNonQuery();
                Notification.Print(String.Format("Number of rows inserted={0}", rowCount));
            }
        }
Exemplo n.º 4
0
	protected void OnRefreshActionActivated (object sender, System.EventArgs e)
	{
		listStore.Clear();
		
		listStore = new ListStore (typeof(string),typeof(string));
		
		treeView.Model=listStore;
		
		mySqlConnection= new MySqlConnection(
			"server = localhost; Database=bdproductos; user id = root; password=sistemas");
		mySqlConnection.Open();
		
		MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
		mySqlCommand.CommandText = "select * from categoria";
		
		MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
		
		while(mySqlDataReader.Read()){
			object id = mySqlDataReader["id"].ToString();
			object nombre = mySqlDataReader["nombre"];
			listStore.AppendValues(id,nombre);
	
		}
	}
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((1 == 1))
            {
                StringBuilder text = new StringBuilder(tainted_2);
                text.Replace("&", "&");
                text.Replace("'", "'");
                text.Replace(@"""", """);
                text.Replace("<", "&lt;");
                text.Replace(">", "&gt;");
                tainted_3 = text.ToString();
            }
            else if (!(1 == 1))
            {
                {}
            }
            else
            {
                {}
            }

            //flaw

            string query = "SELECT * FROM Articles WHERE id=" + tainted_3;


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandText = query;
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((Math.Pow(4, 2) <= 42))
            {
                {}
            }
            else
            {
                string pattern = @"/^[0-9]*$/";
                Regex  r       = new Regex(pattern);
                Match  m       = r.Match(tainted_2);
                if (!m.Success)
                {
                    tainted_3 = "";
                }
                else
                {
                    tainted_3 = tainted_2;
                }
            }

            string query        = "SELECT * FROM Articles WHERE id=@placeholder";
            string checked_data = tainted_3;


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd = new MySqlCommand(query);
                cmd.Parameters.AddWithValue("@placeholder", checked_data);
                cmd.Prepare();
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 7
0
        // GET: MyPoetry
        public ActionResult Index(int?page)
        {
            List <Publish>  pt = new List <Publish>();
            MySqlConnection myConn;
            MySqlDataReader dataReader;

            myConn = new MySqlConnection(TaqtiController.connectionString);
            myConn.Open();
            MySqlCommand cmd = new MySqlCommand(TaqtiController.connectionString);

            cmd = myConn.CreateCommand();
            int maxCount = 1;
            int maxPages = 1;
            int residue  = 0;

            cmd.CommandText = "select count(id) from mypoetry where publish = '1';";
            dataReader      = cmd.ExecuteReader();
            while (dataReader.Read())
            {
                maxCount = dataReader.GetInt32(0);
            }
            myConn.Close();
            maxPages = maxCount / 18;
            residue  = maxCount - maxPages * 18;
            if (residue > 0)
            {
                maxPages = maxPages + 1;
            }
            if (page == null || page == 1)
            {
                MySqlConnection myConn2;
                MySqlDataReader dataReader2;
                myConn2 = new MySqlConnection(TaqtiController.connectionString);
                myConn2.Open();
                MySqlCommand cmd2 = new MySqlCommand(TaqtiController.connectionString);
                cmd2             = myConn2.CreateCommand();
                cmd2.CommandText = "select * from mypoetry  where publish = '1' order by id DESC limit 0,18";
                dataReader2      = cmd2.ExecuteReader();
                while (dataReader2.Read())
                {
                    Publish p = new Publish();
                    p.id    = dataReader2.GetInt32(0);
                    p.text  = dataReader2.GetString(4);
                    p.name  = dataReader2.GetString(1);
                    p.title = dataReader2.GetString(3);
                    try
                    {
                        p.url = dataReader2.GetString(2);
                    }
                    catch
                    {
                    }
                    try
                    {
                        p.date = dataReader2.GetDateTime(6);
                    }
                    catch
                    {
                    }
                    p.mozun       = dataReader2.GetInt32(8);
                    p.maxpages    = maxPages;
                    p.currentPage = 1;
                    pt.Add(p);
                }
                myConn2.Close();
            }
            else
            {
                MySqlConnection myConn2;
                MySqlDataReader dataReader2;
                myConn2 = new MySqlConnection(TaqtiController.connectionString);
                myConn2.Open();
                MySqlCommand cmd2 = new MySqlCommand(TaqtiController.connectionString);
                cmd2             = myConn2.CreateCommand();
                cmd2.CommandText = "select * from mypoetry  where publish = '1' order by id DESC limit @init,@count";
                if (page == maxPages && residue > 0)
                {
                    cmd2.Parameters.AddWithValue("@init", (page - 1) * 18);
                    cmd2.Parameters.AddWithValue("@count", residue);
                }
                else
                {
                    cmd2.Parameters.AddWithValue("@init", (page - 1) * 18);
                    cmd2.Parameters.AddWithValue("@count", 18);
                }

                dataReader2 = cmd2.ExecuteReader();
                while (dataReader2.Read())
                {
                    Publish p = new Publish();
                    p.id    = dataReader2.GetInt32(0);
                    p.text  = dataReader2.GetString(4);
                    p.name  = dataReader2.GetString(1);
                    p.title = dataReader2.GetString(3);
                    try
                    {
                        p.url = dataReader2.GetString(2);
                    }
                    catch
                    {
                    }
                    try
                    {
                        p.date = dataReader2.GetDateTime(6);
                    }
                    catch
                    {
                    }

                    p.mozun       = dataReader2.GetInt32(8);
                    p.maxpages    = maxPages;
                    p.currentPage = (int)page;
                    pt.Add(p);
                }
                myConn2.Close();
            }
            return(View(pt));
        }
Exemplo n.º 8
0
    protected void btnSaveAcademicDetail_Click(object sender, EventArgs e)
    {
        if (checkerPdeg)
        {
            SetRowDataPDeg();
        }
        if (chekcerPHDdeg)
        {
            SetRowDataPhdDeg();
        }

        MySqlConnection connection = new MySqlConnection("server=localhost;user id=root; password = tiger; database=recruitmentdatabase; persistsecurityinfo=True");

        try
        {
            connection.Open();
        }
        catch (MySqlException ex)
        {
            //exception while opening the connection
        }
        int rowIndex = 0;

        if (ViewState["CurrentPDegTable"] != null)
        {
            DataTable deg_dt = (DataTable)ViewState["CurrentPDegTable"];
            if (deg_dt.Rows.Count > 0)
            {
                for (int i = 0; i < deg_dt.Rows.Count; i++)
                {
                    string pdegtype  = deg_dt.Rows[i]["Col1"].ToString();
                    string pdegname  = deg_dt.Rows[i]["Col2"].ToString();
                    string pdegboard = deg_dt.Rows[i]["Col3"].ToString();
                    string pdegyear  = deg_dt.Rows[i]["Col4"].ToString();
                    string pdegDiv   = deg_dt.Rows[i]["Col5"].ToString();
                    string pdegGrade = deg_dt.Rows[i]["Col6"].ToString();
                    string pdegSubs  = deg_dt.Rows[i]["Col7"].ToString();

                    MySqlCommand cmd = connection.CreateCommand();

                    cmd.CommandText = "INSERT INTO edu_core(User_ID,DegreeType,DegreeName,University,Year,Division,Percentage,Subjects) values (@uid,@degType,@degName," +
                                      "@university,@year,@division,@percentage,@subjects)";

                    cmd.Parameters.AddWithValue("@uid", user_id);
                    cmd.Parameters.AddWithValue("@degType", pdegtype);
                    cmd.Parameters.AddWithValue("@degName", pdegname);
                    cmd.Parameters.AddWithValue("@university", pdegboard);
                    cmd.Parameters.AddWithValue("@year", pdegyear);
                    cmd.Parameters.AddWithValue("@division", pdegDiv);
                    cmd.Parameters.AddWithValue("@percentage", pdegGrade);
                    cmd.Parameters.AddWithValue("@subjects", pdegSubs);
                    try
                    {
                        cmd.ExecuteNonQuery();
                        stage1_success = true;
                    }
                    catch (MySqlException ex)
                    {
                        // exception while executing the mysql query
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }

                    cmd.Parameters.Clear();
                    rowIndex++;
                }
            }
        }

        int rowIndex2 = 0;

        if (ViewState["CurrentPhdDegTable"] != null)
        {
            DataTable deg_dt = (DataTable)ViewState["CurrentPhdDegTable"];
            if (deg_dt.Rows.Count > 0)
            {
                for (int i = 0; i < deg_dt.Rows.Count; i++)
                {
                    gridPhdDeg.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    string phdDeggName  = deg_dt.Rows[i]["Col1"].ToString();
                    string phdDeggUni   = deg_dt.Rows[i]["Col2"].ToString();
                    string phdDeggDor   = deg_dt.Rows[i]["Col3"].ToString();
                    string phdDeggDos   = deg_dt.Rows[i]["Col4"].ToString();
                    string phdRegNo     = deg_dt.Rows[i]["Col5"].ToString();
                    string phdDeggTitle = deg_dt.Rows[i]["Col6"].ToString();

                    MySqlCommand cmd = connection.CreateCommand();

                    cmd.CommandText = "INSERT INTO edu_doctorate(User_ID,DegreeName,University,RegistrationDate,SubmissionDate,RegistrationNo,ThesisTitle) values (@uid,@degName," +
                                      "@university,@regDate, @subDate,@regNo,@thesisTitle)";

                    cmd.Parameters.AddWithValue("@uid", user_id);
                    cmd.Parameters.AddWithValue("@degName", phdDeggName);
                    cmd.Parameters.AddWithValue("@university", phdDeggUni);
                    cmd.Parameters.AddWithValue("@regDate", phdDeggDor);
                    cmd.Parameters.AddWithValue("@subDate", phdDeggDos);
                    cmd.Parameters.AddWithValue("@regNo", phdRegNo);
                    cmd.Parameters.AddWithValue("@thesisTitle", phdDeggTitle);
                    try
                    {
                        cmd.ExecuteNonQuery();
                        stage2_success = true;
                    }
                    catch (MySqlException ex)
                    {
                        // exception while executing the mysql query
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }

                    cmd.Parameters.Clear();

                    rowIndex2++;
                }
            }
        }

        if (netJrflist.SelectedItem.Text.Equals("Yes"))
        {
            string isQual   = netJrflist.SelectedItem.Text;
            string year     = netYear.Text;
            string examQual = "";
            string subject  = "";
            string netOrJrf = "";
            string certNo   = rollNo.Text;

            if (examQualified.SelectedItem.Text.Equals("UGC"))
            {
                examQual = "UGC";
                subject  = subUGC.SelectedItem.Text;
                netOrJrf = selNetJrf.SelectedItem.Text;
            }
            else if (examQualified.SelectedItem.Text.Equals("CSIR"))
            {
                examQual = "CSIR";
                subject  = subCSIR.SelectedItem.Text;
                netOrJrf = selNetJrf.SelectedItem.Text;
            }
            else if (examQualified.SelectedItem.Text.Equals("ICAR"))
            {
                examQual = "ICAR";
                subject  = subICAR.SelectedItem.Text;
                netOrJrf = selNetJrf.SelectedItem.Text;
            }
            else if (examQualified.SelectedItem.Text.Equals("Others"))
            {
                examQual = subOtherExam.Text;
                subject  = subOtherExam.Text;
            }


            try
            {
                //connection.Open();
            }
            catch (MySqlException ex)
            {
                //exception while opening the connection
            }
            MySqlCommand cmd = connection.CreateCommand();

            cmd.CommandText = "INSERT INTO edu_net(User_ID,IsQualified,QualificationYear,ExamBody,ExamType,Subject,CertificateNo) values (@uid,@isQual," +
                              "@qualYear,@examBody,@examType,@subject,@certNo)";

            cmd.Parameters.AddWithValue("@uid", user_id);
            cmd.Parameters.AddWithValue("@isQual", isQual);
            cmd.Parameters.AddWithValue("@qualYear", year);
            cmd.Parameters.AddWithValue("@examBody", examQual);
            cmd.Parameters.AddWithValue("@examType", netOrJrf);
            cmd.Parameters.AddWithValue("@subject", subject);
            cmd.Parameters.AddWithValue("@certNo", certNo);

            try
            {
                cmd.ExecuteNonQuery();
                stage3_success = true;

                string insert_com = "update application_status set Academic_Details = 1 where User_ID = " + user_id.ToString();
                using (MySqlCommand update_details = new MySqlCommand(insert_com, connection))
                {
                    try
                    {
                        update_details.ExecuteNonQuery();
                        update_details.Dispose();
                        System.Diagnostics.Debug.WriteLine("Registered successfully......!");
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                        Response.Write("<b>something really bad happened.....Please try again</b> ");
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            catch (MySqlException ex)
            {
                // exception while executing the mysql query
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }



            if (connection != null)
            {
                connection.Close();
            }
        }

        if (stage1_success && stage2_success && stage3_success)
        {
            System.Diagnostics.Debug.WriteLine("Experience.aspx");

            //Response.Redirect("Experience.aspx");
            AcademicDetails_1_Preview();
            AcademicDetails_2_Preview();
            AcademicDetails_3_Preview();
            cardAcademicDetails_1.Visible         = false;
            cardAcademicDetails_2.Visible         = false;
            cardAcademicDetails_3.Visible         = false;
            cardAcademicDetails_1_Preview.Visible = true;
            cardAcademicDetails_2_Preview.Visible = true;
            cardAcademicDetails_3_Preview.Visible = true;
            btnProceedAcademicDetail.Visible      = true;
            btnSaveAcademicDetail.Visible         = false;
        }
    }
Exemplo n.º 9
0
        public SimpleResponse GetSystemAvatars(string accountId, string avatarId, string isDefault, string isEnabled)
        {
            mServiceLog.Log.InfoFormat("GetSystemAvatars: accountId={0}, avatarId={1}, isDefault={2}, isEnabled={3}", accountId, avatarId, isDefault, isEnabled);
            StringBuilder sqlOptions = new StringBuilder();

            StringBuilder xmlBuilder = new StringBuilder();

            try
            {
                using (MySqlConnection mysqlConnection = new MySqlConnection(WebConfig.AvatarsDBConnectionString))
                {
                    mysqlConnection.Open();
                    string getAvatarsForAccountQuery = "SELECT * FROM SystemAvatars  " +
                                                       "LEFT JOIN AccountToAvatarMapping ON (AccountToAvatarMapping.AvatarId = SystemAvatars.AvatarId) " +
                                                       "WHERE 1 ";


                    List <XElement> avatarList = new List <XElement>();
                    using (MySqlCommand getAvatarsCommand = mysqlConnection.CreateCommand())
                    {
                        if (!String.IsNullOrEmpty(avatarId))
                        {
                            sqlOptions.Append("AND AccountToAvatarMapping.AvatarId=@AvatarId ");
                            getAvatarsCommand.Parameters.AddWithValue("@AvatarId", avatarId);
                        }
                        if (!String.IsNullOrEmpty(accountId))
                        {
                            sqlOptions.Append("AND AccountToAvatarMapping.HangoutAccountId=@HangoutAccountId ");
                            getAvatarsCommand.Parameters.AddWithValue("@HangoutAccountId", accountId);
                        }
                        if (!String.IsNullOrEmpty(isDefault))
                        {
                            string boolValue = "0";
                            if (isDefault == "1" || isDefault.ToLower() == "true")
                            {
                                boolValue = "1";
                            }
                            sqlOptions.Append("AND AccountToAvatarMapping.IsDefault=@IsDefault ");
                            getAvatarsCommand.Parameters.AddWithValue("@IsDefault", boolValue);
                        }
                        if (!String.IsNullOrEmpty(isEnabled))
                        {
                            string boolValue = "0";
                            if (isEnabled == "1" || isEnabled.ToLower() == "true")
                            {
                                boolValue = "1";
                            }
                            sqlOptions.Append("AND SystemAvatars.IsEnabled=@IsEnabled ");
                            getAvatarsCommand.Parameters.AddWithValue("@IsEnabled", boolValue);
                        }

                        getAvatarsForAccountQuery += sqlOptions.ToString();
                        getAvatarsForAccountQuery += "ORDER BY AccountToAvatarMapping.AvatarId; ";

                        getAvatarsCommand.CommandText = getAvatarsForAccountQuery;
                        using (MySqlDataReader getAvatarsReader = getAvatarsCommand.ExecuteReader())
                        {
                            while (getAvatarsReader.Read())
                            {
                                xmlBuilder.Append(FormatAvatarData(
                                                      getAvatarsReader["AvatarId"].ToString(),
                                                      getAvatarsReader["IsEnabled"].ToString(),
                                                      getAvatarsReader["IsDefault"].ToString(),
                                                      getAvatarsReader["HangoutAccountId"].ToString(),
                                                      getAvatarsReader["AvatarDNA"].ToString()
                                                      ));
                            }
                        }
                    }
                }
                return(new SimpleResponse("Avatars", xmlBuilder.ToString()));
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            do
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();

                break;
            }while((4 + 2 <= 42));

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandText = query;
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 11
0
    protected void GradeAssignment(string path, string userId, string assignmentID, string userName, string assignmentName)
    {
        ///////////////////
        string          sampleInput = null, sampleOutput = null;
        DataTable       dt         = null;
        MySqlConnection connection = new MySqlConnection(connectionString);

        connection.Open();
        try
        {
            MySqlCommand comm = connection.CreateCommand();
            comm.CommandText = "SELECT assignmentId,sampleInput,sampleOutput FROM testcases where assignmentId=@assignmentId";
            comm.Parameters.AddWithValue("@assignmentId", assignID);
            MySqlDataAdapter adap = new MySqlDataAdapter(comm);
            DataSet          ds   = new DataSet();
            adap.Fill(ds);
            dt = ds.Tables[0];
        }
        catch (Exception ex)
        {
            Response.Redirect("~/Error");
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
        if (dt.Rows.Count == 0)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "Error", "<script language='javascript'>alert('Submission Failed. Please retry.')</script>");
            return;
        }
        double  sum = 0;
        int     numberOfTestcases = 0;
        Literal resultHTML        = new Literal();
        string  htmlSample        = "";

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string output = "";
            sampleInput  = dt.Rows[i][1].ToString();
            sampleOutput = dt.Rows[i][2].ToString();
            string exeOutput = "";
            if (sampleInput != null && sampleInput != "")
            {
                exeOutput = CheckAssignmentZip(userId, assignmentID, assignmentName, ToStream(sampleInput));

                if (exeOutput == sampleOutput)
                {
                    output = "100%";
                    sum    = sum + 100;
                    numberOfTestcases++;
                }
                else
                {
                    output = "test case failed..!!";
                    sum    = sum + 0;
                    numberOfTestcases++;
                }
            }
            string resultInnerHTML = "<hr /><div class='container'>" +
                                     "<div class='container' style='width: 100%;'>" +
                                     "<div class='panel panel-default'>" +
                                     "<div class='panel-heading' style='align-content: center; font-weight: bold'>Test Case " + (i + 1) + "</div>" +
                                     "<div class='panel-body'>" +
                                     "<h4>" + output + "</h4>" +
                                     "<asp:LinkButton runat='server' title='Sample Input' data-toggle='popover' data-trigger='hover' data-content='" + sampleInput + "'>Sample Input</asp:LinkButton><br />" +
                                     "<asp:LinkButton runat='server' title='Sample Output' data-toggle='popover' data-trigger='hover' data-content='" + sampleOutput + "'>Sample Output</asp:LinkButton><br />" +
                                     "<asp:LinkButton runat='server' title='Executed Output' data-toggle='popover' data-trigger='hover' data-content='" + exeOutput + "'>Executed Output</asp:LinkButton><br />" +
                                     "</div></div></div></div>";
            htmlSample = htmlSample + resultInnerHTML;
        }
        resultHTML.Text = htmlSample;
        testcasePHMain.Controls.Add(resultHTML);

        MySqlConnection conn = new MySqlConnection(connectionString);

        conn.Open();
        string maxpoints = "";

        try
        {
            MySqlCommand mysqlcmd = conn.CreateCommand();
            mysqlcmd.CommandText = "SELECT points FROM assignments WHERE assignmentId=@assignmentId";
            mysqlcmd.Parameters.AddWithValue("assignmentId", assignmentID);
            maxpoints = mysqlcmd.ExecuteScalar().ToString();
        }
        catch (Exception ex)
        {
            Response.Redirect("~/Error");
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
        double percentage = (((sum / numberOfTestcases) / 100) * Convert.ToInt32(maxpoints));

        percentLBL.Text  = percentage.ToString() + " out of " + maxpoints;
        outputPH.Visible = true;
        /////////////////////////////
        var             result = 0;
        MySqlConnection conn1  = new MySqlConnection(connectionString);

        conn1.Open();
        try
        {
            MySqlCommand mysqlcmd = conn1.CreateCommand();
            mysqlcmd.CommandText = "SELECT count(*) FROM studentassignments WHERE assignmentId=@assignmentId AND studentId=@userId";
            mysqlcmd.Parameters.AddWithValue("assignmentId", assignmentID);
            mysqlcmd.Parameters.AddWithValue("userId", userId);
            result = Convert.ToInt32(mysqlcmd.ExecuteScalar());
        }
        catch (Exception ex)
        {
            Response.Redirect("~/Error");
        }
        finally
        {
            if (conn1.State == ConnectionState.Open)
            {
                conn1.Close();
            }
        }

        if (result <= 0)
        {
            MySqlConnection conn2 = new MySqlConnection(connectionString);
            MySqlCommand    cmd;
            conn2.Open();
            try
            {
                cmd             = conn2.CreateCommand();
                cmd.CommandText = "INSERT INTO studentassignments(assignmentId,studentId,points,comments,zipFileName,filePath) VALUES(@assignmentId,@studentId,@points,@comments,@zipFileName,@filePath)";
                cmd.Parameters.AddWithValue("@assignmentID", assignID);
                cmd.Parameters.AddWithValue("@studentId", userID);
                cmd.Parameters.AddWithValue("@points", (int)percentage);
                cmd.Parameters.AddWithValue("@comments", "");
                cmd.Parameters.AddWithValue("@zipFileName", userID + "_" + assignID + ".zip");
                cmd.Parameters.AddWithValue("@filePath", path);
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "Error", "<script language='javascript'>alert('Submission Failed. Please retry.')</script>");
                Response.Redirect("~/Error");
            }
            finally
            {
                if (conn2.State == ConnectionState.Open)
                {
                    conn2.Close();
                }
            }
        }
        if (result > 0)
        {
            MySqlConnection conn3 = new MySqlConnection(connectionString);
            MySqlCommand    cmd;
            conn3.Open();
            try
            {
                cmd             = conn3.CreateCommand();
                cmd.CommandText = "UPDATE studentassignments SET points=@points,comments=@comments,zipFileName=@zipFileName,filePath=@filePath where assignmentId=@assignmentID and studentId=@studentId";
                cmd.Parameters.AddWithValue("@assignmentID", assignID);
                cmd.Parameters.AddWithValue("@studentId", userID);
                cmd.Parameters.AddWithValue("@points", (int)percentage);
                cmd.Parameters.AddWithValue("@comments", "");
                cmd.Parameters.AddWithValue("@zipFileName", userID + "_" + assignID + ".zip");
                cmd.Parameters.AddWithValue("@filePath", path);
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "Error", "<script language='javascript'>alert('Submission Failed. Please retry.')</script>");
                Response.Redirect("~/Error");
            }
            finally
            {
                if (conn3.State == ConnectionState.Open)
                {
                    conn3.Close();
                }
                LoadStudentGridView();
                checkAssignmentSubmission();
            }
        }
    }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            tainted_2 = "hardcoded";

            tainted_3 = tainted_2;

            if ((4 + 2 >= 42))
            {
                {}
            }
            else if (!(4 + 2 >= 42))
            {
                {}
            }
            else
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }

            string query        = "SELECT * FROM Articles WHERE id=@placeholder";
            string checked_data = tainted_3;


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd = new MySqlCommand(query);
                cmd.Parameters.AddWithValue("@placeholder", checked_data);
                cmd.Prepare();
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 13
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (comFromBank.SelectedIndex != -1 && comToBank.SelectedIndex != -1 && txtMoney.Text != "")
                {
                    if ((comFromBank.Text) != (comToBank.Text))
                    {
                        dbconnection.Open();
                        string       query          = "select Bank_Stock from bank where Bank_ID=" + comFromBank.SelectedValue;
                        MySqlCommand comand         = new MySqlCommand(query, dbconnection);
                        double       FromBank_Stock = Convert.ToDouble(comand.ExecuteScalar().ToString());

                        query  = "select Bank_Stock from bank where Bank_ID=" + comToBank.SelectedValue;
                        comand = new MySqlCommand(query, dbconnection);
                        double ToBank_Stock = Convert.ToDouble(comand.ExecuteScalar().ToString());

                        double money = 0;
                        if (double.TryParse(txtMoney.Text, out money))
                        {
                            if (money > FromBank_Stock)
                            {
                                MessageBox.Show("لا يوجد ما يكفى");
                                dbconnection.Close();
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("المبلغ المدفوع يجب ان يكون عدد");
                            dbconnection.Close();
                            return;
                        }

                        if (!flagCategoriesSuccess)
                        {
                            if (MessageBox.Show("لم يتم ادخال الفئات..هل تريد الاستمرار؟", "تنبية", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                            {
                                return;
                            }
                        }

                        int    FromBranchId = 0, ToBranchId = 0;
                        string FromBranchName = "", ToBranchName = "";
                        if (radFromSafe.Checked)
                        {
                            string       q       = "SELECT Branch_ID FROM bank where Bank_ID=" + comFromBank.SelectedValue;
                            MySqlCommand command = new MySqlCommand(q, dbconnection);
                            FromBranchId = Convert.ToInt16(command.ExecuteScalar().ToString());

                            q              = "SELECT Branch_Name FROM bank where Bank_ID=" + comFromBank.SelectedValue;
                            command        = new MySqlCommand(q, dbconnection);
                            FromBranchName = command.ExecuteScalar().ToString();
                        }

                        if (radToSafe.Checked)
                        {
                            string       q       = "SELECT Branch_ID FROM bank where Bank_ID=" + comToBank.SelectedValue;
                            MySqlCommand command = new MySqlCommand(q, dbconnection);
                            ToBranchId = Convert.ToInt16(command.ExecuteScalar().ToString());

                            q            = "SELECT Branch_Name FROM bank where Bank_ID=" + comToBank.SelectedValue;
                            command      = new MySqlCommand(q, dbconnection);
                            ToBranchName = command.ExecuteScalar().ToString();
                        }

                        string       q2       = "UPDATE bank SET Bank_Stock = " + (FromBank_Stock - money) + " where Bank_ID=" + comFromBank.SelectedValue;
                        MySqlCommand command2 = new MySqlCommand(q2, dbconnection);
                        command2.ExecuteNonQuery();

                        q2       = "UPDATE bank SET Bank_Stock = " + (ToBank_Stock + money) + " where Bank_ID=" + comToBank.SelectedValue;
                        command2 = new MySqlCommand(q2, dbconnection);
                        command2.ExecuteNonQuery();

                        MySqlCommand com = dbconnection.CreateCommand();
                        com.CommandText = "INSERT INTO bank_Transfer (FromBranch_ID,FromBranch_Name,FromBank_ID,FromBank_Name,ToBranch_ID,ToBranch_Name,ToBank_ID,ToBank_Name,Money,Date,Description,Error) VALUES (@FromBranch_ID,@FromBranch_Name,@FromBank_ID,@FromBank_Name,@ToBranch_ID,@ToBranch_Name,@ToBank_ID,@ToBank_Name,@Money,@Date,@Description,@Error)";
                        if (radFromSafe.Checked)
                        {
                            com.Parameters.Add("@FromBranch_ID", MySqlDbType.Int16, 11).Value      = FromBranchId;
                            com.Parameters.Add("@FromBranch_Name", MySqlDbType.VarChar, 255).Value = FromBranchName;
                        }
                        else
                        {
                            com.Parameters.Add("@FromBranch_ID", MySqlDbType.Int16, 11).Value      = null;
                            com.Parameters.Add("@FromBranch_Name", MySqlDbType.VarChar, 255).Value = null;
                        }
                        com.Parameters.Add("@FromBank_ID", MySqlDbType.Int16, 11).Value      = comFromBank.SelectedValue;
                        com.Parameters.Add("@FromBank_Name", MySqlDbType.VarChar, 255).Value = comFromBank.Text;
                        if (radToSafe.Checked)
                        {
                            com.Parameters.Add("@ToBranch_ID", MySqlDbType.Int16, 11).Value      = ToBranchId;
                            com.Parameters.Add("@ToBranch_Name", MySqlDbType.VarChar, 255).Value = ToBranchName;
                        }
                        else
                        {
                            com.Parameters.Add("@ToBranch_ID", MySqlDbType.Int16, 11).Value      = null;
                            com.Parameters.Add("@ToBranch_Name", MySqlDbType.VarChar, 255).Value = null;
                        }
                        com.Parameters.Add("@ToBank_ID", MySqlDbType.Int16, 11).Value      = comToBank.SelectedValue;
                        com.Parameters.Add("@ToBank_Name", MySqlDbType.VarChar, 255).Value = comToBank.Text;
                        com.Parameters.Add("@Money", MySqlDbType.Decimal, 10).Value        = money;
                        com.Parameters.Add("@Date", MySqlDbType.DateTime, 0).Value         = DateTime.Now;
                        com.Parameters.Add("@Description", MySqlDbType.VarChar, 255).Value = txtDescription.Text;
                        com.Parameters.Add("@Error", MySqlDbType.Int16, 11).Value          = 0;
                        com.ExecuteNonQuery();

                        //////////record adding/////////////
                        query = "select BankTransfer_ID from bank_Transfer order by BankTransfer_ID desc limit 1";
                        com   = new MySqlCommand(query, dbconnection);
                        string bankTransferID = com.ExecuteScalar().ToString();

                        query = "insert into usercontrol (UserControl_UserID,UserControl_TableName,UserControl_Status,UserControl_RecordID,UserControl_Date,UserControl_Reason) values(@UserControl_UserID,@UserControl_TableName,@UserControl_Status,@UserControl_RecordID,@UserControl_Date,@UserControl_Reason)";
                        com   = new MySqlCommand(query, dbconnection);
                        com.Parameters.Add("@UserControl_UserID", MySqlDbType.Int16, 11).Value       = UserControl.userID;
                        com.Parameters.Add("@UserControl_TableName", MySqlDbType.VarChar, 255).Value = "bank_Transfer";
                        com.Parameters.Add("@UserControl_Status", MySqlDbType.VarChar, 255).Value    = "اضافة";
                        com.Parameters.Add("@UserControl_RecordID", MySqlDbType.VarChar, 255).Value  = bankTransferID;
                        com.Parameters.Add("@UserControl_Date", MySqlDbType.DateTime, 0).Value       = DateTime.Now;
                        com.Parameters.Add("@UserControl_Reason", MySqlDbType.VarChar, 255).Value    = null;
                        com.ExecuteNonQuery();
                        //////////////////////

                        query = "insert into transfer_categories_money (a200,a100,a50,a20,a10,a5,a1,aH,aQ,BankTransfer_ID) values(@a200,@a100,@a50,@a20,@a10,@a5,@a1,@aH,@aQ,@BankTransfer_ID)";
                        com   = new MySqlCommand(query, dbconnection);
                        com.Parameters.Add("@a200", MySqlDbType.Int16, 11).Value            = arrPaidMoneyPlus[0];
                        com.Parameters.Add("@a100", MySqlDbType.Int16, 11).Value            = arrPaidMoneyPlus[1];
                        com.Parameters.Add("@a50", MySqlDbType.Int16, 11).Value             = arrPaidMoneyPlus[2];
                        com.Parameters.Add("@a20", MySqlDbType.Int16, 11).Value             = arrPaidMoneyPlus[3];
                        com.Parameters.Add("@a10", MySqlDbType.Int16, 11).Value             = arrPaidMoneyPlus[4];
                        com.Parameters.Add("@a5", MySqlDbType.Int16, 11).Value              = arrPaidMoneyPlus[5];
                        com.Parameters.Add("@a1", MySqlDbType.Int16, 11).Value              = arrPaidMoneyPlus[6];
                        com.Parameters.Add("@aH", MySqlDbType.Int16, 11).Value              = arrPaidMoneyPlus[7];
                        com.Parameters.Add("@aQ", MySqlDbType.Int16, 11).Value              = arrPaidMoneyPlus[8];
                        com.Parameters.Add("@BankTransfer_ID", MySqlDbType.Int16, 11).Value = Convert.ToInt32(bankTransferID);
                        com.ExecuteNonQuery();

                        dbconnection.Close();
                        flagCategoriesSuccess = false;

                        clear();
                        t200.Text      = "";
                        t100.Text      = "";
                        t50.Text       = "";
                        t20.Text       = "";
                        t10.Text       = "";
                        t5.Text        = "";
                        t1.Text        = "";
                        tH.Text        = "";
                        tQ.Text        = "";
                        PaidMoney.Text = "0";

                        for (int i = 0; i < arrPaidMoneyPlus.Length; i++)
                        {
                            arrPaidMoneyPlus[i] = 0;
                        }
                        for (int i = 0; i < arrOFPhaatPlus.Length; i++)
                        {
                            arrOFPhaatPlus[i] = 0;
                        }
                        for (int i = 0; i < arrOFPhaatMinus.Length; i++)
                        {
                            arrOFPhaatMinus[i] = 0;
                        }
                        xtraTabPage.ImageOptions.Image = null;
                    }
                    else
                    {
                        MessageBox.Show("لا يمكنك التحويل الى نفس المصدر");
                    }
                }
                else
                {
                    MessageBox.Show("برجاء ادخال جميع البيانات المطلوبة");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            dbconnection.Close();
        }
    //Build list of files uploaded.
    private void buildTbl(MySqlConnection mySqlConnection)
    {
        if (tblUploads.Rows.Count > 1)
        {
            for (int i = tblUploads.Rows.Count - 1; i > 0; i--)
            {
                tblUploads.Rows.RemoveAt(i);
            }
        }
        MySqlCommand command = mySqlConnection.CreateCommand();
        int          staffID = Convert.ToInt32(Context.Request["StaffID"]);

        command.CommandText = @"SELECT Attachments.ID, FileName, AttchType, FileVersion, FileDate FROM Attachments LEFT JOIN TypeList ON Attachments.FileType = TypeList.ID WHERE AppID = " + Context.Request["AppID"];
        MySqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read()) //Build each row.
            {
                HtmlTableRow row = new HtmlTableRow();

                //Display filename as a hyperlink, so file can be opened.
                HtmlTableCell statusCell = HTMLFactory.buildCell("200", "left", "");
                HyperLink     hl         = new HyperLink();
                hl.Text        = reader["FileName"].ToString();
                hl.NavigateUrl = "http://curtinethics-001-site1.smarterasp.net/Uploads/" + Request["AppID"].ToString() + "_" + reader["FileName"].ToString();
                hl.Target      = "_blank";
                statusCell.Controls.Add(hl);

                //Delete button.
                Button btnDel = new Button(); //Need to use an ASP button to add the client side confirmation.
                btnDel.ID            = "Del" + reader["ID"].ToString();
                btnDel.Text          = "Delete";
                btnDel.OnClientClick = "return(beforeDelete( ))"; //Asks user if they are sure they want to delete.
                btnDel.Click        += btnDel_ServerClick;

                row.Cells.Add(statusCell);
                row.Cells.Add(HTMLFactory.buildCell("200", "left", reader["AttchType"].ToString()));
                row.Cells.Add(HTMLFactory.buildCell("97", "left", reader["FileVersion"].ToString()));
                row.Cells.Add(HTMLFactory.buildCell("97", "center", reader["FileDate"].ToString()));

                if (Context.Request["Mode"].Equals("W")) //If write then construct delete button.
                {
                    row.Cells.Add(HTMLFactory.buildCell("97", "center", btnDel));
                }
                else
                {
                    row.Cells.Add(HTMLFactory.buildCell("97", "center", "Read only"));
                }

                tblUploads.Rows.Add(row);
            }
        }
        else
        {
            if (tblUploads.Rows.Count != 0)
            {
                HtmlTableRow  blnkRow = new HtmlTableRow();
                HtmlTableCell blnk    = new HtmlTableCell();
                blnk.InnerText = "None";
                blnk.ColSpan   = 5;
                blnkRow.Cells.Add(blnk);
                tblUploads.Rows.Add(blnkRow);
            }
        }
        reader.Dispose();
    }
Exemplo n.º 15
0
        public Boolean saveGoodsEntryData(String TRDR_ID, String ITEM_NAME, String WT_BOX_TYPE, String WT_TXT, String LOT_1, String LOT_2, String LOT_3, String LOT_4, String LOT_5,
                                          String LOGISTIC_DETAILS, String SHORT_BOX, String QTY_RCVD, String ORIGIN, String VEHICLE_NO, String FARE_RATE, String TOTAL_FARE, String RECV_DATE, String TRDR_FNAME_TMARK, String LOT_NO_SHORT)
        {
            this.TRDR_ID          = TRDR_ID.Trim();
            this.ITEM_NAME        = ITEM_NAME.Trim();
            this.WT_BOX_TYPE      = WT_BOX_TYPE.Trim();
            this.WT_TXT           = WT_TXT.Trim();
            this.LOT_1            = LOT_1;
            this.LOT_2            = LOT_2;
            this.LOT_3            = LOT_3;
            this.LOT_4            = LOT_4;
            this.LOT_5            = LOT_5;
            this.LOGISTIC_DETAILS = LOGISTIC_DETAILS;
            this.VEHICLE_NO       = VEHICLE_NO;
            this.FARE_RATE        = FARE_RATE;
            this.TOTAL_FARE       = TOTAL_FARE;
            this.SHORT_BOX        = SHORT_BOX;
            this.ORIGIN           = ORIGIN;
            this.RECV_DATE        = RECV_DATE;
            this.QTY_RCVD         = QTY_RCVD;
            this.TRDR_FNAME_TMARK = TRDR_FNAME_TMARK;
            this.LOT_NO_SHORT     = LOT_NO_SHORT;

            //Entry of goods_entry details
            String G_ENTRY_ID = "GETRYID" + GenerateUniqueID.RandomString(8);

            try{
                con = dataBaseConnection.getMySqlDBConnection();
                con.Open();
                MySqlCommand myCommand = con.CreateCommand();

                // Start a local transaction
                myTrans = con.BeginTransaction();
                // Must assign both transaction object and connection
                // to Command object for a pending local transaction
                myCommand.Connection  = con;
                myCommand.Transaction = myTrans;

                insertQuery = "insert into " + tableName + " values('" + G_ENTRY_ID + "','" + TRDR_ID + "','" + ITEM_NAME + "','" + WT_TXT + "','" + LOT_1
                              + "','" + LOT_2 + "','" + LOT_3 + "','" + LOT_4 + "','" + LOT_5 + "','" + LOGISTIC_DETAILS + "','" + VEHICLE_NO + "','" + FARE_RATE + "','"
                              + TOTAL_FARE + "','" + QTY_RCVD + "','" + ORIGIN + "','" + RECV_DATE + "','" + SHORT_BOX + "','" + WT_BOX_TYPE + "','" + TRDR_FNAME_TMARK + "','" + LOT_NO_SHORT + "');";
                Console.WriteLine("Query:" + insertQuery);
                if (!(dataAccessUtility.iscolumnAlreadyPresent(tableName, "G_ENTRY_ID", G_ENTRY_ID)))
                {
                    insertData(insertQuery, con);
                    Console.WriteLine("Goods Entry Inserted");
                }
                else
                {
                    throw (new CustomException("Some Thing Wrong !! Please Try Again"));
                }
                //Entry of stock details for each Lot
                String    stockTable    = "stock_details";
                String    LOTID_1       = "LOT" + GenerateUniqueID.RandomString(8);
                String    LOTID_2       = "LOT" + GenerateUniqueID.RandomString(8);
                String    LOTID_3       = "LOT" + GenerateUniqueID.RandomString(8);
                String    LOTID_4       = "LOT" + GenerateUniqueID.RandomString(8);
                String    LOTID_5       = "LOT" + GenerateUniqueID.RandomString(8);
                String    STOCK_ID      = "STOCK" + GenerateUniqueID.RandomString(8);
                String[]  lotIds        = new String[] { LOTID_1, LOTID_2, LOTID_3, LOTID_4, LOTID_5 };
                String [] lotBoxes      = new String[] { this.LOT_1, this.LOT_2, this.LOT_3, this.LOT_4, this.LOT_5 };
                String    SHORT_LOT_IND = "N";
                if (!(String.IsNullOrEmpty(this.LOT_NO_SHORT)))
                {
                    SHORT_LOT_IND = "Y," + lotIds[int.Parse(this.LOT_NO_SHORT) - 1];
                }
                insertQuery = "insert into " + stockTable + " values('" + G_ENTRY_ID + "','" + LOTID_1 + "','" + LOTID_2 + "','" + LOTID_3 + "','" + LOTID_4
                              + "','" + LOTID_5 + "','" + STOCK_ID + "','" + SHORT_LOT_IND + "');";

                if (!(dataAccessUtility.iscolumnAlreadyPresent(stockTable, "STOCK_ID", STOCK_ID)))
                {
                    insertData(insertQuery, con);
                    Console.WriteLine("StockQuery:" + insertQuery);
                }
                else
                {
                    MessageBox.Show("Some Thing Wrong !! Please Try Again");
                    return(false);
                }

                //Entry of lots details into lot details
                String lotDetailsTable = "lot_status";
                if (SHORT_LOT_IND.Contains("Y"))
                {
                    int index    = int.Parse(this.LOT_NO_SHORT) - 1;
                    int shortbox = int.Parse(this.SHORT_BOX);
                    lotBoxes[index] = (int.Parse(lotBoxes[index]) - shortbox).ToString();
                }

                for (int i = 0; i < lotIds.Length; i++)
                {
                    int lotSerial = 0;
                    if (String.IsNullOrEmpty(lotBoxes[i]))
                    {
                        lotSerial = i + 1;
                        continue;
                    }

                    lotSerial   = i + 1;
                    insertQuery = "insert into " + lotDetailsTable + " values('" + lotIds[i] + "','" + lotBoxes[i] + "','" + G_ENTRY_ID + "','0','" + lotBoxes[i] + "','" + lotSerial + "','N');";
                    insertData(insertQuery, con);
                    Console.WriteLine("Lot_details_Query:" + insertQuery);
                }
                myTrans.Commit();
                Console.WriteLine("All records are written to database.");
                finalResult = true;
                return(finalResult);
            }
            catch (Exception e)
            {
                finalResult = false;
                try
                {
                    myTrans.Rollback();
                    return(finalResult);
                }
                catch (MySqlException ex)
                {
                    if (myTrans.Connection != null)
                    {
                        Console.WriteLine("An exception of type " + ex.GetType() +
                                          " was encountered while attempting to roll back the transaction.");
                    }
                }

                Console.WriteLine("An exception of type " + e.GetType() + " was encountered while inserting the data.");
                Console.WriteLine("Neither record was written to database.");
                return(finalResult);
            }
            finally
            {
                con.Close();
            }
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                throw new Exception("Require buildconfig and cdnconfig (and yes for fullrun)");
            }

            var fullrun = false;

            if (args.Length == 3 && args[2] == "1")
            {
                Console.WriteLine("Doing full run!");
                fullrun = true;
            }

            // TODO: Use configuration stuff instead, but I don't want to figure that out right now. :)
            if (!File.Exists("connectionstring.txt"))
            {
                throw new Exception("connectionstring.txt not found!");
            }

            var dbConn = new MySqlConnection(File.ReadAllText("connectionstring.txt"));

            dbConn.Open();

            CASC.InitCasc("bnet.marlam.in", args[0], args[1]);

            var insertCmd = new MySqlCommand("INSERT INTO wow_rootfiles_links VALUES (@parent, @child, @type)", dbConn);

            insertCmd.Parameters.AddWithValue("@parent", 0);
            insertCmd.Parameters.AddWithValue("@child", 0);
            insertCmd.Parameters.AddWithValue("@type", "");
            insertCmd.Prepare();

            /*
             #region M2
             * var m2ids = new List<uint>();
             *
             * using (var cmd = dbConn.CreateCommand())
             * {
             *  if (fullrun)
             *  {
             *      cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'm2' ORDER BY id DESC";
             *  }
             *  else
             *  {
             *      Console.WriteLine("[M2] Generating list of files to process..");
             *      cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'm2' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
             *  }
             *
             *  var reader = cmd.ExecuteReader();
             *
             *  while (reader.Read())
             *  {
             *      m2ids.Add(uint.Parse(reader["id"].ToString()));
             *  }
             *
             *  reader.Close();
             * }
             *
             * foreach (var m2 in m2ids)
             * {
             *  if (CASC.FileExists(m2))
             *  {
             *      Console.WriteLine("[M2] Loading " + m2);
             *      try
             *      {
             *          var reader = new M2Reader();
             *          reader.LoadM2(m2, false);
             *
             *          insertCmd.Parameters[0].Value = m2;
             *
             *          if (reader.model.textureFileDataIDs != null)
             *          {
             *              foreach (var textureID in reader.model.textureFileDataIDs)
             *              {
             *                  if (textureID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = textureID;
             *                  insertCmd.Parameters[2].Value = "m2 texture";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (reader.model.animFileDataIDs != null)
             *          {
             *              foreach (var animFileID in reader.model.animFileDataIDs)
             *              {
             *                  if (animFileID.fileDataID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = animFileID.fileDataID;
             *                  insertCmd.Parameters[2].Value = "m2 anim";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (reader.model.skinFileDataIDs != null)
             *          {
             *              foreach (var skinFileID in reader.model.skinFileDataIDs)
             *              {
             *                  if (skinFileID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = skinFileID;
             *                  insertCmd.Parameters[2].Value = "m2 skin";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (reader.model.boneFileDataIDs != null)
             *          {
             *              foreach (var boneFileID in reader.model.boneFileDataIDs)
             *              {
             *                  if (boneFileID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = boneFileID;
             *                  insertCmd.Parameters[2].Value = "m2 bone";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (reader.model.recursiveParticleModelFileIDs != null)
             *          {
             *              foreach (var rpID in reader.model.recursiveParticleModelFileIDs)
             *              {
             *                  if (rpID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = rpID;
             *                  insertCmd.Parameters[2].Value = "m2 recursive particle";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (reader.model.geometryParticleModelFileIDs != null)
             *          {
             *              foreach (var gpID in reader.model.geometryParticleModelFileIDs)
             *              {
             *                  if (gpID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = gpID;
             *                  insertCmd.Parameters[2].Value = "m2 geometry particle";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (reader.model.skelFileID != 0)
             *          {
             *              insertCmd.Parameters[1].Value = reader.model.skelFileID;
             *              insertCmd.Parameters[2].Value = "m2 skel";
             *              insertCmd.ExecuteNonQuery();
             *          }
             *
             *          if (reader.model.physFileID != 0)
             *          {
             *              insertCmd.Parameters[1].Value = reader.model.physFileID;
             *              insertCmd.Parameters[2].Value = "m2 phys";
             *              insertCmd.ExecuteNonQuery();
             *          }
             *      }
             *      catch (Exception e)
             *      {
             *          Console.WriteLine(e.Message);
             *      }
             *  }
             * }
             #endregion
             *
             #region WMO
             *
             * var wmoids = new List<uint>();
             *
             * var groupFixCMD = new MySqlCommand("UPDATE wow_rootfiles SET type = '_xxxwmo' WHERE id = @id LIMIT 1", dbConn);
             * groupFixCMD.Parameters.AddWithValue("@id", 0);
             * groupFixCMD.Prepare();
             *
             * using (var cmd = dbConn.CreateCommand())
             * {
             *  if (fullrun)
             *  {
             *      cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'wmo' ORDER BY id DESC";
             *  }
             *  else
             *  {
             *      Console.WriteLine("[WMO] Generating list of files to process..");
             *      cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'wmo' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
             *  }
             *  var reader = cmd.ExecuteReader();
             *
             *  while (reader.Read())
             *  {
             *      wmoids.Add(uint.Parse(reader["id"].ToString()));
             *  }
             *
             *  reader.Close();
             * }
             *
             * foreach (var wmoid in wmoids)
             * {
             *  if (CASC.FileExists(wmoid))
             *  {
             *      Console.WriteLine("[WMO] Loading " + wmoid);
             *      try
             *      {
             *          var reader = new WMOReader();
             *          var wmo = new WoWFormatLib.Structs.WMO.WMO();
             *          try
             *          {
             *              wmo = reader.LoadWMO(wmoid);
             *          }
             *          catch (NotSupportedException e)
             *          {
             *              Console.WriteLine("[WMO] " + wmoid + " is a group WMO, fixing type and skipping..");
             *              groupFixCMD.Parameters[0].Value = wmoid;
             *              groupFixCMD.ExecuteNonQuery();
             *              continue;
             *          }
             *
             *          insertCmd.Parameters[0].Value = wmoid;
             *
             *          var inserted = new List<uint>();
             *
             *          if (wmo.groupFileDataIDs != null)
             *          {
             *              foreach (var groupFileDataID in wmo.groupFileDataIDs)
             *              {
             *                  if (groupFileDataID == 0)
             *                      continue;
             *
             *                  insertCmd.Parameters[1].Value = groupFileDataID;
             *                  insertCmd.Parameters[2].Value = "wmo group";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (wmo.doodadIds != null)
             *          {
             *              foreach (var doodadID in wmo.doodadIds)
             *              {
             *                  if (doodadID == 0 || inserted.Contains(doodadID))
             *                      continue;
             *
             *                  inserted.Add(doodadID);
             *                  insertCmd.Parameters[1].Value = doodadID;
             *                  insertCmd.Parameters[2].Value = "wmo doodad";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *
             *          if (wmo.textures == null && wmo.materials != null)
             *          {
             *              foreach (var material in wmo.materials)
             *              {
             *                  if (material.texture1 == 0 || inserted.Contains(material.texture1))
             *                      continue;
             *
             *                  inserted.Add(material.texture1);
             *                  insertCmd.Parameters[1].Value = material.texture1;
             *                  insertCmd.Parameters[2].Value = "wmo texture";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *          }
             *      }
             *      catch (Exception e)
             *      {
             *          Console.WriteLine(e.Message);
             *      }
             *  }
             * }
             #endregion
             *
             #region WDT
             * var wdtids = new List<uint>();
             * using (var cmd = dbConn.CreateCommand())
             * {
             *  if (fullrun)
             *  {
             *      cmd.CommandText = "SELECT id, filename from wow_rootfiles WHERE type = 'wdt' ORDER BY id DESC";
             *  }
             *  else
             *  {
             *      Console.WriteLine("[WDT] Generating list of files to process..");
             *      cmd.CommandText = "SELECT id, filename from wow_rootfiles WHERE type = 'wdt' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
             *  }
             *  var reader = cmd.ExecuteReader();
             *
             *  while (reader.Read())
             *  {
             *      var filename = (string)reader["filename"];
             *      if (filename.Contains("_mpv") || filename.Contains("_lgt") || filename.Contains("_occ") || filename.Contains("_fogs"))
             *          continue;
             *      wdtids.Add(uint.Parse(reader["id"].ToString()));
             *  }
             *
             *  reader.Close();
             *
             *  foreach (var wdtid in wdtids)
             *  {
             *      Console.WriteLine("[WDT] Loading " + wdtid);
             *
             *      insertCmd.Parameters[0].Value = wdtid;
             *
             *      var wdtreader = new WDTReader();
             *      wdtreader.LoadWDT(wdtid);
             *
             *      foreach(var records in wdtreader.tileFiles)
             *      {
             *          if(records.Value.rootADT != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.rootADT;
             *                  insertCmd.Parameters[2].Value = "root adt";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("Root: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.tex0ADT != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.tex0ADT;
             *                  insertCmd.Parameters[2].Value = "tex0 adt";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("TEX0: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.lodADT != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.lodADT;
             *                  insertCmd.Parameters[2].Value = "lod adt";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("LOD: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.obj0ADT != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.obj0ADT;
             *                  insertCmd.Parameters[2].Value = "obj0 adt";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("OBJ0: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.obj1ADT != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.obj1ADT;
             *                  insertCmd.Parameters[2].Value = "obj1 adt";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("OBJ1: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.mapTexture != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.mapTexture;
             *                  insertCmd.Parameters[2].Value = "map texture";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("MapT: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.mapTextureN != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.mapTextureN;
             *                  insertCmd.Parameters[2].Value = "mapn texture";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("MapTN: " + e.Message);
             *              }
             *          }
             *
             *          if(records.Value.minimapTexture != 0)
             *          {
             *              try
             *              {
             *                  insertCmd.Parameters[1].Value = records.Value.minimapTexture;
             *                  insertCmd.Parameters[2].Value = "minimap texture";
             *                  insertCmd.ExecuteNonQuery();
             *              }
             *              catch (Exception e)
             *              {
             *                  Console.WriteLine("Minimap: " + e.Message);
             *              }
             *          }
             *      }
             *  }
             * }
             #endregion
             */

            #region ADT
            var adtids     = new Dictionary <uint, Dictionary <(byte, byte), uint> >();
            var wdtmapping = new Dictionary <string, uint>();

            using (var cmd = dbConn.CreateCommand())
            {
                if (fullrun)
                {
                    cmd.CommandText = " SELECT id, filename from wow_rootfiles WHERE filename LIKE '%adt' AND filename NOT LIKE '%_obj0.adt' AND filename NOT LIKE '%_obj1.adt' AND filename NOT LIKE '%_lod.adt' AND filename NOT LIKE '%tex0.adt' AND filename NOT LIKE '%tex1.adt' ORDER BY id DESC ";
                }
                else
                {
                    Console.WriteLine("[ADT] Generating list of files to process..");
                    cmd.CommandText = " SELECT id, filename from wow_rootfiles WHERE filename LIKE '%adt' AND filename NOT LIKE '%_obj0.adt' AND filename NOT LIKE '%_obj1.adt' AND filename NOT LIKE '%_lod.adt' AND filename NOT LIKE '%tex0.adt' AND filename NOT LIKE '%tex1.adt' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
                }
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    var filename = (string)reader["filename"];
                    var mapname  = filename.Replace("world/maps/", "").Substring(0, filename.Replace("world/maps/", "").IndexOf("/"));
                    var exploded = Path.GetFileNameWithoutExtension(filename).Split('_');

                    for (var i = 0; i < exploded.Length; i++)
                    {
                        //Console.WriteLine(i + ": " + exploded[i]);
                    }

                    byte tileX = 0;
                    byte tileY = 0;

                    if (!byte.TryParse(exploded[exploded.Length - 2], out tileX) || !byte.TryParse(exploded[exploded.Length - 1], out tileY))
                    {
                        throw new FormatException("An error occured converting coordinates from " + filename + " to bytes");
                    }

                    if (!wdtmapping.ContainsKey(mapname))
                    {
                        var wdtname = "world/maps/" + mapname + "/" + mapname + ".wdt";
                        wdtmapping.Add(mapname, CASC.getFileDataIdByName(wdtname));
                        if (wdtmapping[mapname] == 0)
                        {
                            // TODO: Support WDTs removed in current build
                            Console.WriteLine("Unable to get filedataid for " + mapname + ", skipping...");
                            wdtmapping.Remove(mapname);
                            continue;

                            /*
                             * var wdtconn = new MySqlConnection(File.ReadAllText("connectionstring.txt"));
                             * wdtconn.Open();
                             * using (var wdtcmd = wdtconn.CreateCommand())
                             * {
                             *  wdtcmd.CommandText = "SELECT id from wow_rootfiles WHERE filename = '" + wdtname + "'";
                             *  var wdtread = wdtcmd.ExecuteReader();
                             *  while (wdtread.Read())
                             *  {
                             *      wdtmapping[mapname] = uint.Parse(wdtread["id"].ToString());
                             *  }
                             * }
                             * wdtconn.Close();*/
                        }

                        adtids.Add(wdtmapping[mapname], new Dictionary <(byte, byte), uint>());
                    }

                    var id = uint.Parse(reader["id"].ToString());

                    if (id == 0)
                    {
                        Console.WriteLine("Root ADT " + tileX + ", " + tileY + " with ID 0 on WDT " + wdtmapping[mapname]);
                        continue;
                    }

                    if (wdtmapping.ContainsKey(mapname))
                    {
                        adtids[wdtmapping[mapname]].Add((tileX, tileY), id);
                    }
                }

                reader.Close();

                foreach (var wdtid in adtids)
                {
                    foreach (var adtid in wdtid.Value)
                    {
                        var inserted = new List <uint>();
                        Console.WriteLine("[ADT] Loading " + adtid.Key.Item1 + ", " + adtid.Key.Item2 + "(" + adtid.Value + ")");

                        insertCmd.Parameters[0].Value = adtid.Value;

                        var adtreader = new ADTReader();
                        adtreader.LoadADT(wdtid.Key, adtid.Key.Item1, adtid.Key.Item2);

                        if (adtreader.adtfile.objects.m2Names.filenames != null)
                        {
                            Console.WriteLine(adtid + " is still using old filenames, skipping!");
                        }
                        else
                        {
                            foreach (var worldmodel in adtreader.adtfile.objects.worldModels.entries)
                            {
                                if (inserted.Contains(worldmodel.mwidEntry))
                                {
                                    continue;
                                }

                                insertCmd.Parameters[1].Value = worldmodel.mwidEntry;
                                insertCmd.Parameters[2].Value = "adt worldmodel";
                                insertCmd.ExecuteNonQuery();
                                inserted.Add(worldmodel.mwidEntry);
                            }

                            foreach (var doodad in adtreader.adtfile.objects.models.entries)
                            {
                                if (inserted.Contains(doodad.mmidEntry))
                                {
                                    continue;
                                }

                                insertCmd.Parameters[1].Value = doodad.mmidEntry;
                                insertCmd.Parameters[2].Value = "adt doodad";
                                insertCmd.ExecuteNonQuery();
                                inserted.Add(doodad.mmidEntry);
                            }
                        }
                    }
                }
            }
            #endregion
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((1 == 1))
            {
                string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + ";";
                Regex  r           = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
                tainted_3 = r.Replace(tainted_2, "");
            }
            else if (!(1 == 1))
            {
                {}
            }
            else
            {
                {}
            }

            string query        = "SELECT * FROM Articles WHERE id=@placeholder";
            string checked_data = tainted_3;


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd = new MySqlCommand(query);
                cmd.Parameters.AddWithValue("@placeholder", checked_data);
                cmd.Prepare();
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
        private void btnImprimir_Click(object sender, EventArgs e)
        {
            //Conexion a la base de datos
            MySqlConnection myConexion = new MySqlConnection(clsConexion.ConectionString);
            // Creando el command que ejecutare
            MySqlCommand myCommand = new MySqlCommand();
            // Creando el Data Adapter
            MySqlDataAdapter myAdapter = new MySqlDataAdapter();
            // Creando el String Builder
            StringBuilder sbQuery = new StringBuilder();
            // Otras variables del entorno
            string cWhere   = " WHERE 1 = 1";
            string cUsuario = "";
            string cTitulo  = "";

            try
            {
                // Abro conexion
                myConexion.Open();

                // Creo comando
                myCommand = myConexion.CreateCommand();

                // Adhiero el comando a la conexion
                myCommand.Connection = myConexion;

                // Filtros de la busqueda
                string fechadesde = dtDesde.Value.ToString("yyyy-MM-dd");
                string fechahasta = dtHasta.Value.ToString("yyyy-MM-dd");
                cWhere = cWhere + " AND fecha >= " + "'" + fechadesde + "'" + " AND fecha <= " + "'" + fechahasta + "'" + "";
                if (chkUnidadNaval.Checked == true)
                {
                    cWhere = cWhere + " AND unidadesnavales.id = " + cmbUnidadNaval.SelectedValue + "";
                }
                sbQuery.Clear();
                sbQuery.Append("SELECT movimientocombustible.fecha, movimientocombustible.descripcion_combustible,");
                sbQuery.Append(" movimientocombustible.cantidad, movimientocombustible.id, movimientocombustible.fecha,");
                sbQuery.Append(" unidadesnavales.unidad as embarcacion");
                sbQuery.Append(" FROM movimientocombustible");
                sbQuery.Append(" INNER JOIN unidadesnavales ON unidadesnavales.id = movimientocombustible.embarcacion");
                sbQuery.Append(cWhere);
                sbQuery.Append(" AND tipo_movimiento = 'S' AND anulada = 0");
                //sbQuery.Append(" ORDER BY rangos.orden ASC");

                // Paso los valores de sbQuery al CommandText
                myCommand.CommandText = sbQuery.ToString();
                // Creo el objeto Data Adapter y ejecuto el command en el
                myAdapter = new MySqlDataAdapter(myCommand);
                // Creo el objeto Data Table
                DataTable dtMovimientoCombustible = new DataTable();
                // Lleno el data adapter
                myAdapter.Fill(dtMovimientoCombustible);
                // Cierro el objeto conexion
                myConexion.Close();

                // Verifico cantidad de datos encontrados
                int nRegistro = dtMovimientoCombustible.Rows.Count;
                if (nRegistro == 0)
                {
                    MessageBox.Show("No Hay Datos Para Mostrar, Favor Verificar", "Sistema de Gestion de Combustible", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    //1ero.HACEMOS LA COLECCION DE PARAMETROS
                    //los campos de parametros contiene un objeto para cada campo de parametro en el informe
                    ParameterFields oParametrosCR = new ParameterFields();
                    //Proporciona propiedades para la recuperacion y configuracion del tipo de los parametros
                    ParameterValues oParametrosValuesCR = new ParameterValues();

                    //2do.CREAMOS LOS PARAMETROS
                    ParameterField oUsuario      = new ParameterField();
                    ParameterField oFechaInicial = new ParameterField();
                    ParameterField oFechaFinal   = new ParameterField();
                    //parametervaluetype especifica el TIPO de valor de parametro
                    //ParameterValueKind especifica el tipo de valor de parametro en la PARAMETERVALUETYPE de la Clase PARAMETERFIELD
                    oUsuario.ParameterValueType      = ParameterValueKind.StringParameter;
                    oFechaInicial.ParameterValueType = ParameterValueKind.DateTimeParameter;
                    oFechaFinal.ParameterValueType   = ParameterValueKind.DateTimeParameter;

                    //3ero.VALORES PARA LOS PARAMETROS
                    //ParameterDiscreteValue proporciona propiedades para la recuperacion y configuracion de
                    //parametros de valores discretos
                    ParameterDiscreteValue oUsuarioDValue = new ParameterDiscreteValue();
                    oUsuarioDValue.Value = cUsuario;
                    ParameterDiscreteValue oFechaDValue = new ParameterDiscreteValue();
                    oFechaDValue.Value = fechadesde;
                    ParameterDiscreteValue oFechaFinDValue = new ParameterDiscreteValue();
                    oFechaFinDValue.Value = fechahasta;

                    //4to. AGREGAMOS LOS VALORES A LOS PARAMETROS
                    oUsuario.CurrentValues.Add(oUsuarioDValue);
                    oFechaInicial.CurrentValues.Add(oFechaDValue);
                    oFechaFinal.CurrentValues.Add(oFechaFinDValue);

                    //5to. AGREGAMOS LOS PARAMETROS A LA COLECCION
                    oParametrosCR.Add(oUsuario);
                    oParametrosCR.Add(oFechaInicial);
                    oParametrosCR.Add(oFechaFinal);
                    //nombre del parametro en CR (Crystal Reports)
                    oParametrosCR[0].Name = "cUsuario";
                    oParametrosCR[1].Name = "cFechaInicial";
                    oParametrosCR[2].Name = "cFechaFinal";

                    //nombre del TITULO DEL INFORME
                    cTitulo = "Listado de Despacho de Combustible a Unidades Navales";

                    //6to Instanciamos nuestro REPORTE
                    //Reportes.ListadoDoctores oListado = new Reportes.ListadoDoctores();
                    rptDespachoCombustibleUnidadesNavales orptDespachoCombustibleUnidadesNavales = new rptDespachoCombustibleUnidadesNavales();

                    //pasamos el nombre del TITULO del Listado
                    //SumaryInfo es un objeto que se utiliza para leer,crear y actualizar las propiedades del reporte
                    // oListado.SummaryInfo.ReportTitle = cTitulo;
                    orptDespachoCombustibleUnidadesNavales.SummaryInfo.ReportTitle = cTitulo;

                    //7mo. instanciamos nuestro el FORMULARIO donde esta nuestro ReportViewer
                    frmPrinter ofrmPrinter = new frmPrinter(dtMovimientoCombustible, orptDespachoCombustibleUnidadesNavales, cTitulo);

                    //ParameterFieldInfo Obtiene o establece la colección de campos de parámetros.
                    ofrmPrinter.CrystalReportViewer1.ParameterFieldInfo = oParametrosCR;
                    ofrmPrinter.ShowDialog();
                }
            }
            catch (Exception myEx)
            {
                MessageBox.Show("Error : " + myEx.Message, "Mostrando Reporte", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                //ExceptionLog.LogError(myEx, false);
                return;
            }
        }
Exemplo n.º 19
0
        public Client Register(RegisterModel model)
        {
            Client client = null;
            int    newId;

            using (MySqlConnection conn = GetConnection())
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("select email from clients", conn);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader["email"].ToString() == model.Email)
                        {
                            return(null);
                        }
                    }
                }
                using (var transaction = conn.BeginTransaction())
                {
                    var insertCommand = conn.CreateCommand();
                    insertCommand.CommandText = "call register_client(@lastname, @firstname, @patronymic," +
                                                "@country, @city, @email, @password, @phone_number);";
                    insertCommand.Parameters.AddWithValue("@email", model.Email);
                    insertCommand.Parameters.AddWithValue("@password", model.Password);
                    insertCommand.Parameters.AddWithValue("@lastname", model.Surname);
                    insertCommand.Parameters.AddWithValue("@firstname", model.Name);
                    insertCommand.Parameters.AddWithValue("@patronymic", model.Patronymic);
                    insertCommand.Parameters.AddWithValue("@country", model.Country);
                    insertCommand.Parameters.AddWithValue("@city", model.City);
                    insertCommand.Parameters.AddWithValue("@phone_number", model.PhoneNumber);
                    insertCommand.CommandText += "select LAST_INSERT_ID();";
                    newId = Convert.ToInt32(insertCommand.ExecuteScalar());
                    transaction.Commit();
                }
                MySqlCommand command = new MySqlCommand("select * from clients where id = (@newId);", conn);
                command.Parameters.AddWithValue("@newId", newId.ToString());
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        client = new Client()
                        {
                            Id           = Convert.ToInt32(reader["id"]),
                            FirstNameId  = Convert.ToInt32(reader["id_name2"]),
                            LastNameId   = Convert.ToInt32(reader["id_name1"]),
                            PatronymicId = Convert.ToInt32(reader["id_name3"] != DBNull.Value ? reader["id_name3"] : null),
                            PhoneNumber  = reader["phonenumber"].ToString(),
                            AddressId    = Convert.ToInt32(reader["id_address"] != DBNull.Value ? reader["id_address"] : null),
                            PassportId   = Convert.ToInt32(reader["id_passport"] != DBNull.Value ? reader["id_passport"] : null),
                            Email        = reader["email"].ToString(),
                            Role         = reader["role"].ToString(),
                            Money        = Convert.ToInt32(reader["id_address"] != DBNull.Value ? reader["id_address"] : 0),
                            BlockingId   = null
                        };
                    }
                }
            }
            return(client);
        }
Exemplo n.º 20
0
        private void btnGrabar_Click(object sender, EventArgs e)
        {
            if (txtCodigo.Text == "")
            {
                MessageBox.Show("No se puede grabar un registro sin codigo...");
                txtCodigo.Focus();
            }
            else if (txtDepartamento.Text == "")
            {
                MessageBox.Show("No se puede grabar un registro sin descripcion...");
            }
            else
            {
                // Si estoy agregando un registro nuevo
                if (cModo == "Nuevo")
                {
                    try
                    {
                        // Step 1 - Stablishing the connection
                        MySqlConnection MyConexion = new MySqlConnection(clsConexion.ConectionString);

                        // Step 2 - Crear el comando de ejecucion
                        MySqlCommand myCommand = MyConexion.CreateCommand();

                        // Step 3 - Comando a ejecutar
                        myCommand.CommandText = "INSERT INTO estaciones(estacion) values(@estacion)";
                        myCommand.Parameters.AddWithValue("@estacion", txtDepartamento.Text);

                        // Step 4 - Opening the connection
                        MyConexion.Open();

                        // Step 5 - Executing the query
                        myCommand.ExecuteNonQuery();

                        // Step 6 - Closing the connection
                        MyConexion.Close();

                        MessageBox.Show("Informacion guardada satisfactoriamente...");
                    }
                    catch (Exception myEx)
                    {
                        MessageBox.Show(myEx.Message);
                        throw;
                    }
                }
                // Si estoy editando y modificando un registro
                else
                {
                    try
                    {
                        // Step 1 - Stablishing the connection
                        MySqlConnection MyConexion = new MySqlConnection(clsConexion.ConectionString);

                        // Step 2 - Crear el comando de ejecucion
                        MySqlCommand myCommand = MyConexion.CreateCommand();

                        // Step 3 - Comando a ejecutar
                        myCommand.CommandText = "UPDATE estaciones SET estacion = @estacion WHERE id = " + txtCodigo.Text + "";
                        myCommand.Parameters.AddWithValue("@estacion", txtDepartamento.Text);

                        // Step 4 - Opening the connection
                        MyConexion.Open();

                        // Step 5 - Executing the query
                        myCommand.ExecuteNonQuery();

                        // Step 6 - Closing the connection
                        MyConexion.Close();

                        MessageBox.Show("Informacion actualizada satisfactoriamente...");
                    }
                    catch (Exception myEx)
                    {
                        MessageBox.Show(myEx.Message);
                        throw;
                    }
                }
            }

            // Limpio los cambpos
            this.Limpiar();
            // Cambio la variable de la funcion botones
            this.cModo = "Inicio";
            // Llamo la funcion botones
            this.Botones();
        }
Exemplo n.º 21
0
        public void Init(MySqlConnection connection, SlotType slot)
        {
            using (var command = connection.CreateCommand())
            {
                switch (slot)
                {
                case SlotType.Inventory:
                case SlotType.Equipments:
                    command.CommandText = "SELECT * FROM items WHERE acc_id=@acc_id AND char_id=@char_id";
                    command.Parameters.AddWithValue("@acc_id", _character.Account.DbId);
                    command.Parameters.AddWithValue("@char_id", _character.DbId);
                    break;

                case SlotType.Bank:
                    command.CommandText = "SELECT * FROM items WHERE acc_id=@acc_id AND char_id=0";
                    command.Parameters.AddWithValue("@acc_id", _character.Account.DbId);
                    break;

                case SlotType.PranInventory:
                case SlotType.PranEquipments:
                    command.CommandText = "SELECT * FROM items WHERE acc_id=@acc_id AND pran_id=@pran_id";
                    command.Parameters.AddWithValue("@acc_id", _character.Account.DbId);
                    command.Parameters.AddWithValue("@pran_id", _character.ActivePran.DbId);
                    break;
                }

                command.Prepare();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var item = new Item.Item(reader.GetUInt16("item_id"))
                        {
                            DbId         = reader.GetUInt32("id"),
                            AccId        = reader.GetUInt32("acc_id"),
                            CharId       = reader.GetUInt32("char_id"),
                            PranId       = reader.GetUInt32("pran_id"),
                            SlotType     = (SlotType)reader.GetByte("slot_type"),
                            Slot         = reader.GetUInt16("slot"),
                            Effect1      = reader.GetByte("effect1"),
                            Effect2      = reader.GetByte("effect2"),
                            Effect3      = reader.GetByte("effect3"),
                            Effect1Value = reader.GetByte("effect1value"),
                            Effect2Value = reader.GetByte("effect2value"),
                            Effect3Value = reader.GetByte("effect3value"),
                            Durability   = reader.GetByte("dur"),
                            DurMax       = reader.GetByte("dur_max"),
                            Quantity     = reader.GetByte("quantity"),
                            ItemTime     = reader.GetUInt16("time")
                        };

                        // Check if item exists json data
                        if (item.ItemData == null)
                        {
                            continue;
                        }

                        // Check if in-range of the array
                        if (item.SlotType == SlotType.Equipments && item.Slot < 16 ||
                            item.SlotType == SlotType.Inventory && item.Slot < 84 ||
                            item.SlotType == SlotType.Bank && item.Slot < 86 ||
                            item.SlotType == SlotType.PranInventory && item.Slot < 42 ||
                            item.SlotType == SlotType.PranEquipments && item.Slot < 16)
                        {
                            _items[item.SlotType][item.Slot] = item;
                        }
                    }
                }
            }
        }
Exemplo n.º 22
0
        private void btnImprimir_Click(object sender, EventArgs e)
        {
            //clsConexion a la base de datos
            MySqlConnection myclsConexion = new MySqlConnection(clsConexion.ConectionString);
            // Creando el command que ejecutare
            MySqlCommand myCommand = new MySqlCommand();
            // Creando el Data Adapter
            MySqlDataAdapter myAdapter = new MySqlDataAdapter();
            // Creando el String Builder
            StringBuilder sbQuery = new StringBuilder();
            // Otras variables del entorno
            string cWhere   = " WHERE 1 = 1";
            string cUsuario = frmLogin.cUsuarioActual;
            string cTitulo  = "";

            try
            {
                // Abro clsConexion
                myclsConexion.Open();
                // Creo comando
                myCommand = myclsConexion.CreateCommand();
                // Adhiero el comando a la clsConexion
                myCommand.Connection = myclsConexion;
                // Filtros de la busqueda
                // CREANDO EL QUERY DE CONSULTA
                //string fechadesde = fechaDesde.Value.ToString("yyyy-MM-dd");
                //string fechahasta = fechaHasta.Value.ToString("yyyy-MM-dd");
                //cWhere = cWhere + " AND fechacita >= "+"'"+ fechadesde +"'" +" AND fechacita <= "+"'"+ fechahasta +"'"+"";
                //cWhere = cWhere + " AND year = '" + txtYear.Text + "'";
                sbQuery.Clear();
                sbQuery.Append("SELECT estaciones.id, estaciones.estacion as estaciones ");
                //sbQuery.Append(" tipo_deptogas.tipo as tipodescripcion, tipo_deptogas.id, deptobeneficiariogas.tarjeta");
                sbQuery.Append(" FROM estaciones ");
                //sbQuery.Append(" INNER JOIN tipo_deptogas ON tipo_deptogas.id = deptobeneficiariogas.tipo");
                sbQuery.Append(cWhere);
                sbQuery.Append(" ORDER BY estaciones.estacion ASC");

                // Paso los valores de sbQuery al CommandText
                myCommand.CommandText = sbQuery.ToString();

                // Creo el objeto Data Adapter y ejecuto el command en el
                myAdapter = new MySqlDataAdapter(myCommand);

                // Creo el objeto Data Table
                DataTable dtEstaciones = new DataTable();

                // Lleno el data adapter
                myAdapter.Fill(dtEstaciones);

                // Cierro el objeto clsConexion
                myclsConexion.Close();

                // Verifico cantidad de datos encontrados
                int nRegistro = dtEstaciones.Rows.Count;
                if (nRegistro == 0)
                {
                    MessageBox.Show("No Hay Datos Para Mostrar, Favor Verificar", "Sistema de Gestion de Combustibles", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    //1ero.HACEMOS LA COLECCION DE PARAMETROS
                    //los campos de parametros contiene un objeto para cada campo de parametro en el informe
                    ParameterFields oParametrosCR = new ParameterFields();
                    //Proporciona propiedades para la recuperacion y configuracion del tipo de los parametros
                    ParameterValues oParametrosValuesCR = new ParameterValues();

                    //2do.CREAMOS LOS PARAMETROS
                    ParameterField oUsuario = new ParameterField();
                    //parametervaluetype especifica el TIPO de valor de parametro
                    //ParameterValueKind especifica el tipo de valor de parametro en la PARAMETERVALUETYPE de la Clase PARAMETERFIELD
                    oUsuario.ParameterValueType = ParameterValueKind.StringParameter;

                    //3ero.VALORES PARA LOS PARAMETROS
                    //ParameterDiscreteValue proporciona propiedades para la recuperacion y configuracion de
                    //parametros de valores discretos
                    ParameterDiscreteValue oUsuarioDValue = new ParameterDiscreteValue();
                    oUsuarioDValue.Value = cUsuario;

                    //4to. AGREGAMOS LOS VALORES A LOS PARAMETROS
                    oUsuario.CurrentValues.Add(oUsuarioDValue);

                    //5to. AGREGAMOS LOS PARAMETROS A LA COLECCION
                    oParametrosCR.Add(oUsuario);
                    //nombre del parametro en CR (Crystal Reports)
                    oParametrosCR[0].Name = "cUsuario";
                    //nombre del TITULO DEL INFORME
                    cTitulo = "LISTADO DE ESTACIONES DE COMBUSTIBLE";

                    //6to Instanciamos nuestro REPORTE
                    //Reportes.ListadoDoctores oListado = new Reportes.ListadoDoctores();
                    //REPORTES.rptClientes orptClientes = new REPORTES.rptClientes();
                    rptEstaciones orptEstaciones = new rptEstaciones();

                    //pasamos el nombre del TITULO del Listado
                    //SumaryInfo es un objeto que se utiliza para leer,crear y actualizar las propiedades del reporte
                    // oListado.SummaryInfo.ReportTitle = cTitulo;
                    orptEstaciones.SummaryInfo.ReportTitle = cTitulo;

                    //7mo. instanciamos nuestro el FORMULARIO donde esta nuestro ReportViewer
                    frmPrinter ofrmPrinter = new frmPrinter(dtEstaciones, orptEstaciones, cTitulo);
                    //ParameterFieldInfo Obtiene o establece la colección de campos de parámetros.
                    ofrmPrinter.CrystalReportViewer1.ParameterFieldInfo = oParametrosCR;
                    ofrmPrinter.ShowDialog();
                }
            }
            catch (Exception myEx)
            {
                MessageBox.Show("Error : " + myEx.Message, "Mostrando Reporte", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                // clsExceptionLog.LogError(myEx, false);
                return;
            }
        }
Exemplo n.º 23
0
        private void bt_Add_Click(object sender, EventArgs e)
        {
            if (tb_Email.Text == "" || tb_firstName.Text == "" || tb_Job.Text == "" || tb_lastName.Text == "" || tb_UserName.Text == "" || tb_Password.Text == "" || tb_ConfirmPassword.Text == "")
            {
                MessageBox.Show("Please fill in all fields.");
                return;
            }

            if (tb_Password.Text != tb_ConfirmPassword.Text)
            {
                MessageBox.Show("Password and confirm password field are different!");
                return;
            }

            try
            {
                //Refresh data
                conn.Open();
                MySqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = $"INSERT INTO `employee` (`EventID`, `FirstName`, `LastName`, `User_name`, `Password`, `Email`, `Job`) " +
                                  $"VALUES ('1', '{tb_firstName.Text}', '{tb_lastName.Text}', '{tb_UserName.Text}', '{md5(tb_Password.Text)}', '{tb_Email.Text}', '{tb_Job.Text}');";

                int rowCount = cmd.ExecuteNonQuery();

                if (rowCount < 1)
                {
                    throw new Exception("Failed");
                }

                else
                {
                    data_Employee.ClearSelection();
                    tb_UserName.Text        = "";
                    tb_Password.Text        = "";
                    tb_lastName.Text        = "";
                    tb_Job.Text             = "";
                    tb_firstName.Text       = "";
                    tb_Email.Text           = "";
                    tb_ConfirmPassword.Text = "";
                    id = 0;
                    this.bt_Edit.Enabled = false;
                    bt_Add.Enabled       = true;
                    UpdateControlForm();
                }
            }
            catch (MySqlException sqlEx)
            {
                MessageBox.Show(sqlEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Exemplo n.º 24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            app.UseAuthentication();
            app.UseWebSockets();

#if UseOptions
            #region UseWebSocketsOptions
            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            };
            app.UseWebSockets(webSocketOptions);
            #endregion
#endif

            #region AcceptWebSocket
            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/subserver/ws")//这里可以定义路径的格式
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        var buffer = new byte[1024 * 4];
                        WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                        string restring = Encoding.ASCII.GetString(buffer);

                        JObject jObject = (JObject)JsonConvert.DeserializeObject(restring);//序列化结果

                        //  string PiToken = jObject["PiToken"].ToString();
                        //验证PiToken
                        string subserverId = jObject["SubserverID"].ToString();

                        macAvailable          = true;
                        ErrorRootobject error = new ErrorRootobject
                        {
                            ReturnCode = "1001",
                            msg        = "JSON format error"
                        };
                        string serial = JsonConvert.SerializeObject(error);

                        result = (JObject)JsonConvert.DeserializeObject(serial);

                        if (macAvailable)
                        {
                            var conn = new MySqlConnection(Configuration.GetConnectionString("DefaultConnection"));

                            conn.Open();
                            var command  = conn.CreateCommand();
                            string query = "SELECT  Username"
                                           + " FROM UserToSubserver "
                                           + "WHERE SubserverID = '" + subserverId + "'";

                            command.CommandText       = query;
                            DbDataReader BindedReader = await command.ExecuteReaderAsync();

                            if (BindedReader.HasRows)
                            {
                                //如果查询到被绑定
                                //我担心会查出一个MAC地址绑定了多个用户的情况
                                //后期可以设置让MAC地址为主键
                                BindedReader.Read();
                                string buser     = BindedReader["Username"].ToString();
                                error.ReturnCode = "1005";
                                error.msg        = " This Subserver is owned by " + buser;

                                serial      = JsonConvert.SerializeObject(error);
                                result      = (JObject)JsonConvert.DeserializeObject(serial);
                                var buffer1 = Encoding.ASCII.GetBytes(serial);
                                //将
                                await webSocket.SendAsync(new ArraySegment <byte>(buffer1), webSocketReceiveResult.MessageType, webSocketReceiveResult.EndOfMessage, CancellationToken.None);
                                conn.Close();//关闭连接

                                //加入到字典中
                                WebsocketClient.AddToDictionary(subserverId, webSocket);
                            }
                            else
                            {
                                var buffer1      = new byte[1024 * 4];
                                error.ReturnCode = "1006";
                                error.msg        = " SubserverID is not bound  ";

                                serial  = JsonConvert.SerializeObject(error);
                                result  = (JObject)JsonConvert.DeserializeObject(serial);
                                buffer1 = Encoding.ASCII.GetBytes(serial);
                                //将
                                int a = result.Count;

                                await webSocket.SendAsync(new ArraySegment <byte>(buffer1), webSocketReceiveResult.MessageType, webSocketReceiveResult.EndOfMessage, CancellationToken.None);
                            }
                            conn.Close();
                        }
                        //启动监听
                        await ListenToSubserver(context, webSocket);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else
                {
                    await next();
                }
            });
            #endregion
            app.UseFileServer();

            app.UseStaticFiles();



            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 25
0
    protected void checkAssignmentSubmission()
    {
        var    result = 0;
        string points = "";

        MySqlConnection connection1 = new MySqlConnection(connectionString);

        connection1.Open();
        try
        {
            MySqlCommand mysqlcmd = connection1.CreateCommand();
            mysqlcmd.CommandText = "SELECT count(*) FROM studentassignments WHERE assignmentId=@assignmentId and studentId=@userId";
            mysqlcmd.Parameters.AddWithValue("assignmentId", assignID);
            mysqlcmd.Parameters.AddWithValue("userId", userID);
            result = Convert.ToInt32(mysqlcmd.ExecuteScalar());
        }
        catch (Exception ex)
        {
            //Response.Redirect("~/Error");
        }
        finally
        {
            if (connection1.State == ConnectionState.Open)
            {
                connection1.Close();
            }
        }
        if (result > 0)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            connection.Open();
            try
            {
                MySqlCommand comm = connection.CreateCommand();
                comm.CommandText = "SELECT points,filePath FROM studentassignments where assignmentId=@assignmentId and studentId=@userId";
                comm.Parameters.AddWithValue("@assignmentId", assignID);
                comm.Parameters.AddWithValue("@userId", userID);
                MySqlDataAdapter adap = new MySqlDataAdapter(comm);
                DataSet          ds   = new DataSet();
                adap.Fill(ds);
                DataTable dt = ds.Tables[0];
                points                    = dt.Rows[0][0].ToString();
                submissionPath            = dt.Rows[0][1].ToString();
                Session["submissionPath"] = submissionPath;
            }
            catch (Exception ex)
            {
                Response.Redirect("~/Error");
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }
        if (points != null && submissionPath != "")
        {
            resultPH.Visible = true;
            if (points != "")
            {
                gradeLBL.Text = "Marks: " + points;
            }
            uploadAssignment.Text = "Resubmit Assignment";
        }
    }
Exemplo n.º 26
0
 // Use Database;
 public void UseDatabase(string strDBName)
 {
     using var command   = _connection?.CreateCommand();
     command.CommandText = string.Format("Use {0};", strDBName);
     command.ExecuteNonQuery();
 }
Exemplo n.º 27
0
        public SimpleResponse GetAvatars(string accountId, string accountIdCsvList, string avatarId, string isDefault, string isEnabled)
        {
            mServiceLog.Log.InfoFormat("GetAvatars: accountId={0}, avatarId={1}, isDefault={2}, isEnabled={3}", accountId, avatarId, isDefault, isEnabled);
            StringBuilder sqlOptionsAvatars       = new StringBuilder();
            StringBuilder sqlOptionsSystemAvatars = new StringBuilder();

            StringBuilder xmlBuilder = new StringBuilder();

            try
            {
                using (MySqlConnection mysqlConnection = new MySqlConnection(WebConfig.AvatarsDBConnectionString))
                {
                    mysqlConnection.Open();
                    string getAvatarsForAccountQuery       = "";
                    string getSystemAvatarsForAccountQuery = "";
                    bool   isUserAccount = false;                   //this is set if something needs to return something from
                    bool   isUserAvatar  = false;

                    List <XElement> avatarList              = new List <XElement>();
                    MySqlCommand    getAvatarsCommand       = mysqlConnection.CreateCommand();
                    MySqlCommand    getSystemAvatarsCommand = mysqlConnection.CreateCommand();


                    if (avatarId != null)
                    {
                        if (avatarId == "")
                        {
                            avatarId = "-1";
                        }

                        sqlOptionsAvatars.Append("AND AccountToAvatarMapping.AvatarId=@AvatarId ");
                        getAvatarsCommand.Parameters.AddWithValue("@AvatarId", avatarId);
                        sqlOptionsSystemAvatars.Append("AND AvatarId=@AvatarId ");
                        getSystemAvatarsCommand.Parameters.AddWithValue("@AvatarId", avatarId);
                    }
                    if (accountId != null)
                    {
                        if (accountId == "")
                        {
                            accountId = "-1";
                        }
                        sqlOptionsAvatars.Append("AND AccountToAvatarMapping.HangoutAccountId=@HangoutAccountId ");
                        getAvatarsCommand.Parameters.AddWithValue("@HangoutAccountId", accountId);
                        isUserAccount = true;
                    }
                    else if (accountIdCsvList != null)
                    {
                        string csvList = "";
                        if (accountIdCsvList != "")
                        {
                            string[] accountIds = accountIdCsvList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            string   delimiter  = "";
                            foreach (string s in accountIds)
                            {
                                uint sUint = Convert.ToUInt32(s);
                                csvList  += delimiter + "'" + sUint.ToString() + "'";
                                delimiter = ",";
                            }
                            if (csvList == "")
                            {
                                csvList = "-1";
                            }
                        }
                        else
                        {
                            csvList = "-1";
                        }
                        sqlOptionsAvatars.Append("AND AccountToAvatarMapping.HangoutAccountId IN ( " + csvList + " ) ");
                        isUserAccount = true;
                    }

                    if (!String.IsNullOrEmpty(isDefault))
                    {
                        string boolValue = "0";
                        if (isDefault == "1" || isDefault.ToLower() == "true")
                        {
                            boolValue = "1";
                        }
                        sqlOptionsAvatars.Append("AND AccountToAvatarMapping.IsDefault=@IsDefault ");
                        getAvatarsCommand.Parameters.AddWithValue("@IsDefault", boolValue);
                    }
                    if (!String.IsNullOrEmpty(isEnabled))
                    {
                        string boolValue = "0";
                        if (isEnabled == "1" || isEnabled.ToLower() == "true")
                        {
                            boolValue = "1";
                        }
                        sqlOptionsAvatars.Append("AND Avatars.IsEnabled=@IsEnabled ");
                        sqlOptionsSystemAvatars.Append("AND SystemAvatars.IsEnabled=@IsEnabled ");

                        getAvatarsCommand.Parameters.AddWithValue("@IsEnabled", boolValue);
                        getSystemAvatarsCommand.Parameters.AddWithValue("@IsEnabled", boolValue);
                    }


                    getSystemAvatarsForAccountQuery += "SELECT * FROM SystemAvatars  " +
                                                       "WHERE 1 " + sqlOptionsSystemAvatars.ToString() +
                                                       "ORDER BY AvatarId ";

                    getSystemAvatarsCommand.CommandText = getSystemAvatarsForAccountQuery;
                    if (!isUserAccount && !isUserAvatar)
                    {
                        using (MySqlDataReader getSystemAvatarsReader = getSystemAvatarsCommand.ExecuteReader())
                        {
                            while (getSystemAvatarsReader.Read())
                            {
                                xmlBuilder.Append(FormatAvatarData(
                                                      getSystemAvatarsReader["AvatarId"].ToString(),
                                                      getSystemAvatarsReader["IsEnabled"].ToString(),
                                                      "1",
                                                      "1",
                                                      getSystemAvatarsReader["AvatarDNA"].ToString()
                                                      ));
                            }
                        }
                    }
                    getSystemAvatarsCommand.Dispose();


                    getAvatarsForAccountQuery += "SELECT * FROM Avatars  " +
                                                 "LEFT JOIN AccountToAvatarMapping ON (AccountToAvatarMapping.AvatarId = Avatars.AvatarId) " +
                                                 "WHERE 1 " + sqlOptionsAvatars.ToString() + " ORDER BY AccountToAvatarMapping.AvatarId ; ";


                    getAvatarsCommand.CommandText = getAvatarsForAccountQuery;
                    using (MySqlDataReader getAvatarsReader = getAvatarsCommand.ExecuteReader())
                    {
                        while (getAvatarsReader.Read())
                        {
                            xmlBuilder.Append(FormatAvatarData(
                                                  getAvatarsReader["AvatarId"].ToString(),
                                                  getAvatarsReader["IsEnabled"].ToString(),
                                                  getAvatarsReader["IsDefault"].ToString(),
                                                  getAvatarsReader["HangoutAccountId"].ToString(),
                                                  getAvatarsReader["AvatarDNA"].ToString()
                                                  ));
                        }
                    }
                    getAvatarsCommand.Dispose();
                }
                return(new SimpleResponse("Avatars", xmlBuilder.ToString()));
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 28
0
        private void button1_Click(object sender, EventArgs e)
        {
            String name = textBox1.Text;
            String city = textBox2.Text;

            if (name == "" || city == "")
            {
                System.Windows.Forms.MessageBox.Show("Please fill in all informations.");
            }
            else
            {
                con.Open();

                MySqlCommand     myCommand = con.CreateCommand();
                MySqlTransaction myTrans;

                myTrans = con.BeginTransaction();

                myCommand.Connection  = con;
                myCommand.Transaction = myTrans;



                try
                {
                    myCommand.CommandText = "call insert_manufacturer(?name, ?city)";

                    myCommand.Parameters.Add(new MySqlParameter("name", name));
                    myCommand.Parameters.Add(new MySqlParameter("city", city));


                    myCommand.ExecuteNonQuery();


                    myTrans.Commit();

                    System.Windows.Forms.MessageBox.Show("Successfully added");
                }
                catch (Exception er)
                {
                    System.Windows.Forms.MessageBox.Show(er.GetType().ToString());
                    try
                    {
                        myTrans.Rollback();
                    }
                    catch (Exception ex)
                    {
                        if (myTrans.Connection != null)
                        {
                            Console.WriteLine("An exception of type " + ex.GetType() +
                                              " was encountered while attempting to roll back the transaction.");
                        }
                    }
                }
                finally
                {
                    con.Close();
                    this.Hide();
                }
            }
        }
Exemplo n.º 29
0
    void ExecuteScripts(string scriptDirectory, string tablePrefix)
    {
        #region ExecuteScriptsSqlServer

        using (var connection = new SqlConnection("ConnectionString"))
        {
            connection.Open();
            using (var transaction = connection.BeginTransaction())
            {
                foreach (var createScript in Directory.EnumerateFiles(
                             path: scriptDirectory,
                             searchPattern: "*_Create.sql",
                             searchOption: SearchOption.AllDirectories))
                {
                    using (var command = connection.CreateCommand())
                    {
                        command.Transaction = transaction;
                        command.CommandText = File.ReadAllText(createScript);
                        var tablePrefixParameter = command.CreateParameter();
                        tablePrefixParameter.ParameterName = "tablePrefix";
                        tablePrefixParameter.Value         = tablePrefix;
                        command.Parameters.Add(tablePrefixParameter);
                        var schemaParameter = command.CreateParameter();
                        schemaParameter.ParameterName = "schema";
                        schemaParameter.Value         = "dbo";
                        command.Parameters.Add(schemaParameter);
                        command.ExecuteNonQuery();
                    }
                }
                transaction.Commit();
            }
        }

        #endregion

        #region ExecuteScriptsMySql

        using (var connection = new MySqlConnection("ConnectionString"))
        {
            connection.Open();
            using (var transaction = connection.BeginTransaction())
            {
                foreach (var createScript in Directory.EnumerateFiles(
                             path: scriptDirectory,
                             searchPattern: "*_Create.sql",
                             searchOption: SearchOption.AllDirectories))
                {
                    using (var command = connection.CreateCommand())
                    {
                        command.Transaction = transaction;
                        command.CommandText = File.ReadAllText(createScript);
                        var parameter = command.CreateParameter();
                        parameter.ParameterName = "tablePrefix";
                        parameter.Value         = tablePrefix;
                        command.Parameters.Add(parameter);
                        command.ExecuteNonQuery();
                    }
                }
                transaction.Commit();
            }
        }

        #endregion

        #region ExecuteScriptsOracle
        using (var connection = new OracleConnection("ConnectionString"))
        {
            connection.Open();
            using (var transaction = connection.BeginTransaction())
            {
                foreach (var createScript in Directory.EnumerateFiles(
                             path: scriptDirectory,
                             searchPattern: "*_Create.sql",
                             searchOption: SearchOption.AllDirectories))
                {
                    using (var command = connection.CreateCommand())
                    {
                        command.Transaction = transaction;
                        command.CommandText = File.ReadAllText(createScript);
                        var parameter = command.CreateParameter();
                        parameter.ParameterName = "tablePrefix";
                        parameter.Value         = tablePrefix;
                        command.Parameters.Add(parameter);
                        command.ExecuteNonQuery();
                    }
                }
                transaction.Commit();
            }
        }
        #endregion
    }
Exemplo n.º 30
0
        public static List <Produkt> produktnachkat(int katid)
        {
            const string constring = "Server=localhost;Database=praktikum;Uid=webapp;Pwd=webapp;";

            List <Produkt>  result = new List <Produkt>();
            MySqlConnection con    = new MySqlConnection(constring); // lässt sich per using(){} noch besser handhaben
            MySqlConnection con2   = new MySqlConnection(constring); // lässt sich per using(){} noch besser handhaben

            con.Open();
            con2.Open();

            MySqlCommand cmd;
            MySqlCommand cmd2;

            cmd2 = con2.CreateCommand();
            cmd  = con.CreateCommand();
            if (katid > 0)
            {
                cmd.CommandText = "with recursive kat as (select k.id, k.bezeichnung, k.oberkategorie from kategorie as k";

                // einfachstes Beispiel für eine Anpassung der Query je nach Anwendungszustand (ist ein parameter vorhanden zB)
                if (katid > 0)
                {
                    cmd.CommandText += " WHERE id = " + katid;
                }
                cmd.CommandText += " union all select k1.id, k1.bezeichnung, k2.bezeichnung from kategorie as k1 join kat as k2 on k2.id = k1.Oberkategorie) select distinct p.ID, beschreibung, Bezeichnung, Binaerdaten from produkt as p join kat as k on k.ID=p.katid left join bild on bild.id=p.bildid where p.katid=k.ID order by k.id";


                // hier wird nun zum DBMS gesendet und die Antwortrelation vorbereitet

                MySqlDataReader r = cmd.ExecuteReader();
                while (r.Read())
                {
                    Produkt p = new Produkt();
                    p.ID           = Convert.ToInt16(r["ID"]);
                    p.Name         = r["beschreibung"].ToString();
                    p.Beschreibung = r["Bezeichnung"].ToString();
                    p.binaer       = r["Binaerdaten"] as byte[];
                    result.Add(p);
                }
            }
            else
            {
                cmd.CommandText = "select produkt.id, produkt.Beschreibung , bild.Alttext , bild.Binaerdaten from produkt inner join bild on produkt.bildid = bild.id order by RAND()";
                MySqlDataReader r = cmd.ExecuteReader();
                while (r.Read())
                {
                    Produkt p = new Produkt();
                    p.ID           = Convert.ToInt16(r["ID"]);
                    p.Name         = r["beschreibung"].ToString();
                    p.Beschreibung = r["Alttext"].ToString();
                    p.binaer       = r["Binaerdaten"] as byte[];
                    result.Add(p);
                }
            }


            con.Close();
            con2.Close();

            return(result);
        }
Exemplo n.º 31
0
        protected DisposableAction WithMySqlDatabase(out string connectionString, out string databaseName, string dataSet, bool includeData = true)
        {
            databaseName = "sql_test_" + Guid.NewGuid();
            var rawConnectionString = MySqlConnectionString.Instance.VerifiedConnectionString.Value;

            if (string.IsNullOrEmpty(rawConnectionString))
            {
                throw new InvalidOperationException("The connection string for MySql db is null");
            }

            connectionString = $"{rawConnectionString};database='{databaseName}'";

            using (var connection = new MySqlConnection(rawConnectionString))
            {
                connection.Open();

                using (var dbCommand = connection.CreateCommand())
                {
                    dbCommand.CommandTimeout = CommandTimeout;
                    dbCommand.CommandText    = $"CREATE DATABASE `{databaseName}`";
                    dbCommand.ExecuteNonQuery();
                }
            }

            using (var dbConnection = new MySqlConnection(connectionString))
            {
                dbConnection.Open();

                var assembly = Assembly.GetExecutingAssembly();

                using (var dbCommand = dbConnection.CreateCommand())
                {
                    dbCommand.CommandTimeout = CommandTimeout;
                    var textStreamReader = new StreamReader(assembly.GetManifestResourceStream("SlowTests.Data.mysql." + dataSet + ".create.sql"));
                    dbCommand.CommandText = textStreamReader.ReadToEnd();
                    dbCommand.ExecuteNonQuery();
                }

                if (includeData)
                {
                    using (var dbCommand = dbConnection.CreateCommand())
                    {
                        dbCommand.CommandTimeout = CommandTimeout;
                        var textStreamReader = new StreamReader(assembly.GetManifestResourceStream("SlowTests.Data.mysql." + dataSet + ".insert.sql"));
                        dbCommand.CommandText = textStreamReader.ReadToEnd();
                        dbCommand.ExecuteNonQuery();
                    }
                }
            }

            string dbName = databaseName;

            return(new DisposableAction(() =>
            {
                using (var con = new MySqlConnection(rawConnectionString))
                {
                    con.Open();

                    using (var dbCommand = con.CreateCommand())
                    {
                        dbCommand.CommandTimeout = CommandTimeout;
                        var dropDatabaseQuery = "DROP DATABASE `{0}`";
                        dbCommand.CommandText = string.Format(dropDatabaseQuery, dbName);

                        dbCommand.ExecuteNonQuery();
                    }
                }
            }));
        }
Exemplo n.º 32
0
 private void button1_Click(object sender, EventArgs e)
 {
     String full = fullname.Text;
     String last = lastname.Text;
     String da = dob.Value.ToString("MM/dd/yyyy");
     String pho = phone.Text;
     String gen = "";
     if (male.Checked)
     {
         gen = "Male";
     }
     if (female.Checked)
     {
         gen = "Female";
     }
     Double sal = Convert.ToDouble(salary.Text);
     String ni = nic.Text;
     String add = address.Text;
     if (full == "" || last == "" || da =="" || pho =="" || gen =="" || ni == "" || add == "")
     {
         MessageBox.Show("Every Field are Required");
     }
     else
     {
         DateTime tod = DateTime.Today;
         string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=debuggeddb;";
         MySqlConnection databaseConnection = new MySqlConnection(connectionString);
         try
         {
             databaseConnection.Open();
             MySqlCommand comm = databaseConnection.CreateCommand();
             comm.CommandText = "INSERT INTO employeetable(`FirstName`,`LastName`,`DOB`,`NIC`,`Gender`,`Address`,`Salary`,`PhoneNo`,`AppDate`) VALUES(@ff,@ll,@dd,@nn,@gg,@aa,@ss,@pp,@ap);";
             comm.Parameters.AddWithValue("@ff", full);
             comm.Parameters.AddWithValue("@ll", last);
             comm.Parameters.AddWithValue("@dd", da);
             comm.Parameters.AddWithValue("@nn", ni);
             comm.Parameters.AddWithValue("@gg", gen);
             comm.Parameters.AddWithValue("@aa", add);
             comm.Parameters.AddWithValue("@ss", sal);
             comm.Parameters.AddWithValue("@pp", pho);
             comm.Parameters.AddWithValue("@ap", tod);
             comm.ExecuteNonQuery();
             databaseConnection.Close();
             //clear the text
             fullname.Text = "";
             lastname.Text = "";
             phone.Text = "";
             salary.Text = "";
             nic.Text = "";
             address.Text = "";
             //message
             MessageBox.Show("Data Has been successfully inserted");
             this.Hide();
             employeeView ev = new employeeView();
             ev.Show();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
Exemplo n.º 33
0
        public void LockedTable()
        {
            string connStr = GetConnectionString(true);

              connStr = String.Format(@"Use Affected Rows=true;allow user variables=yes;Server=localhost;Port={0};
            Database={1};Uid=root;Connect Timeout=35;default command timeout=90;charset=utf8", this.port, database0);

              execSQL(@"CREATE TABLE `t1` (
                `Key` int(10) unsigned NOT NULL auto_increment,
                `Val` varchar(100) NOT NULL,
                `Val2` varchar(100) NOT NULL default '',
                PRIMARY KEY  (`Key`)
                ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1");
              execSQL(@"CREATE TABLE `t2` (
                `Key` int(10) unsigned NOT NULL auto_increment,
                `Val` varchar(100) NOT NULL,
                PRIMARY KEY  (`Key`)
                ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1");

              execSQL("lock tables t2 read");

              using (TransactionScope scope = new TransactionScope())
              {
            using (MySqlConnection conn = new MySqlConnection(connStr))
            using (MySqlCommand cmd = conn.CreateCommand())
            {
              conn.Open();
              cmd.CommandText = @"insert into t1 (Val,Val2) values (?value1, ?value2)"; ;
              cmd.CommandTimeout = 5;
              cmd.Parameters.AddWithValue("?value1", new Random().Next());
              cmd.Parameters.AddWithValue("?value2", new Random().Next());
              cmd.ExecuteNonQuery();
            }

            using (MySqlConnection conn = new MySqlConnection(connStr))
            using (MySqlCommand cmd = conn.CreateCommand())
            {
              conn.Open();
              cmd.CommandText = @"insert into t2 (Val) values (?value)";
              cmd.CommandTimeout = 5;
              cmd.Parameters.AddWithValue("?value", new Random().Next());
              try
              {
            cmd.ExecuteNonQuery();
              }
              catch (MySqlException ex)
              {
            Assert.IsTrue(ex.InnerException is TimeoutException);
              }
            }

            scope.Complete();
              }

              MySqlPoolManager.ClearAllPools();
        }
Exemplo n.º 34
0
		public static void UpdateIssue(long IssueId, IssueUpdateData Issue)
		{
			using (MySqlConnection Connection = new MySqlConnection(SqlConnector.ConnectionString))
			{
				Connection.Open();

				using (MySqlCommand Command = Connection.CreateCommand())
				{
					List<string> Columns = new List<string>();
					List<string> Values = new List<string>();
					if(Issue.Summary != null)
					{
						Columns.Add("Summary");
						Values.Add("@Summary");
						Command.Parameters.AddWithValue("@Summary", SanitizeText(Issue.Summary, IssueSummaryMaxLength));
					}
					if (Issue.Owner != null)
					{
						Columns.Add("OwnerId");
						Values.Add("@OwnerId");
						Command.Parameters.AddWithValue("OwnerId", FindOrAddUserId(Issue.Owner, Connection));
					}
					if(Issue.NominatedBy != null)
					{
						Columns.Add("NominatedById");
						Values.Add("@NominatedById");
						Command.Parameters.AddWithValue("NominatedById", FindOrAddUserId(Issue.NominatedBy, Connection));
					}
					if(Issue.Acknowledged.HasValue)
					{
						Columns.Add("AcknowledgedAt");
						Values.Add(Issue.Acknowledged.Value? "UTC_TIMESTAMP()" : "NULL");
					}
					if(Issue.FixChange.HasValue)
					{
						Columns.Add("FixChange");
						Values.Add("@FixChange");
						Command.Parameters.AddWithValue("FixChange", Issue.FixChange.Value);
					}
					if(Issue.Resolved.HasValue)
					{
						Columns.Add("ResolvedAt");
						Values.Add(Issue.Resolved.Value? "UTC_TIMESTAMP()" : "NULL");
					}

					StringBuilder CommandText = new StringBuilder("UPDATE ugs_db.Issues SET ");
					for(int idx = 0; idx < Columns.Count; idx++)
					{
						CommandText.Append(String.Format("{0}={1}", Columns[idx], Values[idx]));
						if(idx != Columns.Count - 1)
						{
							CommandText.Append(",");
						}
					}
					CommandText.Append(" WHERE Id = @IssueId");
					Command.CommandText = CommandText.ToString();
					Command.Parameters.AddWithValue("@IssueId", IssueId);
					Command.ExecuteNonQuery();
				}
			}
		}