Failed to generate a user instance of SQL Server - c#

I have a local project where I am trying to input data from an ASP:textbox to a database.
On building I get the following...
"Failed to generate a user instance of SQL Server. Only an integrated connection can generate a user instance. The connection will be closed."
I'm a little puzzled here, I have checked the database and it is active with the credentials i am trying to connect with.
Here is the code behind
C#
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection sqlcon = new SqlConnection(#"user id=*myuserid*;"+"password=*mypassword*;"+"Data Source=mssql.dev-works.co.uk;User Instance=True;"+"Database=devworks_osqar"+"Trusted_Connection=true;");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Create_Click(object sender, EventArgs e)
{
DataBinder ds = new DataBinder();
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}
}
Any help would be much appreciated.
Edited code behind (read commment below)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string myConnectionString;
private SqlConnection myConn;
public new_questionnaire()
{
myConn = new SqlConnection();
myConnectionString += "Data Source=mssql.database.co.uk; Initial Catalog=devworks_osqar;User ID=myusername;Password=mypassword";
}
protected void Create_Click(object sender, EventArgs e)
{
//DataBinder ds = new DataBinder();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
insert(sqlcmd);
}
private void insert(SqlCommand myCommand)
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}
}
}

Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."
Content from link pasted and altered below in case reference site is removed in the future:
Step 1.
Enabling User Instances on your SQL Server installation
First we are gonna make sure we have enabled User Instances for SQL Server installation.
Go to Query Window in SQL Server Management Studio and type this:
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
Run this query and then restart the SQL Server.
Step 2.
Deleting old files
Now we need to delete any old User Instances.
Go to your C drive and find and completely DELETE this path (and all files inside):
C:\Documents and Settings\ YOUR_USERNAME \Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
(Dont forget to replace the bold text in the path with your current username (if you are not sure just go to C:\Documents and Settings\ path to figure it out).
After deleting this dir you can go to Visual Studio, create ASP.NET WebSite and click on your App_Data folder and choose Add New Item and then choose SQL Server Database and it should work!!!

Related

Visual C# SQL statement won't insert into database

I am trying to simply insert values into an SQL table. The ID in the database cannot be AUTO_INCREMENT so I use MAX and +1. Not only will this code not make a new ID, it simply isn't inserting anything into the table.
Even in the debugger there are no errors or warnings, it just isn't showing up in the database itself..
Here is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
using System.ComponentModel;
using System.Drawing;
using System.Text;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonClick(object sender, EventArgs e){
using (var sqlConnection1 = new SqlConnection("Data
Source=SERVER; Initial Catalog = Metal; Integrated
Security = True"))
{
SqlDataAdapter cmd = new SqlDataAdapter();
using (var insertData = new SqlCommand("INSERT INTO ApptIn
(CONTROLNUMBER, CARRIERNAME, EXPECTEDNUMOFPIECES, EXPECTEDWEIGHT) VALUES
(#carrierSelectInput,
#pieceCountInput, #weightinput)")
{
SqlCommand generateApptNum = new SqlCommand();
View appNumView = new View();
insertData.Connection = sqlConnection1;
string carrierSelectInput = DropDownList1.Text;
string pieceCountInput = TextBox1.Text;
string weightInput = TextBox2.Text;
insertData.Parameters.Add("#carrierSelectInput",
carrierSelectInput.VarChar);
insertData.Parameters.Add("#pieceCountInput",
pieceCountInput.Int);
insertData.Parameters.Add("#weightInput",
weightInput.Int);
cmd.InsertCommand = insertData;
sqlConnection1.Open();
insertData.ExecuteNonQuery();
generateApptNum.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
}
EDIT: I have tried running the SQL into the DB and it gave an error, so I changed it(updated in code) but it puts in at ID=0...
I know you have already committed to your plan, but, I feel that I have to point out that, due to the sub select for the Max id value in your query, the insert statement has the potential to be much slower than a normal insert.
If you are planning on inserting a large number of rows or creating an API for use throughout the code I highly recommend either adjusting the column definition to be an identity column or to consider using a a sequence to generate the ids.
The issue could be that you need to specify the CommandType to be CommandType.Text on the insertData command. There is a lot going on in the original code with multiple sqlcommands being declared. I think the code could be simplified as such:
protected void ButtonClick(object sender, EventArgs e)
{
using (var sqlConnection1 = new SqlConnection("data source=testServer;initial catalog=testCat;integrated security=True;"))
using (var insertData = new SqlCommand("insert into tempExample (id, code, description) values ((select max(coalesce(id, 1)) from tempExample)+1, #code, #description)", sqlConnection1))
{
insertData.CommandType = CommandType.Text;
insertData.Parameters.AddWithValue("#code", "Testing4");
insertData.Parameters.AddWithValue("#description", "Testing3");
sqlConnection1.Open();
insertData.ExecuteNonQuery();
sqlConnection1.Close();
}
}
Update - I changed the code above to reflect a working test on my local machine. Note that the connection string format is different (lack of spaces).

How to connect to database in C# using SqlConnection object?

How can I connect to a remote or local database using simple SqlConnection object? I learned to do it this way, but my connection is failing. I read about creation of connection string from this page:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
My code:
using System.Data.SqlClient;
namespace SyncApp_BuiltInProviders
{
public partial class Form1 : Form
{
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection source_conn = new SqlConnection();
source_conn.ConnectionString ="Server=localhost;Database = ptls; UID = root;Password = ODYSSEY99GRANITE;";
source_conn.Open();
}
}
}
As from your comment in another answer it is clear that you are using the wrong classes. The SqlConnection is a class specialized in connecting to Sql Server/Sql Server Express/LocalDb. It cannot work against a MySql
If you use MySql then you need to download and install the MySql Connector for NET from here.
After that, you need to reference the MySql.Data.dll and add a
using MySql.Data.MySqlClient;
to all the source files that interact with the database.
Finally, all the classes used to work with the database, should be the ones provided by the MySql NET Connector.
They are prefixed with MySql..... (MySqlConnection, MySqlCommand, MySqlDataReader etc.)
If you are used SQL Database, it seems to me that, you have not set username and password. If you have not set username and password then try this.
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection db_connect= new SqlConnection();
db_connect.ConnectionString ="Server=[your local pc connection name, it is not local host.];Database=[database_name];Trusted_Connection=true";
db_connect.Open();
}
If you use MySql then
private void btnSynchronize_Click(object sender, EventArgs e)
{
//Create a MySQL connection string.
string connectionString="Server=localhost;Database[database_name];Uid=root;Password =your password; ";
MySqlConnection db_connect= new MySqlConnection(connectionString);
db_connect.Open();
}
Finally use following name space
using MySql.Data.MySqlClient;

Connection String Issues in C# ASP.NET

The current program I am working on is for a Registration page for a shopping cart, I have setup a SQL Server with tables to allow data to be recorded as
UserName,
Email,
Password all are set a Nvarchar(max).
The version of the .NET Framework is 4.5 and I am using VS 2012 and am coding in C#, and the server is an SQL Server instance KENSULLIVAN-PC\KSSQL using integrated Windows Authentication.
So far, I have been able to run the registration page to the point where it will save a cookie of the information but, not send any information to the tables in SQL Server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Account_Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
}
//Submit button for user registration information
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
int TheUserID = 5000;
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC/KSSQL;Database=GroupProject; Integrated Security=True");
//INSERT command for values to be updated or added to the Database
SqlCommand comm = new SqlCommand("INSERT INTO RegUser (UserName, Email, Password) VALUES (#UserName, #Email, #Password)", conn);
comm.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#UserName"].Value = RegisterUser.UserName;
comm.Parameters.Add("#Email", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#Email"].Value = RegisterUser.Email;
comm.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#Password"].Value = RegisterUser.Password;
try
{
conn.Open();
comm.ExecuteNonQuery();
Response.Redirect("~/LoggedIn.aspx");
}
catch
{
//ErrorDB.Text = "Error Submitting, Try Again";
}
finally
{
conn.Close();
}
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/LoggedIn.aspx";
}
Response.Redirect(continueUrl);
}
}
What should I be doing differently, what do you notice that is not really recommended?
Thank you,
Kenneth
I see a couple of possible issues.
First, the instance name for SQL databases should be using a backslash. Of course you'll need to escape that backslash, so try this:
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC\\KSSQL;Database=GroupProject; Integrated Security=True");
Second, integrated security can be a little tricky from ASP.NET since often times it's running from a service or system account. You may want to enable MIXED authentication mode in MS-SQL, create a SQL account, and pass in a username and password. I would recommend storing your connection string in the web.config and encrypting it.
Is there a specific error/exception you're receiving? That would be very helpful to us.
First of all #Adam already pointed out, your connection string has issue, for named instance of SQl server, if you are using .Net, it should be backslash
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC\\KSSQL;Database=GroupProject; Integrated Security=True");
OR using #
SqlConnection conn = new SqlConnection(#"Server=KENSULLIVAN-PC\KSSQL;Database=GroupProject; Integrated Security=True");
Second, because you are using Window Authentication, you need to set you ThreadPool which host you web application to run under a windows domain account, which has enough permission to backend database.
If each user using your web site login with windows domain account, and you want to use user's window domain credential to access to backend database, then you need more set up, you need the impersonation, you probably also need constrained delegation.

can't find the logical error in c# asp.net below

I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.

How is the debug version of a SQL Server database maintained?

I am getting the Errors
"Unable to copy file "j:\users\gary\documents\visual studio
2010\Projects\MyApp01\MyApp01\MyApp01.mdf" to "bin\Debug\MyApp01.mdf".
The process cannot access the file 'bin\Debug\MyApp01.mdf' because it
is being used by another process."
and
"Unable to delete file "j:\users\gary\documents\visual studio
2010\Projects\MyApp01\MyApp01\bin\Debug\MyApp01.mdf". The process
cannot access the file 'j:\users\gary\documents\visual studio
2010\Projects\MyApp01\MyApp01\bin\Debug\MyApp01.mdf' because it is
being used by another process."
I have been working on getting this problem fixed for almost a week now, but still cannot fathom out what is wrong.
Today I have created a new Project called MyApp01 & connected a new 2 Column Database of the same name, and I edited the Properties to change the "Copy to Output Directory" status from "Copy Always" to "Copy if Newer". My understanding of this is that the database that is stored in the MyApp01 Folder creates a test version of it in the MyApp01\bin\Debug\ folder the first time it is accessed and then is only overwritten if the Database layout is changed. Is that correct ? If so, why am I getting these errors that seem to insinuate that the system is trying to replace the \bin\Debug\ version of the database ?
I ran the App for the first time & it seemed to work just fine, my database was updated with three records, these displayed in Form2 and I Quit out of it successfully. However, back in VS2010 I used the Server Explorer to Show Table Data and this shows the Database as empty, so I believe that insinuates it is looking at the version in the MyApp01 folder & not the version in the MyApp01\bin\Debug\ folder. Therefore I ran the program again and this is where I get these errors.
So, again, is my understanding of the way the database is copied and maintained correct, and if so (or if not !!) why am I getting these errors telling me that the system is trying to replace the \bin\Debug\ version of the database ?
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.Windows.Forms;
using System.Data.SqlClient;
namespace MyApp01
{
public partial class Form1 : Form
{
int myCount;
string myDBlocation = #"Data Source=MEDESKTOP;AttachDbFilename=|DataDirectory|\MyApp01.mdf;Integrated Security=True;User Instance=False";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myCount++;
//Insert Record Into SQL File
myDB_Insert();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
private void button3_Click(object sender, EventArgs e)
{
//Quit
myDB_Close();
this.Close();
}
void myDB_Insert()
{
using (SqlConnection myDB = new SqlConnection(myDBlocation))
using (SqlCommand mySqlCmd = myDB.CreateCommand())
{
mySqlCmd.CommandText = "INSERT INTO MyAppTbl(MyData) VALUES(#MyValue)";
mySqlCmd.Parameters.AddWithValue("#MyValue", myCount);
myDB.Open();
MessageBox.Show("State = " + myDB.State);
mySqlCmd.ExecuteNonQuery();
myDB.Close();
MessageBox.Show("State = " + myDB.State);
}
return;
}
void myDB_Close()
{
using (SqlConnection myDB = new SqlConnection(myDBlocation))
using (SqlCommand mySqlCmd = new SqlCommand())
{
myDB.Close();
}
return;
}
}
}
I have resolved this now by using a New Database that I created in MS SQL Server Management Studio and I added it to the VS2010 C# Project as an Existing Item, rather than a New Item.
I hope this helps anybody that runs into the same frustrating problems that I did !!!

Categories