protected string LookUpEmailBasedOnPhoneName()
        {
            string phone = TextBox3.Text;
            string name = TextBox2.Text;

            try
            {
                SqlConnection connection = new SqlConnection("Data Source = itksqlexp8; Integrated Security = true");
                connection.Open();
                connection.ChangeDatabase("itk485nnrs");
                string query =
                            "Select email from signuptable where cellPhone = '"+phone+"' and firstname='"+name+"'";
                SqlCommand command = new SqlCommand(query, connection);

                var reader = command.ExecuteReader();
                if (reader.Read())
                {
                    emailFromSignUpTable = reader["email"]+"";
                    connection.Close();
                }
                reader.Close();
            }
            catch(Exception ex)
            {
                Response.Write("Some error occured: "+ex.Message);
            }
            return emailFromSignUpTable;
        }
Example #2
0
        public void TestCleanup()
        {
            var repositoryType = Instance.GetType();

            if (repositoryType == typeof(JsonRepository))
            {
                if (Directory.Exists(JsonWorkingFolder))
                {
                    Directory.Delete(JsonWorkingFolder, recursive: true);
                }
            }
            else if (repositoryType == typeof(SqlRepository))
            {
                using (var cnn = new SqlConnection(SqlConnectionString))
                using (var cmd = new SqlCommand("EXEC sp_MSforeachtable @command1 = 'TRUNCATE TABLE ?'", cnn))
                {
                    cnn.Open();
                    cnn.ChangeDatabase(SqlDatabaseName);
                    cmd.ExecuteNonQuery();
                }
            }
            else if (repositoryType == typeof(MongoRepository))
            {
                var server = new MongoClient(MongoConnectionString).GetServer();
                server.DropDatabase(MongoDatabaseName);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateCatagories();
                Session["prevAList"] = "";
                Session["prevBList"] = "";
                        SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
                //string img= "../UserWebForms/";
                dbConnection.Open();
                 dbConnection.ChangeDatabase("nasa_SilentAuction_v1");
                //string sqlQuery = "select * from item where approvalStatus=" +true;
                SqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from item where approvalStatus= 1";


                //string strQuery = "select * from item where approvalStatus=1";
                //SqlCommand cmd = new SqlCommand(strQuery, dbConnection);

                cmd.CommandType = CommandType.Text;
                //cmd.CommandText = CommandText.te
                cmd.Connection = dbConnection;

                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                // SqlDataReader pendingListDisplay = cmd.ExecuteReader();
                da.Fill(dt);
                DataList1.DataSource = dt;
                DataList1.DataBind();
                dbConnection.Close();

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Important: If didn't check this, the list will get re-populated (and the 1st item will be the selected one)!
            if (!IsPostBack) 
            {
                        SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");

                dbConnection.Open();
               dbConnection.ChangeDatabase("nasa_SilentAuction_v1");
                string SQLString = "SELECT DISTINCT categoryName,categoryPrefix FROM category";

                SqlCommand cmd = new SqlCommand(SQLString, dbConnection);

               

                SqlDataReader ddlValues;
                ddlValues = cmd.ExecuteReader();

                DropDownList1.DataSource = ddlValues;
                DropDownList1.DataValueField = "categoryPrefix";
                DropDownList1.DataTextField = "categoryName";
                DropDownList1.DataBind();

                dbConnection.Close();

            }
        }
        public static SqlConnection GetConnection(string sConnection, string sDatabase)
        {
            SqlConnection dbconnection = null;

            try
            {
                dbconnection = new SqlConnection(sConnection);
                dbconnection.Open();

                 if (sDatabase.Trim() != string.Empty)
                {
                    dbconnection.ChangeDatabase(sDatabase);
                }
            }
            catch (System.InvalidOperationException e)
            {
                throw new Exception("GetConnection error: " + e.Message);
            }

            catch (System.Data.SqlClient.SqlException e)
            {
                throw new Exception("GetConnection error2: " + e.Message);
            }

            return dbconnection;
        }
        protected void BindDataToUserList()
        {
            try
            {
                        SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
                dbConnection.Open();
               dbConnection.ChangeDatabase("nasa_SilentAuction_v1");

                String searchString = "select distinct buyerid from item where buyerid is not null";
                SqlCommand SQLString = new SqlCommand(searchString, dbConnection);
                SqlDataAdapter da = new SqlDataAdapter(SQLString);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DropDownList1.DataSource = dt;
                DropDownList1.DataValueField = "buyerid";
                DropDownList1.DataTextField = "buyerid";
                DropDownList1.DataBind();
                dbConnection.Close();

                //Adding "Please select" option in dropdownlist
                DropDownList1.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select a buyer", ""));
            }
            catch (SqlException exception)
            {
                System.Diagnostics.Debug.WriteLine("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
            }
        }
        /// <summary>
        /// becareful
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static Boolean dropDB(String connectionString="")
        {
            try
            {
                SqlConnectionStringBuilder pa = new SqlConnectionStringBuilder(connectionString);
                using (SqlConnection sqlconnection = new
            SqlConnection(connectionString))
                {
                    sqlconnection.Open();
                    // if you used master db as Initial Catalog, there is no need to change database
                    sqlconnection.ChangeDatabase("master");

                    string rollbackCommand = @"ALTER DATABASE ["+pa.InitialCatalog+"] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE";

                    SqlCommand deletecommand = new SqlCommand(rollbackCommand, sqlconnection);

                    deletecommand.ExecuteNonQuery();

                    string deleteCommand = @"DROP DATABASE [" + pa.InitialCatalog + "]";

                    deletecommand = new SqlCommand(deleteCommand, sqlconnection);

                    deletecommand.ExecuteNonQuery();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return false;
            }
        }
Example #8
0
        private void buttonConnections_Click(object sender, EventArgs e)
        {
            SqlConnection objCon = new SqlConnection();

            /** option 1: The "HardCoded" way **/
            objCon.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog = DB1; Integrated Security=True;";

            /** option 2: The "Before .Net v2.0" way**/
            objCon.ConnectionString = ConfigurationSettings.AppSettings["Conn2"];

            /** option 3: The "Common" way  (Note: You must have a reference to the System.Configuration .dll) **/
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["Conn3"].ConnectionString;

            objCon.StateChange += new StateChangeEventHandler(objCon_StateChange);
            try
            {
                objCon.Open();
                objCon.ChangeDatabase("Northwind");
                MessageBox.Show("Database is now: " + objCon.Database);

            }
            finally
            {
                objCon.Close();
            }
            MessageBox.Show("Database state after Close(): " + objCon.State.ToString());
        }
        void populateDropDown()
        {
                    SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");

            try
            {
                dbConnection.Open();
                dbConnection.ChangeDatabase("nasa_SilentAuction_v1");
                String query = "SELECT * FROM USERS WHERE approvalStatus=1";
                SqlCommand cmd = new SqlCommand(query, dbConnection);

                SqlDataReader data = cmd.ExecuteReader();
                while (data.Read())
                {
                    ListItem u = new ListItem();
                    u.Text = (string)data["userID"];
                    u.Value = (string)data["userID"];
                    buyerIdList.Items.Add(u);
                }
            }
            catch (SqlException exception)
            {
                Response.Write("Error Code: " + exception.Message);
            }
        }
        protected void getBidderDetails()
        {
            string userid = Session["user_id"].ToString();
            try
            {
                        SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
                dbConnection.Open();
                dbConnection.ChangeDatabase("nasa_SilentAuction_v1");

                String searchString = "select * from users "
                                        + " where userId = @userID; ";

                SqlCommand SQLString = new SqlCommand(searchString, dbConnection);
                SQLString.Parameters.AddWithValue("@userID", userid);

                SqlDataReader idRecords = SQLString.ExecuteReader();
                if (idRecords.Read())
                {
                    bidderName.Text = idRecords["firstName"].ToString().ToUpper();
                    bidderNumber.Text = idRecords["bidder_no"].ToString();
                }

                idRecords.Close();
                dbConnection.Close();
            }
            catch (SqlException exception)
            {
                Response.Write("<p>Error code " + exception.Number
                         + ": " + exception.Message + "</p>");

            }

        }
        protected bool checkIfItemSoldToThisUser()
        {
            bool itemSold = false;
            string userid = Session["user_id"].ToString();
            try
            {
                        SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
                dbConnection.Open();
                dbConnection.ChangeDatabase("nasa_SilentAuction_v1");

                String searchString = "select * from item where buyerID = @userID";

                SqlCommand SQLString = new SqlCommand(searchString, dbConnection);
                SQLString.Parameters.AddWithValue("@userID", userid);

                SqlDataReader idRecords = SQLString.ExecuteReader();
                if (idRecords.Read())
                {
                    itemSold = true;
                }

                idRecords.Close();
                dbConnection.Close();
            }
            catch (SqlException exception)
            {
                Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
            }
            return itemSold;
        }
        protected void updateUserProfile(object sender, EventArgs e)
        {

                    SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
            try
            {
                dbConnection.Open();
                dbConnection.ChangeDatabase("nasa_SilentAuction_v1");
                string name = Session["user_id"] as string;
             str = "Update users set firstName='" + fname.Text + "', lastName='" + lname.Text + "', addressLine1='" + addressLine1.Text + "', addressLine2='" + addressLine2.Text + "', city='" + city.Text + "', stateName='" + state.Text + "', phoneHome='" + phoneNumber.Text + "', phncarrier='" + networkProvider.SelectedValue + "', email='" + email.Text + "', password='" + Password1.Text + "' WHERE userID='" + userid1.Text + "'";
                SqlCommand sqlCommand = new SqlCommand(str, dbConnection);
              var x =   sqlCommand.ExecuteNonQuery();


                string message = "Bingo! your profile has been Updated. For confirmation we have sent you an email, Happy Bidding :)" ;
                textMessage = new SMSService(networkProvider.Text, phoneNumber.Text, message);
                textMessage.SendTextMessage(textMessage);


                UpdateReply.Text = "Data Updated Successfully, Please check your inbox :)";
               
            }
            catch (SqlException exception)
            {
                Response.Write("<p>Error code " + exception.Number
                    + ": " + exception.Message + "</p>");
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            String sc = "Data Source=.\\sqlexpress;Initial Catalog=MASTER;Integrated Security=true;";

            using (SqlConnection c = new SqlConnection(sc))
            {
                String cmd = "CREATE DATABASE VS2010";

                using (SqlCommand k = new SqlCommand(cmd, c))
                {
                    //SqlCommand faz parte do modelo CONECTADO
                    //ExecuteNonQuery retorna o nĂºmero de linhas afetadas

                    c.Open();

                    k.ExecuteNonQuery();

                    c.ChangeDatabase("VS2010");

                    k.CommandText = "CREATE TABLE PESSOA (COD_PESSOA INT, NOME_PESSOA VARCHAR(50), SEXO_PESSOA CHAR(1))";

                    k.ExecuteNonQuery();

                    c.Close();
                }
            }

            Console.WriteLine("funcionou");

            Console.ReadKey();
        }
        protected void LookUpForAdminAccess()
        {
            string adminAccess = "";

            try
            {
                SqlConnection connection = new SqlConnection("Data Source = itksqlexp8; Integrated Security = true");
                connection.Open();
                connection.ChangeDatabase("itk485nnrs");
                string tempEmail = Session["loginEmail"].ToString() ;
                string query =
                            "Select access from signuptable where email = '" + tempEmail + "'";
                SqlCommand command = new SqlCommand(query, connection);

                var reader = command.ExecuteReader();
                if (reader.Read())
                {
                    adminAccess = reader["access"] + "";
                    connection.Close();
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Response.Write("Some error occured: " + ex.Message);
            }
            Session["adminAccess"] = adminAccess;
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Page.IsPostBack)
     {
         Page.Validate();
         if (Page.IsValid)
         {
             SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
             try
             {
                 dbConnection.Open();
                 dbConnection.ChangeDatabase("ConservationSchool");
                 string SQLString = "SELECT * FROM students WHERE studentID=" + studentID.Text;
                 SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
                 SqlDataReader idRecords = checkIDTable.ExecuteReader();
                 if (idRecords.Read())
                 {
                     Response.Redirect("ReturningStudent.aspx?studentID=" + studentID.Text);
                     idRecords.Close();
                 }
                 else
                 {
                     validateMessage.Text = "<p>**Invalid student ID**</p>";
                     idRecords.Close();
                 }
             }
             catch (SqlException exception)
             {
                 Response.Write("<p>Error code " + exception.Number
                     + ": " + exception.Message + "</p>");
             }
         }
     }
 }
Example #16
0
        public List<MysteryGame> GameList(string ConnectionStringValue, string databasename, string filter)
        {
            List<MysteryGame> returnValue = new List<MysteryGame>();
            SqlConnection sqlConn = new SqlConnection(ConnectionStringValue);
            if (sqlConn.State == ConnectionState.Closed)
                sqlConn.Open();
            sqlConn.ChangeDatabase(databasename);
            SqlCommand spHandler = new SqlCommand("spGames", sqlConn);
            spHandler.Parameters.AddWithValue("@step", 3);
            spHandler.Parameters.AddWithValue("@filter", filter);
            spHandler.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter daGameHandler = new SqlDataAdapter(spHandler);
            DataTable dtGameHandler = new DataTable();
            daGameHandler.Fill(dtGameHandler);

            var convertedList = (from rw in dtGameHandler.AsEnumerable()
                                 select new MysteryGame()
                                 {
                                     gameid = Convert.ToString(rw["gameid"]),
                                     download = Convert.ToString(rw["download"]),
                                     drawdate = Convert.ToString(rw["drawdate"]),
                                     submitter = Convert.ToString(rw["submitter"]),
                                     name = Convert.ToString(rw["name"]),
                                     platform = Convert.ToString(rw["platform"]),
                                     goal = Convert.ToString(rw["goal"]),
                                     specialrequirements = Convert.ToString(rw["specialrequirements"]),
                                     tournamentraceresult = Convert.ToString(rw["tournamentraceresult"]),
                                     notes = Convert.ToString(rw["notes"]),
                                     draws = Convert.ToString(rw["draws"]),
                                     pastebin = (Utilities.PasteBinPass(Convert.ToString(rw["pastebin"]))) ? Convert.ToString(rw["pastebin"]) : "pastebin not provided"
                                 }).ToList();

            return convertedList;
        }
Example #17
0
        /// <summary>
        /// Mains this instance.
        /// </summary>
        public static void Main()
        {
            Console.WriteLine("To get this working fix dbPath and db connection string if required!");
            // Get DB structure.
            string createClone = string.Empty;
            using (var northwindDbContext = new NorthwindEntities())
            {
                createClone = (northwindDbContext as IObjectContextAdapter).ObjectContext.CreateDatabaseScript();
            }

            string createDBScript = "" +
                "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'NorthwindTwin')"+
                "DROP DATABASE NorthwindTwin;" +
                "CREATE DATABASE NorthwindTwin ON PRIMARY " +
                "(NAME = NorthwindTwin, FILENAME = '" + dbPath + "NorthwindTwin.mdf', SIZE = 5MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
                "LOG ON (NAME = NorthwindTwinLog, FILENAME = '" + dbPath + "NorthwindTwin.ldf', SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 10%);";

            using (var db = new SqlConnection("Server=.; Database=master; Integrated Security=true"))
            {
                // Create empty DB
                db.Open();
                var initializeEmptyDB = new SqlCommand(createDBScript, db);
                initializeEmptyDB.ExecuteNonQuery();
                db.ChangeDatabase("NorthwindTwin");

                // Create twin structure.
                SqlCommand createTwin = new SqlCommand(createClone, db);
                createTwin.ExecuteNonQuery();
            }

            Console.WriteLine("Cloning Done!");
        }
        public override void Execute(SqlConnection dbConnection, string destDBName)
        {
            if(CanNotExecute) return;

            base.Execute(dbConnection, destDBName);

            if (dbConnection.State == ConnectionState.Closed) dbConnection.Open();

            string currentDirectory  =  Directory.GetCurrentDirectory();

            if (SourceStream == null) SourceStream = File.OpenRead(currentDirectory + "\\Scripts\\Tables.txt");

            using (SourceStream)
            {
                if (SourceStream == null) throw new Exception(Resources.FileNotFound);

                foreach (string commandText in FileHelper.LoadItemsLines(new StreamReader(SourceStream)))
                {
                    try
                    {
                        string tempCommand = commandText.Replace("[NewDataBase]", "[" + destDBName + "]");

                        Statement statement = DBHelper.ParseCommand(tempCommand);

                        SqlCommand command = dbConnection.CreateCommand();

                        command.CommandTimeout = AppConfig.CommandTimeOut;

                        string prevDBName = dbConnection.Database;

                        dbConnection.ChangeDatabase(destDBName);

                        command.CommandText = CreateCommandText(dbConnection, statement);

                        dbConnection.ChangeDatabase(prevDBName);

                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Errors.Add(ex);
                    }
                }
            }

            dbConnection.Close();
        }
        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                if (Session["user_id"] == null)
                {
                    Response.Redirect("../Default.aspx");
                }


                else
                {
                            SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
                    try
                    {

                        dbConnection.Open();
                         dbConnection.ChangeDatabase("nasa_SilentAuction_v1");
                        string name = Session["user_id"].ToString();
                        userid1.Text = name.ToString();

                        string SQLString = "SELECT * FROM users WHERE userID='" + name + "'";
                        SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
                       
                        SqlDataReader idRecords = checkIDTable.ExecuteReader();
                        if (idRecords.Read())
                        {
                            do
                            {
                                
                                
                                fname.Text = idRecords["firstName"].ToString();
                                lname.Text = idRecords["lastName"].ToString();
                                addressLine1.Text = idRecords["addressLine1"].ToString();
                                addressLine2.Text = idRecords["addressLine2"].ToString();
                                city.Text = idRecords["city"].ToString();
                                state.Text = idRecords["stateName"].ToString();
                                phoneNumber.Text = idRecords["phoneHome"].ToString();
                                networkProvider.SelectedValue = idRecords["phncarrier"].ToString();
                                email.Text = idRecords["email"].ToString();
                                Password1.Text = idRecords["password"].ToString();
                            }
                            while (idRecords.Read());
                        }
                        idRecords.Close();

                    }

                    catch (SqlException exception)
                    {
                        Response.Write("<p>Error code " + exception.Number
                            + ": " + exception.Message + "</p>");
                    }
                }
            }
        }
Example #20
0
 public void TestCleanup()
 {
     using (var cnn = new SqlConnection(SqlConnectionString))
     using (var cmd = new SqlCommand("EXEC sp_MSforeachtable @command1 = 'TRUNCATE TABLE ?'", cnn))
     {
         cnn.Open();
         cnn.ChangeDatabase(SqlDatabaseName);
         cmd.ExecuteNonQuery();
     }
 }
Example #21
0
 private static object PullSql(string conn, string db, string query, string error, SQLReturn type)
 {
     var result = new object();
     try
     {
         using (var c = new SqlConnection(conn))
         {
             c.Open();
             c.ChangeDatabase(db);
             SqlDataReader reader = new SqlCommand(query, c).ExecuteReader();
             switch (type)
             {
                 case SQLReturn.Bool:
                     result = false;
                     while (reader.Read())
                     {
                         if (reader != null)
                         {
                             result = true;
                             break;
                         }
                     }
                     break;
                 case SQLReturn.Item:
                     result = String.Empty;
                     while (reader.Read())
                     {
                         if (reader != null)
                         {
                             result = reader[0].ToString();
                             break;
                         }
                     }
                     break;
                 case SQLReturn.List:
                     var Results = new List<string>();
                     while (reader.Read())
                     {
                         Results.Add(reader[0].ToString());
                     }
                     result = Results;
                     break;
             }
         }
     }
     catch (SqlException e)
     {
         Messaging.ThrowException(error, e);
     }
     catch (Exception e)
     {
         Messaging.ThrowException(error, e);
     }
     return result;
 }
Example #22
0
 private static void RunSql(string sql, string dbName)
 {
     using (var con = new SqlConnection(connection_string))
     {
         con.Open();
         con.ChangeDatabase(dbName);
         using (var cmd = con.CreateCommand())
         {
             cmd.CommandText = sql;
             cmd.ExecuteNonQuery();
         }
     }
 }
        public static void ssb_get_certificate_blob(
            SqlString dbName,
            SqlString certName,
            out SqlBytes blob)
        {
            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
            scsb.ContextConnection = true;
            SqlConnection connection = new SqlConnection(scsb.ConnectionString);
            connection.Open();

            using (connection)
            {
                connection.ChangeDatabase(dbName.Value);

                string tempPath = Path.GetTempPath();
                string certFile = Path.Combine(
                    tempPath, Path.GetRandomFileName());

                try
                {
                    if (false == Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }

                    SqlCommand cmd = new SqlCommand(
                        String.Format(
                            @"BACKUP CERTIFICATE [{0}] TO FILE = '{1}';",
                            certName.Value.Replace("]", "]]"),
                            certFile),
                        connection);

                    cmd.ExecuteNonQuery();

                    blob = new SqlBytes(File.ReadAllBytes(certFile));
                }
                finally
                {
                    if (File.Exists(certFile))
                    {
                        try
                        {
                            File.Delete(certFile);
                        }
                        catch (IOException)
                        {
                        }
                    }
                }
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Request.QueryString["studentID"] == "")
         Response.Redirect("Default.aspx");
     else
     {
     SqlConnection dbConnection = new SqlConnection(
     "Data Source=.\\SQLEXPRESS;Integrated Security=true");
     string studentID = Request.QueryString["studentID"];
     schedule.Text = "<p>Student ID: " + Request.QueryString["studentID"] + "</p>";
     try
     {
     dbConnection.Open();
     dbConnection.ChangeDatabase("ConservationSchool");
     string classInfo = "SELECT * FROM registration WHERE studentID=" + studentID;
     SqlCommand studentSchedule = new SqlCommand(
         classInfo, dbConnection);
     SqlDataReader scheduleRecords =
         studentSchedule.ExecuteReader();
     if (scheduleRecords.Read())
     {
         schedule.Text += "<table width='100%' border='1'>";
         schedule.Text += "<tr><th>Class</th><th>Days</th><th>Time</th></tr>";
         do
         {
             schedule.Text += "<tr>";
             schedule.Text += "<td>"
                 + scheduleRecords["class"]
                 + "</td>";
             schedule.Text += "<td>"
                 + scheduleRecords["days"]
                 + "</td>";
             schedule.Text += "<td>"
                 + scheduleRecords["time"]
                 + "</td>";
             schedule.Text += "</tr>";
         } while (scheduleRecords.Read());
         schedule.Text += "</table>";
     }
     else
         schedule.Text += "<p>You have not registered for any classes! Click your browser's Back button to return to the previous page.</p>";
     scheduleRecords.Close();
     }
     catch (SqlException exception)
     {
     Response.Write("<p>Error code " + exception.Number
         + ": " + exception.Message + "</p>");
     }
     dbConnection.Close();
     }
 }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                Page.Validate();
                if (Page.IsValid)
                {
                    // Reading from Web.Config
                    //string connectionString = ConfigurationManager.ConnectionStrings["ConservationSchoolConnectionString"].ConnectionString;
                    //SqlConnection dbConnection = new SqlConnection(connectionString);

                    SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
                    //                SqlConnection dbConnection = new SqlConnection("Data Source=BLLIM-LT;Integrated Security=true");
                    //                SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
                    try
                    {
                        dbConnection.Open();
                        dbConnection.ChangeDatabase("itk485nnrs");
                        //string SQLString1 = "INSERT INTO userLogin VALUES( '" + fnameId.Text + "','" + lnameId.Text + "')";
                        string SQLString1 = "INSERT INTO anonymousbiddertable  VALUES( '" + fnameId.Text + "','" + lnameId.Text + "','" + cellId.Text + "')";
                        SqlCommand checkIDTable1 = new SqlCommand(SQLString1, dbConnection);

                        checkIDTable1.ExecuteNonQuery();

                        Session["firstname"] = fnameId.Text;
                        Session["lastname"] = lnameId.Text;
                        Session["cellPhoneNo"] = cellId.Text;
                        Response.Redirect("bidOnline.aspx");

                        //SqlDataReader idRecords = checkIDTable.ExecuteReader();
                        //if (idRecords.Read())
                        //{
                        //    Response.Write("Hello, " + username.Text);
                        //    idRecords.Close();
                        //}
                        //else
                        //{
                        //    Response.Write("**Invalid Match **");
                        //    //Label1.Text = "<p>**Invalid Match **</p>";
                        //    idRecords.Close();
                        //}
                    }
                    catch (SqlException exception)
                    {
                        Response.Write("<p>Error code " + exception.Number
                            + ": " + exception.Message + "</p>");
                    }
                }

            }
        }
Example #26
0
 protected void Page_Load(object sender, EventArgs e)
 {
     SqlConnection dbConnection = new SqlConnection(
     "Data Source=.\\SQLEXPRESS;Integrated Security=true");
     try
     {
         dbConnection.Open();
         dbConnection.ChangeDatabase("forecast");
         string retString = "SELECT * FROM outlook ORDER BY city";
         SqlCommand outlookCommand =
             new SqlCommand(retString, dbConnection);
         SqlDataReader outlookRecords
             = outlookCommand.ExecuteReader();
         if (outlookRecords.Read())
         {
             Response.Write("<table width='100%' border='1'>");
             Response.Write("<tr><th>City</th><th>State</th><th>Day</th><th>High</th><th>Low</th><th>Conditions</th></tr>");
             do
             {
                 Response.Write("<tr>");
                 Response.Write("<td>" + outlookRecords["city"]
                     + "</td>");
                 Response.Write("<td>" + outlookRecords["state"]
                     + "</td>");
                 Response.Write("<td>" + outlookRecords["day"]
                     + "</td>");
                 Response.Write("<td>" + outlookRecords["high"]
                     + "</td>");
                 Response.Write("<td>" + outlookRecords["low"]
                     + "</td>");
                 Response.Write("<td>"
                     + outlookRecords["conditions"] + "</td>");
                 Response.Write("</tr>");
             } while (outlookRecords.Read());
             Response.Write("</table>");
         }
         else
             Response.Write("<p>Your query returned no results.</p>");
         outlookRecords.Close();
     }
     catch (SqlException exception)
     {
         Response.Write("<p>Error code " + exception.Number
             + ": " + exception.Message + "</p>");
     }
     dbConnection.Close();
     addForecast("INSERT INTO outlook VALUES('Tucson', 'AZ', 'Tuesday', 102, 72, 'Partly cloudy')");
     addForecast("INSERT INTO outlook VALUES('Williamsburg', 'VA', 'Wednesday', 90, 71, 'Mostly clear')");
 }
Example #27
0
 public static SqlConnection loadDB()
 {
     SqlConnection dbConnection = null;
     try
     {
         dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true");
         dbConnection.Open();
         dbConnection.ChangeDatabase("it368_Auction_Project");
     }
     catch (SqlException exception)
     {
         Console.Write("<p>Error code " + exception.Number
             + ": " + exception.Message + "</p>");
     }
     return dbConnection;
 }
Example #28
0
 public bool createDatabase(string n)
 {
     using (con = __initConnection(false)) {
         con.Open();
         con.ChangeDatabase("master");
         using (com = new SqlCommand("CREATE DATABASE " + n, con)) { // cannot parameterize without getting a syntax error => need to find where sanitization happens internally
             try {
                 com.ExecuteNonQuery();
                 return true;
             } catch (Exception ex) {
                 HttpContext.Current.Response.Write(ex.ToString());
                 return false;
             }
         }
     }
 }
        private void CreateConnectionAndDB()
        {
            try {
                m_conn = new SqlConnection(textBoxServer.Text);
                m_conn.Open();
                SqlCommand exists = m_conn.CreateCommand();
                string dbname = textBoxDBName.Text.Replace(" ", "").Trim();
                exists.CommandText = "if not exists(select * from sys.databases where name = '" + dbname + "') create database " + dbname + ";";

                exists.ExecuteNonQuery();
                m_conn.ChangeDatabase(dbname);
            }
            catch (Exception x) {
                m_conn = null;
                MessageBox.Show(x.Message);
            }
        }
Example #30
0
        public override void InvokeHandler(CommandSetState state)
        {
            var diagram = state.CurrentDocView.CurrentDiagram;
            var modelRoot = diagram.Store.ElementDirectory.FindElements<ModelRoot>().Single();
            var connectionString = modelRoot.ConnectionString;

            var dlg = new GenerateSQLForm();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var sqlGenerator = new DbSchemaGenerator(diagram)
                {
                    CleanUpDbSchema = dlg.CleanupDbSchema,
                    UseNavigationPropertyNameForFKeys = dlg.UseNavigationPropertyNameForFKeys,
                };
                var sb = sqlGenerator.GenerateScripts();
                System.IO.File.WriteAllText(dlg.Filename, sb.ToString());

                if (dlg.OverwriteDatabase)
                {
                    //Creating a connection to the given database
                    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
                    {
                        var originalDatabase = sqlConnection.Database;
                        sqlConnection.Open();

                        //Switching to master database
                        sqlConnection.ChangeDatabase("master");
                        ServerConnection svrConnection = new ServerConnection(sqlConnection);

                        //Recreating database and executing the query file
                        DropAndRecreateDatabase(originalDatabase, svrConnection);
                        svrConnection.ExecuteNonQuery(System.IO.File.ReadAllText(dlg.Filename));
                    }

                    ModelerTransaction.Enter(() =>
                        {

                            //Importing the new schema from database
                            var sync = new Utilities.DbSchemaImporter(diagram);
                            sync.FullDatabaseReload = true;
                            sync.ImportModels();
                        });
                }
                System.Windows.Forms.MessageBox.Show("Sql script generation completed.");
            }
        }