i am developing window application and i want the user of the app can change the connection string so i create aform to save connection string to setting and able to retrieve it but the problem is how to use this setting
private void button1_Click(object sender, EventArgs e)
{
var serv = Properties.Settings.Default.server;
var db = Properties.Settings.Default.database;
var userid = Properties.Settings.Default.userid;
var pass = Properties.Settings.Default.password;
SqlConnection conn = new SqlConnection("Data Source=serv;Initial Catalog=db;User ID=userid password=pass");
SqlDataAdapter sda = new SqlDataAdapter("SELECT count(*) FROM users WHERE username='" + txtUsername.Text + "' and password='" + txtPassword.Text + "'", conn);
}
Put your connection string in the App.config/Web.config, it will make it that much easier to alter later on if need be.
Also remember to always make use of the using statement when working with SqlConnection in general.
For example:
In the App.config/Web.config add the following:
<appSettings>
<add key="myConnectionString" value="Data Source=serv;Initial Catalog=db;User ID=userid password=pass" />
</appSettings>
Then you can easily access it anywhere in your project:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["myConnectionString"]))
{
using(SqlCommand sqlCommandConn = new SqlCommand(InsertStatement))
{
sqlCommandConn.Connection = conn;
//TODO: Open connection, Execute queries...
}
}
Note
You can alter these settings via code as well if you wish:
private void UpdateConfig(string key, string value)
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configFile.AppSettings.Settings[key].Value = value;
configFile.Save();
}
Try
SqlConnection conn = new SqlConnection("Data Source=" + serv.ToString() + ";Initial Catalog=" + db.ToString() + ";User ID=" + userid.ToString() + ";password= " + pass.ToString());
As you can see from your code snippet, the connection string value is just a string that you are passing to the SqlConnection constructor, so for your case you could pull the value at runtime and load that value dynamically.
While it is possible to manipulate the app.config file which does hold connection string values, I typically prefer to manipulate secondary files. A better option could be to use a secondary file in XML for example and preform CRUD like operations on it as your users change their connection strings. At runtime, you can pull their specific connection string value and load it into the constructor as your doing above. A sample XML structure could be as follows:
<connections>
<connection userID="12345">Data Source=servA;Initial Catalog=db123;User ID=jSmith password=pass1</connection>
<connection userID="43532">Data Source=servB;Initial Catalog=db456;User ID=rJSmith password=abc321</connection>
</connections>
If all that is changing is the user, pass, catalog, and datasource values and the remainder of the connection string is static, you could just store these individual values as opposed to the entire connection string and then inject those dynamically to build the connection string at runtime.
Reading the XML is not difficult when using something like LINQ to XML which would allow you to query the XML file and get a specific connection string by the userID field. A good reference for LINQ to XML is at the following: http://msdn.microsoft.com/en-us/library/bb387098.aspx
Related
I am trying to replicate a defunct homegrown program that I don't have access to the source code. Basically I need to read in a SQL file (here denoted as querySqlAddresses[i]), execute it and dump the result into a specific sheet in a file that I have open.
I'm finding a lot of dead end things, but I think there may be promise in this, I am just not sure HOW to drop the "results" or even what the "results" variable is so I can target it. Does this even make sense?
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo(querySqlAddresses[i]);
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
I actually found another way of doing it using OleDB connections and passing the User Name, Password and Table space into the connection string.
string connectionString = "Provider=OraOLEDB.Oracle;Data Source=" + tableSpace + ";User Id=" + userName + ";Password=" + password + ";";
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection(connectionString);
cnn.Open();
System.Data.OleDb.OleDbDataAdapter Dadpt = new System.Data.OleDb.OleDbDataAdapter(readText, cnn);
DataSet ds = new DataSet();
Dadpt.Fill(ds);
cnn.Close();
I have created a WPF desktop application before and I was able to write up the code to save data from a textbox to a table I created in sql server 2012. I tried to create a WPF Web browser application and the same code was not working to save my data to my sql database. I am now trying to create another WPF desktop application and the same code that worked the last time is not working anymore. Please look at my code and help.
private void savebuyers_Click(object sender, RoutedEventArgs e)
{
string connectionstring = null;
connectionstring = "Data Source=FRANCIS;Initial Catalog=Pam Golding;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionstring);
try
{
string query;
query = "insert into buyers (name,number,email) values ('" + namebuyers.Text + "'," + Convert.ToInt32(numberbuyers) + ",'" + emailbuyers.Text + "')";
SqlCommand command = new SqlCommand(query, con);
message1.Text = "Data Saved Successfully!";
con.Open();
command.ExecuteNonQuery();
con.Close();
}
catch
{
message1.Text = "Error While Saving Data!";
}
}
You have missed the Text property of numberbuyers. So it is unable to cast object of type TextBox to type System.IConvertible.
You can fix it like this:
Convert.ToInt32(numberbuyers.Text)
Also you should always use parameterized queries to avoid Sql Injection.
I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. I've tried it but I am not able to do it in correct manner.
Let me show you how I've coded, the code I did in frmViewformList savechanges button is :
private void btnSaveChanges_Click(object sender, EventArgs e)
{
string sql;
string UserName;
UserName = txtUserName.Text; // saving data loaded on run time to UserName
sql = "";
sql += "UPDATE UserLogin";
sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
sql += "WHERE Name= " + //how to access data which was in text box right after loading + ""; //
}
I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query...
This question is a bit confusing, I know. Let me explain; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well.
I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused.
You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation.
It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier.
Here is an example you can reference:
public void DoWork()
{
// Build Query Use #Name Parameters instead of direct values to prevent SQL Injection
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE UserLogin");
sql.Append("SET Name = #UpdatedName");
sql.Append("WHERE Name = #Name");
// Create parameters with the value you want to pass to SQL
SqlParameter name = new SqlParameter("#Name", "whatEverOldNameWas");
SqlParameter updatedName = new SqlParameter("#UpdatedName", txtUserName.Text);
Update(sql.ToString(), new [] { name, updatedName });
}
private static readonly string connectionString = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
public static int Update(string sql, SqlParameter[] parameters)
{
try
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
foreach (var parameter in parameters)
{
if (parameter != null)
command.Parameters.Add(parameter);
}
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}
}
You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " +, you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +...
This is probably best done using
string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);
Then you will execute your query by using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database.
At the top of your .cs file you should have.
using System.Data.SqlClient; // for sql server for other data bases you should use OleClient instead.
And inside your button click event you could put the following.
// to know how to get the right connection string please check this site: http://www.connectionstrings.com
string connString = "database connection string here";
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
//insert text into db
string sql_insert = "INSERT INTO ....."; // Use parameters here.
SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
int rowsAffected = cmd_insert.ExecuteNonQuery();
}
Hopefully this is enough to get you started.
I would like to apply my connection string to the whole winform. If I do this in this case - it will apply to the whole win form, but then i cannot use textbox to enter details:
public partial class Form1 : Form
{
SqlConnection myConnection = new SqlConnection("user id=userName;" +
"password=userPass;" +
"server=.;" +
"Trusted_Connection=yes;" +
"database=dbName; " +
"MultipleActiveResultSets=True;" +
"connection timeout=30");
public Form1()
{
InitializeComponent();
}
And if I will use with textbox I will need to enter the connection string to each method.
Is there anyway to get around it?
Another approach you can take is create the SqlConnection when it is needed and then store in a private variable if you want to save the reference.
So when you need the connection have:
if( myConnection == null )
{
string connectionString = string.Format( "user id={0}, password={1}", userIdTextBox.Text, passwordTextBox.Text );
myConnection = new SqlConnection( connectionString );
}
You will extend the "string.Format" to include the other connection properties.
If you require the "myConnection" in multiple places then place the above code into a method named "GetConnection", have it return an SqlConnection instance using the contents of the textboxes and call this method each time a connection is required.
EDIT:
Personally I would have a method that builds the connection string, like described above, and create a new SqlConnection instance whenever it is needed. This will attempt to open a new connection each time, but will make use of connection pooling built into the ADO.NET library.
using( SqlConnection connection = new SqlConnection( this.GetConnectionString() ) )
{
// Open Connection
// Access the database
// Close the connection <- Manual closing MAY not be needed as it might be done in Dispose ...check MSDN for clarification.
}
You can create a static class to store the connection string in there. It is not a good practice to create always the connection string.
I have to populate checkboxes with data coming from database, but no checkboxes are showing on my page. Please let me know the correct way to do that. In C#, the page_load method I've written is this:
public partial class dbTest1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string Server = "al2222";
string Username = "hshshshsh";
string Password = "sjjssjs";
string Database = "database1";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
string query = "Select * from Customer_Order where orderNumber = 17";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (!IsPostBack)
{
Interests.DataSource = dr;
Interests.DataTextField = "OptionName";
Interests.DataValueField = "OptionName";
Interests.DataBind();
}
}
conn.Close();
conn.Dispose();
}
}
}
}
And in the .aspx, I have this:
<asp:CheckBoxList ID="Interests" runat="server"></asp:CheckBoxList>
Please tell me the correct way to accomplish this.
Although your question is already answered (via the connection string comments), I thought I'd chime in with a possible way to rewrite this. I'd started this off as a comment, but it got a bit long and unwieldy. Note that this doesn't directly answer your question, but it is something to consider for code cleanliness and a possible (likely very mild) performance boost on postbacks.
protected void Page_Load(object sender, EventArgs e)
{
// If we're in postback, let's not poll the database.
if (Page.IsPostback)
return; // Change this if you do need some postback processing here.
// I assume that in the real world you pull this info from web.config
string Server = "al2222";
string Username = "hshshshsh";
string Password = "sjjssjs";
string Database = "database1";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
string query = "Select * from Customer_Order where orderNumber = 17";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
// Going to assume that you're only getting 1 record
// due to apparent key (orderNumber = 17) in query?
// You can also consider "if (dr.Read())", but fundamentally
// they will do the same thing.
while (dr.Read())
{
Interests.DataSource = dr;
Interests.DataTextField = "OptionName";
Interests.DataValueField = "OptionName";
Interests.DataBind();
}
// I've excised the calls to .Close() and .Dispose(),
// as the using block covers them for you.
}
}
}
Why would we go this route?
In your original code, you were polling the database (and potentially looping, if my assumption about that being a single-record query was wrong) every page load, whether or not you were in postback. You weren't checking postback until you were inside the loop, where the damage was mostly already done. In the code I've listed, you short-circuit out of Page_Load() altogether if you're in postback. You can, of course, change that to an if/else and bracket the groups if you need some load-event processing on postbacks as well. This also simplified your in-loop code.
Your using blocks covered the disposal/closure of the connection for you. Thus, you do not need that additional code.
As OrbMan stated in the comments, hopefully in your actual code you're retrieving all the connection string info from your web.config file instead of hard-coding it, correct?
Final final unrelated note: This is a lot of data access code that newer versions of the .NET Framework simplify greatly with tools such as Entity Framework and LINQ-to-SQL. There are also 3rd-party data access layer tools (such as SubSonic and ActiveRecord) that will simplify this. Using tools such as those will greatly reduce the amount of code you're writing here -- and I'm guessing you're using quite a bit of similar code throughout your app as well, so those tools will provide you the developer with quite the productivity boost. (And much simpler down-the-road maintenance.)
Just food for thought.