Code won't work without a relative file path - c#

This is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace SDD_Single_Project___Michael_Merjane
{
public partial class NewUser : Form
{
private OleDbConnection connection = new OleDbConnection(); //setting up a private connection
public NewUser()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\schoolwork\Year 11\SDD\3 SINGLE TASK\SDD Single Project - Michael Merjane\SDD Single Project - Michael Merjane\bin\Persondata.accdb; //PROBLEM IS HERE
Persist Security Info=False;"; // there is no security for finding the location, this is not very safe but for the circumstances it works. In the line above, it is finding the location of the database. This could change due to computer and cause the whole program to not run
}
private void btnBack_Click(object sender, EventArgs e) //all of these mean when button is clicked
{
this.Hide(); //hides this page
MainScreen frm = new MainScreen(); //finds the next screen (the main screen)
frm.Show(); //shows it
}
private void btnSubmit_Click(object sender, EventArgs e)
{
try {
connection.Open(); // opens the connection
OleDbCommand command = new OleDbCommand(); //names command as a new oledbcommand for further use
command.Connection = connection;
command.CommandText = "insert into Persondata ( FirstName,LastName,Address,Suburb,Email,Mobile,Gender,Age) values ( '" + txtFirst.Text + "' , '" + txtLast.Text + "' , '" + txtAddress.Text + "' , '" + txtSuburb.Text + "' , '" + txtEmail.Text + "' , '" + txtMobile.Text + "' , '" + dropGender.Text + "' , '" + dropAge.Text + "') ";
// finds where its going to, finds the columns it is going to fill, finds the text boxes that is going to fill them
command.ExecuteNonQuery(); //execute the save
MessageBox.Show("Data Saved"); //pretty much shows a box saying everything worked
connection.Close(); // closes the connection
}
catch (Exception ex) //if something has gone wrong a catch will occur
{
MessageBox.Show("Error " + ex); //show the error
} //if there is a error message box will appear informing it
}
}
}
This is code for an assignment I must give in, the problem is I won't be able to hand it because then the absolute path won't find the file. I need a way to use a relative file path that can change due to a change in location. At the moment, the path (as long is it is) goes to the bin folder within the programs files. So if there was a way to change it so it somehow automatically looks in its own program files to the bin or anywhere else in its own program files that would be great.

Put whatever file you want into the folder your current ptoject is. Then
Directory.GetCurrentDirectory()
will give the current folder you are working on. It will give you the release folder of your project. Store it as a string and use it where ever needed.

try :
var currDir = System.Environment.CurrentDirectory;
then concatenate the path from there...

Sure.
That is pretty basic thing - I'd suggest putting database file in DB folder inside bin - or left inside bin as it is.
Then you need to determine location of your binary folder - there are several ways, while two below are most common:
Environment.CurrentDirectory - will work until you are not changing it during run-time (elsewhere)
Assembly.GetEntryAssembly().Location - which is full path to the executable that started current process
I'd suggest then looking onto System.IO.Path class - first to strip only path from Location and then to combine it back but this time with database file-name string.
While this is you assignment I'm going to leave you here to study this class by yourself - this is pretty interesting one :P
http://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx

Related

"database is locked" C# & SQLite

I keep getting this exception over and over. I've tried separating my query into two separate queries, that didn't work. I've checked to make sure the db connection is closed elsewhere before it's opened during this method, it's definitely closed before the function is called and opened before any queries.
Below iss the code for the function. I've set breakpoints and the query itself is fine. The code is the exact same that I used previously for updating a PIN function, with just the query string changed, so I don't know why it's causing issues:
Code:
public void transferMoney(string senderIban, decimal senderBalance, string receiverIban, decimal transferAmount,string messageOptional)
{
//myBankAccount.AccountPin = updatedPin;
DataTable dtUser = new DataTable();
sqlconnConnection.Open();
string strQuery2 = #"UPDATE Accounts SET Balance = Balance + " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + receiverIban + "';"
+ "UPDATE Accounts SET Balance = Balance - " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + senderIban + "';";
// example of a Paramaterised SQL statement.
SQLiteCommand sqlcomCommand2 = new SQLiteCommand(strQuery2, sqlconnConnection);
SQLiteDataAdapter sqldatadptAdapter = new SQLiteDataAdapter(sqlcomCommand2); // local SQL data Adaptor
try
{
// sqldatadptAdapter.Fill(dtUser);
sqlcomCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
// Exception will the "thrown" when there was a problem
throw new Exception($"UPDATE WAS unsuccessful:\n{ex.Message}");
}
finally
{
sqlconnConnection.Close();
}
Maybe you have a DB browser opened? Or you have accessed the DB some other way. This error only occurs when DB is modified or used elsewhere. If you can't find it, I'd suggest restarting PC just in case there something hidden :)
P.S. Posting this as answer as I cannot comment under the question for technical reasons :)

Cannot write to a Microsoft Access file using SQL (OLEDB) C#

I understand that this may be considered a duplicate question, but I am at an impasse and i do not know what it is I am doing wrong, I need help. The duplicate question said to use OLEDB in order to write to the Microsoft Access file, where as before I was using the SQL connection to accomplish my task. As far as i can tell there are no syntax, logic, or runtime errors and Visual Studios doesnt have an issue either.
When i run the code and go to add a new entry to the Microsoft Access Database Table, it says it worked, but when I go and look at the file there is NOTHING there. Someone please help me, I have goe through all the links, all the web pages, all the search engines, and I dont know what is wrong. I would love to learn what is wrong and how to fix it so I wont ever have to ask for help again.
Currently I am a college student and I am working on a team assignment. Our task, is to create a window that will take input from a user and then add it as a entry into an Microsoft Access File as if it were a SQL database.
The issue we are having is that we are trying to add the new entry to a local Microsoft Access file under the table named Artist. I have connected to an actual SQL server before and no one else in my group has, even worse no one has done this with using a Microsoft Access file on our PC either.
I have added the Database (Microsoft Access File) in Visual Studios using the Database Configuration Wizard. At first I was using straight SQL do to this and then i was told i need to use OLEDB in order to do this. SO I have implemented in the code and for some reason I still cannot get it to work. If anyone can give me a hand and tell me what it is I am doing wrong, I would greatly appreciate it.
Details that I believe are important for anyone to help me:
The name of the table I am attempting to write a new entry to: Artist
Name of the Microsoft Access File: Kays.accdb
Location of the Microsoft Access file: C:\KayDB\Kays.accdb (local machine)
Once again I would greatly appreciate any help that anyone can give me. I really am curious as to why the code is not working, please help me understand.
My code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Kay
{
public partial class Kay_Green : Form
{
string Username,Fname, Mname, Lname, streetaddress, city, phonenumber, emailaddress, zipcode, taxIDnummber, state;
string[,] SQLTable = new string[0, 10];
public Kay_Green()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{//Save Button
/*Upon clicking the save button, gather all info and save it into an temp array.
Then send it to the SQL database.*/
/*The order of the data in the array will be the same order in the SQL table.*/
Fname = tbFirstName.Text;
Mname = tbMiddleInitial.Text;
Lname = tbLastName.Text;
streetaddress = tbStreet.Text;
city = tbCity.Text;
state = cbState.Text;
phonenumber = tbPhoneNumber.Text;
emailaddress = tbEmailAddress.Text;
zipcode = tbZipCode.Text;
taxIDnummber = tbTaxID.Text;
Username = tbUserName.Text;
/*SQLTable[0,0] = taxIDnummber;
SQLTable[0,1] = Fname;
SQLTable[0,2] = Mname;
SQLTable[0,3] = Lname;
SQLTable[0,4] = streetaddress;
SQLTable[0,5] = city;
SQLTable[0,6] = state;
SQLTable[0,7] = zipcode;
SQLTable[0,8] = phonenumber;
SQLTable[0,9] = emailaddress;*/
/*Below is the details for the SQL connection*/
string connectstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\KayDB\\Kays.accdb";
OleDbConnection connection=new OleDbConnection(connectstring);
OleDbCommand command;
OleDbDataAdapter adapter;
DataTable dt = new DataTable();
string sql ="Insert into ARTIST values ('" + taxIDnummber + "','"
+ emailaddress + "','" + Fname + "','" + Mname + "','"
+ Lname + "','" + phonenumber+"','"+ Username + "','"
+ streetaddress + "','" + city + "','" +state+ "','"
+ zipcode + "')";
try
{
connection.Open();
command = new OleDbCommand(sql, connection);
MessageBox.Show("Connection Open And data added to table! ");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " + ex.StackTrace.ToString());
}
/*Above is the details for the SQL connection*/
}
private void btnCancel_Click(object sender, EventArgs e)
{//Cancel Button
tbCity.Clear();
tbEmailAddress.Clear();
tbFirstName.Clear();
tbLastName.Clear();
tbMiddleInitial.Clear();
tbPhoneNumber.Clear();
tbStreet.Clear();
tbTaxID.Clear();
tbZipCode.Clear();
tbUserName.Clear();
Close();//Go back to switchboard from here
}
private void btnClear_Click(object sender, EventArgs e)
{//Clear button
tbCity.Clear();
tbEmailAddress.Clear();
tbFirstName.Clear();
tbLastName.Clear();
tbMiddleInitial.Clear();
tbPhoneNumber.Clear();
tbStreet.Clear();
tbTaxID.Clear();
tbZipCode.Clear();
tbUserName.Clear();
}
}
}
This code
command = new OleDbCommand(sql, connection);
sets up a command but does not run it
you need to run this afterwards:
command.ExecuteNonQuery();
This has nothing to do with connection strings

C#: annoying mistake during making back up of sql database

I am trying to make my application which have aim to make backup of database on disk and also send it through ftp or mail.
So I made a research and finally I wrote project of Windows service and another project in console which is making a backup of database. Both are working well and both are written in the same Visual Studio but when I am trying to put code of making backups in Windows service it doesn't work. I can't understand why. I tried put code instead of example (which is creating a file and writing one line there and this part is working well) and I even tried to make another method to do it and then call this method.
Windows service is completely the same as here and in the SpadesAdminService class instead of
System.Diagnostics.EventLog.WriteEntry("SpadesAdminSvc",
ServiceName + "::Execute()");
I made this code (is working well - making an empty file on my disk every 5 seconds, should be written "text to file" but files are appearing !):
using (FileStream fs = File.OpenWrite("C:\\place\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
{
Byte[] napis = new UTF8Encoding(true).GetBytes("text to files"));
fs.Write(napis, 0, napis.Length);
}
My class of making back up (alone is also working well):
namespace makeBackUpConsole
{
class Program
{
static void Main(string[] args)
{
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
}
}
}
I am copying this class instead of my code to making txt files and Windows Service is not working. Here is a code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace toni.exampleService.Services
{
public class exampleAdminService : exampleServiceBase
{
public exampleAdminService()
{
this.ServiceName = "exampleAdminSvc";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
protected override int Execute()
{
//using (FileStream fs = File.OpenWrite("C:\\development\\toni\\dd\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
//{
// Byte[] napis = new UTF8Encoding(true).GetBytes("DzieƄ i godzina: " + DateTime.Now.ToString("ddMMyyyy_HHmmss"));
// fs.Write(napis, 0, napis.Length);
//}
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
return 0;
}
}
}
Of course all libraries as well linked.
Looking for any advice, please help me.
Thank you in advance and have a nice day.
edit:
Hey, problem solved.
I created a database account (not Windows account) in sql management studio and I putted this account User Id and Password directly into my code in C# in Windows Service.
Anyway maybe somebody will use my code :)
Thanks for reply.
Have you checked that a Windows Service has permissions to write a file in the location you are specifying. Services don't necessarily run as a user, so don't assume that where you can write a file your service can too.
Have you tried writing to a folder underneath c:\ProgramData?
If you don't know precisely what the problem is then you need to find out. Try adding System.Diagnostics.Debugger.Launch(); at service startup and then track the changes inside the debugger.
The Windows Service you have programmed is using "Integrated Security" for your SQL Server.
If you don't want to enter login credentials in your code, you should either set the executing user to your local account or grant the required user (e.g. LocalSystem) access to your database in your SQL Management Studio.
Usually a Windows Service is running as LocalSystem, LocalService or NetworkService. Just change the setting for your Windows Service in services.msc

ExecuteNonQuery() not saving any record

I'm working a WinForms based C# tool which has an attached MDF file based database. I'm trying to use the SqlCommand.ExecuteNonQuery() method to save a record to this attached MDF database, but the record is not saved. No error or exception occurs; only problem is that the record is not actually saved.
I have a Console.WriteLine at the top which shows the query I'm trying to run. Its correct syntax-wise, and if I copy-paste it from the output windows and run it separately, it works.
I have correctly defined the connection string as the following, and it works fine for fetching records:
public static String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestBuildDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
Here the function I'm using to save records:
public static void PerformDBWriteTransaction(string inputSQLStatement)
{
Console.WriteLine(inputSQLStatement);
DataTable returnDataTable = new DataTable();
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = connectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = inputSQLStatement;
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
errorMessages.Clear();
errorMessages.Append("The following errors were found in the SQL statement:\n\n");
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
MessageBox.Show(errorMessages.ToString());
}
finally
{
cmd.Connection.Close();
}
}
Can someone tell me what might be the problem ? Do I need to perform a 'commit' somehow ?
EDIT:
I have found the problem, and have written up a solution below .. Thanks to all who helped me out though :)
I found the problem ! It was very simple, and it was stupid really :) .. The code above is all correct .. Yes, people pointed out optimizations, etc, but still the code above was correct.
The problem was that when I imported the TestDB.MDF file into my Visual 2010 project, a copy of that was made inside the project's folder. When you run/debug the program, another copy of the this file is made and is put in the \bin\Debug\ folder. In the connection string I was using, I had mentioned: AttachDbFilename=|DataDirectory|\TestBuildDB.mdf .. This meant that all reads/writes were done to the copy in the bin\Debug folder. However, the TestDB.MDF file I was looking into to verify if records were inserted or not, was in the project's folder ! So basically, there were two MDF files, and I was writing the records into one file, but was trying to find them in the other :)
When you add an MDF file into your VS2010 Project, VS2010 by default makes a connection to that MDF file, from where you can browse the stuff in that MDF file .. The MDF file used for this purpose was the one placed in the project's folder, NOT the one in bin\Debug\ folder. And like I said earlier, my code used the one in the bin\Debug folder :)
So what I've done now is that I've removed the Test.MDF file reference from my project, which removes the copy present in the project's folder. However, I DO have a copy of TestDB.MDF file in the bin\Debug\ folder, which I connect to from within my application. And if I want to browse the MDf file outside my project, I use SQL Management Studio. The only problem here is that an MDF file can only be used by one program at a given time. So if I have to use it with my application, I have to take it offline from SQL Management studio, and vica versa !
I hope this explanation helps someone out there :)
The solution to this problem is very simple just give the full path of the original MDF file in the connection String like this:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=**C:\VISUAL STUDIO 2012\PROJECTS\ENGLISHTOHINDIDICTIONARY\ENGLISHTOHINDIDICTIONARY\DICTIONARY.MDF**;Initial Catalog=Dictionary;Integrated Security=false"
providerName="System.Data.SqlClient"
That's it, your problem is solved.
I had the same challenge, I simply changed the database property "Copy to Output Directory" from "Copy always" to "Do not copy" then moved my database.mdf (drag & drop from my IDE) into the bin\debug folder.
Tip:
The bin directory is normally hidden, use the "Show All Files" to display it
Provide a catch clause for all Exceptions. If there something wrong other than SqlException, you will never see what is it and your db will neved be updated. Imagine there is a FormatException...
Also check the return of ExecuteNonQuery : it's the number of rows affected by the query.
First, you should always wrap up your IDisposable objects in a using to ensure they're closed and disposed of properly (and that connection pooling can do its thing). Second, when modifying data wrap up your sql in a transaction to maintain data integrity.
Try the following code and see if any exceptions are raised. I wouldn't normally recommend catching Exception as it's too general, I'd let that bubble up to the calling mechanism and handle it there - but for this instance it will show you any and all issues. I think your particular issue is at the .Open stage of the connection, so try stepping through.
public static void PerformDBWriteTransaction(string inputSQLStatement)
{
DataTable returnDataTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlTransaction sqlTrans = sqlConnection.BeginTransaction())
{
try
{
using (SqlCommand cmd = new SqlCommand(inputSQLStatement, sqlConnection))
{
cmd.CommandType = CommandType.Text;
cmd.Transaction = sqlTrans;
cmd.ExecuteNonQuery();
}
}
catch (SqlException sqlEx)
{
sqlTrans.Rollback();
throw sqlEx;
}
sqlTrans.Commit();
}
}
}
catch (Exception ex)
{
errorMessages.Clear();
errorMessages.Append("The following errors were found in the SQL statement:\n\n");
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
MessageBox.Show(errorMessages.ToString());
}
}
Hi I am working on library database when I add student record executionNonQuery
shows error like invalid column name page opens but saving data from not happening.
Here I have given the code statement
public partial class add_student_info : Form
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-SPT6GLG\SQLEXPRESS;Initial Catalog=library_managment;Integrated Security=True;Pooling=False");
public add_student_info()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into student_info values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "'," + textBox5.Text + "," + textBox6.Text + "," + textBox7.Text + ")";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Student recorc addedd sussfully");
}
}
}

Trouble opening SQL connection to insert textbox values

First off, I'd like to say that this is the most brilliant forum I've encountered in my programming journey, and I've been google-fishing for all the help I can get for the last three months. Great support, and even greater style #necromancer badge.
Enough with the flattery.
I'm doing a practice project, insurance website. Right now, I need to get user input from the textboxes into the database. I have seen plenty of related questions here, but I'm getting an error message on my connection I haven't found on any of the other posts, and I'm so ignorant it's difficult to apply examples that don't fit exactly what I'm doing. (As a side note, my trainer specifically wants the most basic form of this code, and as such told me not to worry about parameterizing the queries for security or to use a try-catch block for exceptions, but many thanks to the answers here for those pointers)
The error message I get is "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."
Am I getting my syntax wrong? Am I using the 'TextBox1.Text' value right? Am I just too stupid to be doing this?
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubmissionPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\aspnetdb.mdf;Integrated Security=True;User Instance=True";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
String thisQuery = "INSERT INTO Customer (" + " Name, SIC_NAIC, Address, City, State, Zip, " + ") VALUES (" + " #TextBox1.Text, #RadioButtonList1.SelecedItem, #TextBox2.Text, #DropDownList1.SelectedItem, #TextBox3.Text" + ")";
SqlCommand thisCommand = new SqlCommand(thisQuery, sqlConn);
thisCommand.ExecuteNonQuery();
sqlConn.Close();
}
}
Check this and use sql parameters:
using (var conn = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=aspnetdb;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT INTO Customer (Name,SIC_NAIC) VALUES (#Name,#SIC_NAIC)",conn))
{
try
{
cmd.Parameters.Add("#Name", SQlDbType.VarChar, 50).Value = TextBox1.Text;
cmd.Parameters.Add("#SIC_NAIC", SQlDbType.VarChar, 50).Value = RadioButtonList1.SelecedItem.ToString();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
{
}
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Make sure you have downloaded sqlmanagement studio 2008 express.. and then attach asp.netdb on it and change your sql connectionstring.
sql ms
Regards
This error is often caused because the parent instance (for whatever reason) can't copy the system databases to the users local isolated storage folders. Sometimes it is because of a previous install of SQL Express has left files in that directory. Full story here
http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/f5eb164d-9774-4864-ae05-cac99740949b
could be due to permission issue, check eventlog. you may try removing User Instance=True from connection string
In addition to answers regarding SQL database instances, your SQL query looks wrong. Try changing your embedded query to:
String thisQuery = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('" + TextBox1.Text + "', '" + RadioButtonList1.SelecedItem.Text + "', '" + TextBox2.Text + "', '" + DropDownList1.SelectedItem.Text + "', '" + TextBox3.Text + "', '" + TextBoxZip.Text + "')";
This will format the SQL statement from the values on your form.
NOTE: Assuming field SIC_NAIC and State are storing text values and an additional field for Zip (TextBoxZip).
First of all, if your mdf resides at App_Data, then your connection string is all wrong.
Put the following in your web.config
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Now call it like
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is a fix for your error. But you should have an instance of SQL Express installed, which I supposecomes standard with Visual Studio.
http://www.aspdotnetfaq.com/Faq/fix-error-Failed-to-generate-a-user-instance-of-SQL-Server-due-to-a-failure-in-starting-the-process-for-the-user-instance.aspx
And while you are at it, please alter your Button_Click event like this
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string sql = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = String.Format(sql,
TextBox1.Text,
RadioButtonList1.SelectedItem.Text,
TextBox2.Text,
DropDownList1.SelectedItem.Text,
TextBox3.Text,
"000000");
using (SqlCommand command = new SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
}
Also keep in mind that you cannot insert RadioButtonList1.SelecedItem or DropDownList1.SelectedItem to database. You must append either .Text or .Value to it as per your requirement.
Ok guys, first of all I'm overwhelmed by the helpfulness I found here. I'll be a stackoverflow-er for life. Thank you all for taking your time and experience to aid a total stranger. I couldn't have gotten this done without it.
I wanted to post the code I ended up with, just so as to have a record of what actually worked for me in case someone with the same issue needs to see the end result. As per #yetanothercoder's recommendation, I placed this connection string in my webconfig file, and it looked like this (from ?xml version... to configuration is just to show where I placed the code, since I had wondered about that myself, the connection string is wrapped between the tags):
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=The-Crushinator\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ArgonautSubmission.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
And, although my trainer assured me that the using block #yetanothercoder suggested should be fine, it wasn't working for me, so I used the example from #chaps' answer, remembering to put in the TextBox4.Text value forgot. The code looks like this:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubmissionPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String thisQuery = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('" + TextBox1.Text + "', '" + RadioButtonList1.SelectedItem.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + DropDownList1.SelectedItem.Text + "', '" + TextBox4.Text + "')";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand command = new SqlCommand(thisQuery, sqlConn))
{
command.ExecuteNonQuery();
}
}
}
}
Next came the more convoluted part. To rid myself of the dreaded "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed" error message, I followed this link from #yetanother coder,
and found that I needed to install Sql Server Management Studio Express. I had to use Microsoft Web Platform Installer because when I tried to follow the instructions at msdn.com for downloading ssmse, I kept getting a cyclical error. I installed ssmse, opened up the query window with the 'new query' button, and executed this command
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
then I restarted sql server, added a new database to my asp.net project, and BAM! It worked! User info was saved into the database, where it was supposed to go! I had been so conditioned to expecting failure from my code that it felt like watching my first rocket make it into orbit. Awesome. Thanks again, everyone, and I hope this helps someone in a similar situation.

Categories

Resources