Connection String with WCF and deployment - c#

I have an WCF service in Visual Studio. The WCF Service must simply write to a database name Market.mdf. What I have done to write to a database is:
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|/Market.mdf';Integrated Security=True";
using(SqlConnection connection =new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Table (Value) VALUES (#Value);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Value", "Jonathan");
connection.Open();
cmd.ExecuteNonQuery();
}
This does not allow me to write to the database when I attempt via localhost:58632/UserManagement.svc/write. When I use this I get.
I don't know how to fix this as I am new to C# and WCF. How would the connection string differ if I was going to deploy on to IIS?

You have an unescaped sequence in your connection string
string connectionString = #"Data Source=(LocalDB)\v11.0;
AttachDbFilename='|DataDirectory|/Market.mdf';
Integrated Security=True";
Add the character # before the connectionstring to get a verbatim literal string or double the backslashes
string connectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename='|DataDirectory|/Market.mdf';Integrated Security=True";

Related

Recycling Connection String In Windows Forms C#

I'm trying to reuse a connection string created from a DataGridView. I can't seem to translate the value in the Settings.settings file to a usable connection string. Any ideas of what the Connection_String SHOULD look like?
Error:
Format of the initialization string does not conform to specification starting at index 0.
Code:
// This fills the gridview
this.loanacctTableAdapter.FillBy(this.innovate_Loan_ServicingDataSet.loanacct, ((decimal)(System.Convert.ChangeType(acctrefnoToolStripTextBox.Text, typeof(decimal)))));
// This tries to use the same connection
Connection_String = SpecialSetting.ConnectionString.ToString();
Command = "SELECT acctrefno FROM loanacct WHERE acctrefno = " + AcctrefnoToolStripTextBox.Text + "";
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
textBox1.Text = DR1.GetValue(0).ToString();
textBox1.ReadOnly = true;
}
Conn.Close();
Settings.Designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=ILSVUPGRADE01;Initial Catalog=Innovate_Loan_Servicing;Integrated Secu" +
"rity=True")]
public string Innovate_Loan_ServicingConnectionString {
get {
return ((string)(this["Innovate_Loan_ServicingConnectionString"]));
ConnectionString is simply a String. I suggest to use the SqlConnectionStringBuilder Class. It makes it much easier to create a valid connection string.
You can get the full ConnectionString then with .ToString()
The solution ended up being the difference between Windows Forms and ASP.NET. I needed to find the configuration in the Settings.settings file and drill down. Windows forms stores the connection string as "Properties.Settings.Default. name of connection here.ToString(); The command and connection can then be set simply. ASP.NET sets the connection string under ConfigurationSettings.AppSettings("myConnectionString").
My code ended up looking like this.
string Connection_String = Properties.Settings.Default.Innovate_Loan_ServicingConnectionString.ToString();
string Command = "SELECT acctrefno, loan_number, [shortname], [loan_group_no] FROM loanacct WHERE acctrefno = " + acctrefnoToolStripTextBox.Text + "";
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
etc.

ConnectString didn't work in C#

public static DataSet ParseDatabaseData(string sheetName)
{
string connectionString = "Provider=System.Data.SqlClient;Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;";
SqlConnection conn = new SqlConnection(connectionString);
string strSQL = "SELECT * FROM [" + sheetName + "$]";
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
conn.Close();
return dataset;
}
The error show that 'provider' keyword is wrong.
Please help me to correct how to connect with Database through connection string?
You do not need to specify the Provider in the Connection String.
Try it like this:
public static DataSet ParseDatabaseData(string sheetName)
{
string connectionString = "Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;";
Instead of mentioning the connection string in the individual file itself, you can place the connection string in the web.config or app.config and use the config where ever required.
Sample for web.config place the connection string under the <configuration>, there you can provide the provider name:
<configuration>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and inside the file
public static DataSet ParseDatabaseData(string sheetName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
Note: add using System.Configuration; for the ConfigurationManager.

How to save a string in SQL Server as SqlDateType by using Visual Studio 2013?

How to save a string in SQL Server as SqlDateType by using Visual Studio 2013? My string which I want to save is 1996-25-04. I am working with C#.
I have tried this as far
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass");
con.Open();
string sql = " insert into Staff_Management values( '" + TM_Add_BirthDate.Value.ToString() + "' ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
You should NEVER EVER concatenate together your SQL statements like this! This opens all doors to SQL injection attacks - and causes trouble with string and date values.
Try this code instead - using a parametrized query:
// define the query - and I'd recommend to always define the name of the columns you're inserting into
string query = "INSERT INTO dbo.Staff_Management(name-of-column-here) VALUES (#Birthdate);";
// define connection and command
// also: do **NOT** use the `sa` user for your production code!
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// add the parameter - and use the proper datatype - don't convert all dates to strings all the time!
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = TM_Add_Birthdate.Value;
// open connection, execute INSERT query, close connection - done
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
}

"Illegal characters in path" error when connecting to SQL Server

I'm trying to connect to database and I get the following error:
Illegal characters in path.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlDataAdapter adapt = new SqlDataAdapter();
adapt.InsertCommand = new SqlCommand(" INSERT INTO tblEmployee VALUES (#employeeNumber, #employeePrivateName, #employeeFamilyName ,#city, #street, #houseNo, #phoneNumber, #birthDate, #startWorkingDate)", Con);
adapt.InsertCommand.Parameters.Add("#employeeNumber", SqlDbType.Char).Value = textBox1.Text;
adapt.InsertCommand.Parameters.Add("#employeePrivateName", SqlDbType.VarChar).Value = textBox2.Text;
adapt.InsertCommand.Parameters.Add("#employeeFamilyName", SqlDbType.VarChar).Value = textBox3.Text;
adapt.InsertCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox4.Text;
adapt.InsertCommand.Parameters.Add("#street", SqlDbType.VarChar).Value = textBox5.Text;
adapt.InsertCommand.Parameters.Add("#houseNo", SqlDbType.Int).Value = textBox6.Text;
adapt.InsertCommand.Parameters.Add("#phoneNumber", SqlDbType.Char).Value = textBox7.Text;
adapt.InsertCommand.Parameters.Add("#birthDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
adapt.InsertCommand.Parameters.Add("#startWorkingDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
Con.Open();
adapt.InsertCommand.ExecuteNonQuery();
Con.Close();
}
How to do I connect to the database so the I can insert into it?
You'll need to escape \targil3.mdf
Use \\ or put an # before the assignment of the string, for instance.
SqlConnection Con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
This is because you have got characters in your connection string which need to be escaped. To overcome this issue you have got couple of options.
Either to explicitly escape those characters by using
\\
OR
use the # sign before assignment.
PS: Though i would recommend you to specify your connection string in app.config and read it like this
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["yourConnectionString"].ToString();
and you should consider the user of
using (SqlConnection sqlConn = new SqlConnection(conString ))
{
try
{
//your sql statements here
}
catch (InvalidOperationException)
{
}
catch (SqlException)
{
}
catch (ArgumentException)
{
}
}
You won't face any errors specified above.

Backup a database

I want to backup my DB but I got a error:
ConnectionStrings cannot be used like a method
How can I resolve this?
string strCon = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
string sSQL = "BACKUP DATABASE Database TO DISK = 'D:\\Database.bak';";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.Connectionstrings(strCon).ConnectionString))
{
SqlCommand command = new SqlCommand(sSQL, connection);
connection.Open();
command.ExecuteNonQuery();
}
You should directly use that variable as SqlConnection requires a string object containing a connection string and you are storing it in a string object itself.
So it would be simply like this:
using (SqlConnection connection = new SqlConnection(strCon))
{
SqlCommand command = new SqlCommand(sSQL, connection);
connection.Open();
command.ExecuteNonQuery();
}
Recommended: (to store it in Web.config)
<connectionStrings>
<add name="job" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Then access it like this: (using System.Configuration;)
ConfigurationManager.ConnectionStrings["job"].ConnectionString
ConnectionStrings is a collection. It must be used like:
ConfigurationManager.Connectionstrings[0].ConnectionString

Categories