I have a legacy application that I am migrating off an old server onto a new one. The application is written in VB and I am simply forklifting it from one server to another. The application works fine in it's current location and the only change I made when I moved it was to update the connection strings to reflect the new database. For some reason, I now get the following error only on the OleDB connection string based on the stack trace. The other difference here is that the application on the new server uses domain accounts to authenticate the DB and not SQL accounts.
So,
1. Can you use domain accounts with an OleDB connection?
2. Is there another cause for this error?
Thanks in advance!
Connection String:
<add key="ConnectionString" value="SERVER=SQLDEV1\SQLDEV1;DATABASE=Comp_Dev;Integrated Security=SSPI;" />
<add key="SQLConnectionString" value="Provider=SQLOLEDB;Data Source=SQLDEV1\SQLDEV1;Initial Catalog=Comp_Dev;Integrated Security=SSPI;" />
Decompiled Code:
private void DisplayManagers()
{
this.wkSQL = " SELECT lngManagerID, strName FROM Managers order by strName ";
OleDbConnection oleDbConnection1 = new OleDbConnection(Conversions.ToString(this.Session["database"]));
oleDbConnection1.Open();
OleDbDataReader oleDbDataReader1 = new OleDbCommand()
{
Connection = oleDbConnection1,
CommandText = this.wkSQL,
CommandType = CommandType.Text
}.ExecuteReader(CommandBehavior.CloseConnection);
this.Manager1.DataValueField = "lngManagerID";
this.Manager1.DataTextField = "strName";
this.Manager1.DataSource = (object) oleDbDataReader1;
this.Manager1.DataBind();
this.Manager1.Items.Insert(0, new ListItem());
this.wkSQL = " SELECT lngManagerID, strName FROM Managers order by strName ";
OleDbConnection oleDbConnection2 = new OleDbConnection(Conversions.ToString(this.Session["database"]));
oleDbConnection2.Open();
OleDbDataReader oleDbDataReader2 = new OleDbCommand()
{
Connection = oleDbConnection2,
CommandText = this.wkSQL,
CommandType = CommandType.Text
}.ExecuteReader(CommandBehavior.CloseConnection);
this.Manager2.DataValueField = "lngManagerID";
this.Manager2.DataTextField = "strName";
this.Manager2.DataSource = (object) oleDbDataReader2;
this.Manager2.DataBind();
this.Manager2.Items.Insert(0, new ListItem());
}
Error:
Server Error in '/LicenseCompliance' Application.
--------------------------------------------------------------------------------
The ConnectionString property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The ConnectionString property has not been initialized.]
System.Data.OleDb.OleDbConnection.PermissionDemand() +1674465
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6600667
System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +27
System.Data.OleDb.OleDbConnection.Open() +47
LicenseCompliance.search.DisplayManagers() in C:\Users\12876\Documents\Visual Studio 2010\Projects\LicenseCompliance\search.aspx.vb:47
LicenseCompliance.search.Page_Load(Object sender, EventArgs e) in C:\Users\12876\Documents\Visual Studio 2010\Projects\LicenseCompliance\search.aspx.vb:34
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
You need to reference the connection string like so:
System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
the connectionString you have kept in config file does not belong to OleDB, rather it is of SQL Server.
Please check it to be like of OLEDB
Or else you may try by avoiding Oledb in your application and convet it to SQL
try by this
imports System.Sql.SqlClient
and then replace all OldDb with SQL, e.g. OleDbCommand to SqlComamnd
Related
I'm trying to make a simple program that has a log-in part, with a local database just for testing.And i keep getting an error when I try to open the connection to the SQL database.
private void logInButton_Click(object sender, EventArgs e)
{
MainMenu openMainMenu = new MainMenu();
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30");
sqlcon.Open();
SqlCommand cmd = new SqlCommand("Select * from Table Where username ='" + usernameTextBox.Text + "' and password = '" + passwrodTextBox.Text + "'");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count > 0)
{
openMainMenu.Show();
this.Hide();
}
else
MessageBox.Show("Wrong username or password!");
}
I get the error at sqlcon.Open();, and it is: "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: An attempt to attach an auto-named database for file C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
Well, the best advice I can give you is to google the error message. Keep in mind that if there is an error message it means that the problem is well known an as such it's a safe bet that someone have encountered it before you and managed to solve it. The first 4 results of this search are on stackoverflow and at least two of them have accepted answers, so I believe a little reasearch would have saved you a long time.
This is the best advice because it streaches far beyond your current problem. I firmly believe that good searching skills is the most important and most powerfull tools of a sotfware developer. I can assure you, no matter how much time you are developing software, almost every exception you get, someone else have already solved and posted the solution somewhere, you only need to find it.
Now, as for the code it self - You have some major problems other then the exception you are asking about:
Concatenating strings into sql statements instead of using parameters expose your code to SQL injection attacks. This is a very serious threat that is extremely easy to fix.
Using insntances of classes that implements the IDisposable interface without properly disposing them may lead to memory leak. Read about the using statement and make it a habit to use it every time it's possible.
Exception handling. Currently, if your database can't be reached, you get an exception and your program crash. You should use a try...catch block anywhere you can't control in code to let your program end gracefuly instead. (Don't ever use try...catch for things you can do in code such as validate user input or checking division by zero - only for things that are beyon your control such as database availability.)
Having said all that, your code should look something like this:
private void logInButton_Click(object sender, EventArgs e)
{
using (var sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|C:\Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30"))
{
sqlcon.Open();
using (var cmd = new SqlCommand("Select 1 from Table Where username = #userName and password = #password"))
{
cmd.Parameters.Add("#userName", SqlDbType.NVarChar).Value = usernameTextBox.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar).Value = passwrodTextBox.Text;
using (var dtbl = new DataTable())
{
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
var openMainMenu = new MainMenu();
openMainMenu.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Wrong username or password!");
}
}
}
I have problem with connecting to firebird tables. I tried every connection string i could find on internet but it doesn't work. Problem comes when i open connection
Here is code
private void RutinskiPopis_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"User ID=sysdba;Password=masterkey;Database=localhost:D:\\TDWORK.FDB;Data Source=localhost;");
SqlCommand cmd = new SqlCommand("SELECT Opis, Broj FROM PLNAZIVI", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1_Data((IDataRecord)dr);
}
con.Close();
}
Can anyone help me with that connection string?
Here is full connection string
initial catalog=D:\TDWORK.FDB;data source=localhost;user id=SYSDBA;role=admin
The problem is that you are using SqlConnection, which can only connect to Microsoft SQL Server. For Firebird you need to use FbConnection.
See for examples: .NET - examples of use.
I solved this by using FbConnection instead of SqlConnection, and then using standard firebird connection string.
try
{
string strSQLConnString = GetConnectionString();
using (SqlConnection myConnection = new SqlConnection(strSQLConnString))
{
SqlCommand myCommand = new SqlCommand("spFortesting", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Param1", varParam1);
myCommand.Parameters.AddWithValue("#Param2", varParam2);
myCommand.Parameters.AddWithValue("#Param3", varParam3);
myCommand.Parameters.AddWithValue("#Param4", varParam4);
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
dt = new DataTable();
if (myReader.HasRows)
{
dt.Load(myReader);
}
myReader.Close();
}
myConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
I am getting exception like
"The exception message is 'Could not find stored procedure 'spFortesting'."
All other existing Stored Procs are accessed correctly.
Connection string is common for all other SQL calls in the application.
'spFortesting' is newly created StoredProc.
owner is 'dbo' I tried with dbo.spname as well
While I can access the Stored Proc and Tables which are newly created using SQL Mgmt Studio and the same credentials as in web.config, but not thru the code.
What could have been wrong.
Thanks in Advance,
Amit
My mistake! when i watched it very closely I found that connection strings are not matching, the connectionstring was being picked up from the other similar sounding virtual directory. System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(#"\AppName");
and my appname on the deployed server was AppNameNew for some unkown reasons, since ages. With the name AppName there was another virtual folder and its web.config was pointing towards different database.
Sorry for the inconvenience caused if any.
Cheers!!!
and a Happy new year
I have the following code which is connecting to my database and retrieving some data from a table:
string connectionString = "Data Provider=SQLOLEDB;Data Source=myserver;Initial Catalog=Db;Integrated Security=FALSE;user=zh;pwd=zh12;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT [Location], [URL], [TAGS] FROM [Db].[dbo].[BOOKINGTABLE]";
command.CommandType = CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
menu_ul_1.DataSource = reader;
menu_ul_1.DataBind();
}
}
I get the following error:
Exception Details: System.ArgumentException: An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.
When I change the connectionstring line to:
string connectionString = "Provider=SQLOLEDB;Data Source=myserver;Initial Catalog=Db;Integrated Security=FALSE;user=zh;pwd=zh12;";
I get the following error:
Exception Details: System.Data.OleDb.OleDbException: No error message available, result code: DB_E_ERRORSOCCURRED(0x80040E21).
Source Error:
Line 23: using (OleDbConnection connection = new OleDbConnection(connectionString))
Line 24: {
Line 25: connection.Open();
Line 26:
Line 27: OleDbCommand command = new OleDbCommand();
How can I resolve the issue?
My Web.config file has the following line:
<add key="ConnStringTEST" value="Data Source=myserver;Initial Catalog=Db;Integrated Security=FALSE;user=zh;pwd=zh12;" />
How, If, I can use the above line in my C# code?
After much troubleshooting, I was able to figure out why it wasn't working. I rewrote the string like this:
string cString = "Provider=sqloledb;Data Source=myserver;Initial Catalog=mydatabase;User Id=myid;Password=mypassword;";
That worked like a charm, in case someone else is having the same issue.
Don't use "Integrated Security" when you are supplying the user ID and password.
Using this video mentioned by Borat in the comments I was able to reference differences in the connection string to adjust mine. The video demonstrates windows authentication, so if that's not what you want be sure to add your own user id and password.
My issue was my provider attribute was referencing: "Provider=IBMDASQL.DataSource.1" when connection to DB/2 but the connection string when viewed as shown in the video was referencing, "IBMDA400.DataSource.1"
Funny, after watching the video, I already knew this, and have used this method but have forgotten. How quickly we forget things.
I am new with WCF, I am trying to deploy my WCF sample application on IIS, this application works fine in debug mode with VS2008, this application authenticate the WCF messages with following code. I am doing it like this, I have added the resulted .dlls web.config and the Service.svc in the wwwroot directory, and I have also added connection string in IIS Manager, which is
Server=MyPC\SQLEXPRESS;Database=MySampleDb;Integrated Security=true
I am using Windows Integrated Security. I am using same connection string for connection in the database class but I get following exception,
Please guide me to deploy this application
In Validater
public override void Validate(string userName, string password)
{
ValidateUser(userName, password);
}
public static bool ValidateUser(string userName, string password)
{
if (!string.IsNullOrEmpty(userName))
{
ICustomer customer = GetCustomerByUsername(userName);
if (customer ==null)
{
throw new exception("User Not found.");
}
else
{
return true;
}
}
else
{
throw new FaultException("User name is required!");
}
}
public static ICustomer GetCustomerByUsername(string username)
{
try
{
//ConnectionString= "Server=MyPC\SQLEXPRESS;Database=MySampleDb;Integrated Security=true";
OpenConnection();
var cmd = new SqlCommand("GetUserByUsername", _connection) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.Add("Username", username);
connState = _connection.State.ToString();
if (_connection.State == ConnectionState.Closed)
{
OpenConnection();
}
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
ICustomer customer = null;
customer = ExtractCustomerFromDataReader(dr)[0];
dr.Close();
return customer;
}
catch (Exception e)
{
throw new Exception(e.Message + Environment.NewLine + e.StackTrace);
}
finally
{
CloseConnection();
}
}
Exception:
ExecuteReader requires an open and
available Connection. The connection's
current state is closed. at
System.Data.SqlClient.SqlConnection.GetOpenConnection(String
method) at
System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String
method, SqlCommand command) at
System.Data.SqlClient.SqlCommand.ValidateCommand(String
method, Boolean async) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior,
Boolean returnStream, String method,
DbAsyncResult result) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior,
Boolean returnStream, String method)
at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior) at
Aschrafi.MobileZollServer.Services.DatabaseHelper.GetCustomerByUsername(String
username) in
I think I am missing some point in database settings or in IIS Manager the website settings. Some tutorial or article link for WCF deployment in IIS and authenticating WCF communication would be really appreciated.
Thanks in advance.
The error message quite clearly states that your connection is not open at the time you're trying to execute your data reader.
Basically, I'd recommend completely rewriting your GetCustomerByUsername method - use the using(...) { ... } blocks as best practice around your SqlConnection and SqlCommand - something like this:
public static ICustomer GetCustomerByUsername(string username)
{
ICustomer customer = null;
try
{
using(SqlConnection _con = new SqlConnection(connectionString))
using(SqlCommand _cmd = new SqlCommand("GetUserByUsername", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("Username", username);
_con.Open();
using(SqlDataReader dr = cmd.ExecuteReader())
{
customer = ExtractCustomerFromDataReader(dr)[0];
dr.Close();
}
_con.Close();
}
return customer;
}
catch (Exception e)
{
throw new Exception(e.Message + Environment.NewLine + e.StackTrace);
}
}
By employing the using() blocks, you make sure the class instance in question will be released at the end of the { ... } block - no more need for keeping track of state and no more need for a finally clause.
Also: integrated security works fine from your desktop - but it won't work well in a hosted environment. After all: it's the IIS process that is now connection to your database - I would rather use a specific user with a password here.
Update: you can name your user anything you like - e.g. use the application's name as your user name or whatever makes sense for you. You need to create that using e.g. SQL Server Express Management Studio, and you need to create a login first using CREATE LOGIN or the GUI equivalent (under "Security" - "Logins" - right-click and pick "New Login") - this step gives that "name" the right to log into the SQL Server in the first place. This is the point where you pick a password, too.
Once you have that login created, then you need to create a user based on that login in your database (USE <database name> GO - CREATE USER ...... - or use the GUI - Your Database -> Security -> Users -> right-click and choose "New User").
Once you have all of this, your connection string will look something like:
Server=MyPC\SQLEXPRESS;Database=MySampleDb;User Id=(your user name);Pwd=(your password)