I copied the ConnectString value from the properties of my local database.
Connection String from the properties is :
Data Source=Cyber\SQLEXPRESS;Initial Catalog=GeneratedData;Integrated Security=True;
When I directly copy the ConnectionString into ConnectString, I get an error. So I take that "\" off and I did not get an error. However it still does not work. I also noticed that people usually change that ConnectionString value to a single word to make it easy.However, my VB properties section is not allowing me to change it. Here is the error I get
public class SQLConnection
{
#region MemberVariables
private SqlConnection mConnection = null;
private SqlDataAdapter mDataAdapter = null;
private SqlCommand mCommand = null;
static string mDbConnString = string.Empty;
#endregion
#region PublicMemberVariables
public SqlConnection Connection
{
get
{
return mConnection;
}
set
{
mConnection = value;
}
}
public SqlDataAdapter DataAdapter
{
get
{
return mDataAdapter;
}
set
{
mDataAdapter = value;
}
}
public SqlCommand Command
{
get
{
return mCommand;
}
set
{
mCommand = value;
}
}
public string ConnectString
{
get
{
return mDbConnString;
}
set
{
lock (mDbConnString)
{
mDbConnString = value;
}
lock (mConnection)
{
mConnection.ConnectionString = mDbConnString;
}
}
}
#endregion
public void TestConnection()
{
ConnectString = "Data Source=Cyber SQLEXPRESS;Initial Catalog=GeneratedData;Integrated Security=True";
Connection = new SqlConnection(ConnectString);
Connection.Open();
MessageBox.Show(Connection.State.ToString());
}
}
Change
Data Source=Cyber\SQLEXPRESS;Initial Catalog=GeneratedData;Integrated Security=True;
To
Data Source=Cyber\\SQLEXPRESS;Initial Catalog=GeneratedData;Integrated Security=True;
Related
This question already has answers here:
COM object that has been separated from its underlying RCW cannot be used. in oledb
(1 answer)
Hitting "COM object that has been separated from its underlying RCW cannot be used" error
(2 answers)
Closed 1 year ago.
My OleDB Class
public oleDB()
{
if (string.IsNullOrWhiteSpace(CONNECTION_STRING))
{
IDSTool.Security.EncryptDecryptData();
string dbname = "D:\\C# Desktop\\Database\\GoodsManagementMDB1.mdb;";
Source={0};Jet OLEDB:Database Password={1}", dbname, password);
CONNECTION_STRING = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Persist Security Info=False;", dbname);
ConnectionString = CONNECTION_STRING;
}
else
{
ConnectionString = CONNECTION_STRING;
}
DbConnection = new OleDbConnection(ConnectionString);
DbCommand = new OleDbCommand();
DbCommand.Connection = DbConnection;
}
public void ExecuteReader()
{
try
{
DbDataReader = DbCommand.ExecuteReader();
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbCommand.Parameters.Clear();
}
}
My AbstractDataAccess
public IDbCommand DbCommand
{
get { return dbCommand; }
set { dbCommand = value; }
}
public void Close()
{
if (DbConnection.State == ConnectionState.Open || DbConnection.State == ConnectionState.Fetching)
DbConnection.Close();
}
#region IDisposable Members
public void Dispose()
{
dbConnection.Close();
dbConnection.Dispose();
dbCommand.Dispose();
if (dbDataReader != null)
{
dbDataReader.Close();
dbDataReader.Dispose();
}
if (dbDataAdapter != null)
{
dbDataAdapter = null;
}
GC.Collect();
GC.SuppressFinalize(this);
}
My User Class
public bool CheckLogin(string userID, string userpassword)
{
bool result = false;
using (DatabaseAccess.oleDB oleDB = new DatabaseAccess.oleDB())
{
using (oleDB.DbCommand)
{
oleDB.CommandText = #"SELECT * FROM[User] where UserID=#UserID";
oleDB.AddParameter("#UserID", System.Data.OleDb.OleDbType.VarChar, userID);
oleDB.CommandType = System.Data.CommandType.Text;
try
{
oleDB.Open();
oleDB.ExecuteReader();
while (oleDB.DbDataReader.Read())
{
if (userID == oleDB.DbDataReader["UserID"].ToString() && userpassword == Tools.Security.Decrypted(oleDB.DbDataReader["Password"].ToString()))
result = true;
else
result = false;
}
oleDB.Close();
return result;
}
catch (Exception)
{
return result;
throw;
}
}
}
}
I use the oledb class as a reference in the User class to connect to the access database, oledb inherits from the AbstratDataAccess class where the AbstratDataAccess class has properties dbconnection, dbcommand etc., I have declared new DbCommand in the oledb class, but why when DbCommand.Dispose(); in Public Void Closer() method an error appears COM object that has been separated from its underlying RCW cannot be used.
I am using asp.net core 2.0 and dapper. I have a class that wraps an IDbConnection Interface and only exposes certain methods. Here is a short version of that class.
public class MyConnectionString : IMyConnectionString
{
private readonly IDbConnection _connection;
public int ConnectionTimeout => _connection.ConnectionTimeout;
public string Database => _connection.Database;
public string ConnectionString { get => null; set => _connection.ConnectionString = value; }
public ConnectionState State => _connection.State;
public MyConnectionString(IOptions<ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper)
{
var con = "some logic to get the connection string.";
_connection = new SqlConnection(con);
}
public int Execute(string query, object parameters = null)
{
using (var con = _connection) { return con.Execute(query, parameters); }
}
}
I am injecting this class via a constructor to my Repository services. For example, this is a method that would call it:
internal class SomeRepository
{
private readonly IMyConnectionString _connection;
public SomeRepository(IMyConnectionString connection)
{
_connection = connection;
}
public void ExecuteSomeQuery(Object params)
{
var query = "Some query...";
_connection.Execute(query, params);
}
}
Now the problem is that if I call _connection.Execute(query, params); twice in a single request (2 different services), the second time it gets called the ConnectionString value inside MyConnectionString class is empty. I have tried binding it in Transient and Request scope to see if it would preserve it, but no luck. Any idea on why this is happening or how can I preserve it so that I won't have to create the connection string every time it is requested?
wrapping the Connection inside a using disposes the Connection at his end of execution: just as #Jasen said in comments.
I would, in your case, just get the connection and execute on the Connection created in the constructor: removing the using completely.
You should not create the SqlConnection, since you are implementing dependency injection. You should:
Implement IDisposable to dispose your connection when your class is collected.
Pass a SqlConnection factory to create your SqlConnection, seperating your creation logic from your class.
Your class should resemble something like this:
public class MyConnectionString : IMyConnectionString
{
private readonly IDbConnection _connection;
public int ConnectionTimeout => _connection.ConnectionTimeout;
public string Database => _connection.Database;
public string ConnectionString
{
get => null;
set => _connection.ConnectionString = value;
}
public ConnectionState State => _connection.State;
public MyConnectionString(IOptions<ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper)
{
string con = "some logic to get the connection string.";
_connection = new SqlConnection(con);
}
public int Execute(string query, object parameters = null)
{
return _connection.Execute(query, parameters);
}
}
With IDisposable implementation:
using System;
public class MyConnectionString : IMyConnectionString, IDisposable
{
private readonly IDbConnection _connection;
public int ConnectionTimeout => _connection.ConnectionTimeout;
public string Database => _connection.Database;
public string ConnectionString
{
get => null;
set => _connection.ConnectionString = value;
}
public ConnectionState State => _connection.State;
public MyConnectionString(IOptions<ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper)
{
string con = "some logic to get the connection string.";
_connection = new SqlConnection(con);
}
public int Execute(string query, object parameters = null)
{
return _connection.Execute(query, parameters);
}
public void Dispose()
{
_connection.Dispose();
}
}
With your own ISqlConnectionFactory factory:
public class MyConnectionString : IMyConnectionString, IDisposable
{
private readonly IDbConnection _connection;
private readonly ISqlConnectionFactory _factory;
public int ConnectionTimeout => _connection.ConnectionTimeout;
public string Database => _connection.Database;
public string ConnectionString
{
get => null;
set => _connection.ConnectionString = value;
}
public ConnectionState State => _connection.State;
public MyConnectionString(IOptions<ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper, ISqlConnectionFactory factory)
{
_factory = factory;
_connection = _factory.CreateConnection(connProvOpts, encHelper);
}
public int Execute(string query, object parameters = null)
{
return _connection.Execute(query, parameters);
}
}
public interface ISqlConnectionFactory
{
SqlConnection CreateConnection(IOptions<ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper);
}
public class SqlConnectionFactory : ISqlConnectionFactory
{
public SqlConnectionFactory()
{
// Maybe initialization?
}
public SqlConnection CreateConnection(IOptions<ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper)
{
string con = "some logic to get the connection string.";
_connection = new SqlConnection(con);
}
}
Personally, I would have created and disposed the Connection each time Execute is invoked. This means that outside of Execute, your connection is closed and resources are released.
I have already searched for the error
the connection string property has not been initialized.
on Google as well as on Stack Overflow but couldn't find the solution. I have created a database class for interaction with database all related code is written in this file. The problem is same code runs fine on other pages and it just don't work on a page called "addevent.aspx" I don't understand the reason why it is not running properly.
Here are the methods that I created in database.cs file
public void CreateConnection()
{
var ConfiguredString = ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString;
obj_sqlconnection = new SqlConnection(ConfiguredString);
}
//This property will set the connection string for database
public string ConnectionString
{
get
{ //if _connectionString is already created or set, only then it will return the value of _connectionString
if (_connectionString != string.Empty && _connectionString != "" && _connectionString != null)
return _connectionString;
else
return string.Empty;
}
// When you want to set the connection string set block is called.
set
{ // this line sets the connection string to the _connectionString data member for the first time.
if (_connectionString == string.Empty || _connectionString == "" || _connectionString == null)
_connectionString = value;
}
}
// Open database connection.
public void OpenConnection()
{
obj_sqlconnection.Open();
}
// Close database connection.
public void CloseConnection()
{
obj_sqlconnection.Close();
obj_sqlconnection.Dispose();
}
public SqlConnection GetCurrentConnection
{
get { return obj_sqlconnection; }
set { obj_sqlconnection = value; }
}
I simply don't understand the logic of this error and its occurrence. I get this error when I open the connection
How do I call these methods, I have already created a object of database.cs class outside the method AddEvent with object name mydb
public int AddEvent(string _title, string _description, string _place, int _eventTypeID, string _startingTime, string _endingTime, string _startingDate, string _endingDate, string _creatorID, string _picture)
{
string[] blacklist = { _title, _description, _place, _picture };
if (Jvalidate.FilterBlackLIstKeywords(blacklist))
{
int eventid = Convert.ToInt32(mydb.GetLastValueByColumnName("event_id", "tbl_events"));
int rowsaffected = 0;
mydb.CreateConnection();
mydb.InitializeSQLCommandObject(mydb.GetCurrentConnection, "spAddEvent", true);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventID", eventid + 1);
mydb.obj_sqlcommand.Parameters.AddWithValue("#title", _title);
mydb.obj_sqlcommand.Parameters.AddWithValue("#description", _description);
mydb.obj_sqlcommand.Parameters.AddWithValue("#place", _place);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventType", _eventTypeID);
mydb.obj_sqlcommand.Parameters.AddWithValue("#startingTime", _startingTime);
mydb.obj_sqlcommand.Parameters.AddWithValue("#endingTime", _endingTime);
mydb.obj_sqlcommand.Parameters.AddWithValue("#startDate", _startingDate);
mydb.obj_sqlcommand.Parameters.AddWithValue("#endDate", _endingDate);
mydb.obj_sqlcommand.Parameters.AddWithValue("#schoolID", SchoolID);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventCreatorID", _creatorID);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventPicture", _picture);
try
{
//mydb.obj_sqlconnection.ConnectionString = ConfigurationManager.ConnectionStrings["cesConnectionString"].ToString();
mydb.OpenConnection();
rowsaffected = mydb.obj_sqlcommand.ExecuteNonQuery();
}
finally
{
mydb.CloseConnection();
mydb.obj_sqlcommand.Dispose();
}
return rowsaffected;
}
return 0;
}
it's too complicated solution... this will solve your problem of understanding and unnecessary code lines:
solution:
namespace Stackoverflow
{
public static class Solution
{
static readonly string _connectionStringName =
#"mainConnectionStringName";
static readonly string _connectionString =
_connectionStringName.getConnectionString();
// string extended method like .ToLower() or .Trim()
public static string getConnectionString(
this string connectionStringName)
{
return
System.
Configuration.
ConfigurationManager.
ConnectionStrings[connectionStringName].
ConnectionString;
}
public static object SqlExecute(
string connectionStringName,
string storedProcedureName,
System
.Collections
.Generic
.Dictionary<string, object> parameters,
bool isScalar)
{
object result = null;
using (System
.Data
.SqlClient
.SqlConnection connection =
new System.Data.SqlClient.SqlConnection(
string.IsNullOrWhiteSpace(connectionStringName)
? _connectionString
: connectionStringName.getConnectionString()))
if (connection != null)
using (System.Data.SqlClient.SqlCommand command =
new System.Data.SqlClient.SqlCommand()
{
CommandText = storedProcedureName,
CommandType = System
.Data
.CommandType
.StoredProcedure,
Connection = connection
})
if (command != null)
{
if (parameters != null)
foreach (System
.Collections
.Generic
.KeyValuePair<string, object>
pair in parameters)
command.Parameters.AddWithValue(
pair.Key, pair.Value);
command.Connection.Open();
result = isScalar
? command.ExecuteScalar()
: command.ExecuteNonQuery();
if (command.Connection.State ==
System.Data.ConnectionState.Open)
command.Connection.Close();
}
return result;
}
}
}
usage:
namespace SomeNamespace
{
public sealed class SomeClass
{
public int Example()
{
return (int)Stackoverflow
.Solution
.SqlExecute(
#"anyConnectionStringName", // or null for main connection string
#"anyStoredProcedureName",
new System
.Collections
.Generic
.Dictionary<string, object>()
{
{ #"field0", "value" },
{ #"field1", -1.5 },
{ #"field2", System.DateTime.Now },
{ #"field3", 3.5 },
{ #"field4", 7 },
},
false // for ExecuteNonQuery or true for ExecuteScalar
);
}
}
}
I'm trying to connect to a database, I also have a bool function to check if the connection worked. I searched all over the internet but can't really find how to do it properly.
public class DBConnection : DBLabsDLL.DBConnectionBase
{
///*
// * The constructor
// */
public DBConnection()
{
string connectionString = null;
SqlConnection connection;
connectionString = "Data Source=SQL Server;Initial Catalog=www3.idt.mdh.se;User ID=ezi15001;Password=********";
connection = new SqlConnection(connectionString);
}
public override bool login(string username, string password)
{
try
{
using (var connection = new SqlConnection(connectionString)
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
I have my connection string stored in a myGlobals.cs page as below:
/* Connection String */
public static string conString
{
get { return _conString; }
set { _conString = ConfigurationManager.ConnectionStrings["BaseConnectionString"].ToString(); }
}
I have my code setup in the 4 tier architecture. So I have a Business Object folder, Business Access Layer & Data Access Layer. If I move the connection string into the DAL structure it works fine. Other wise I get this error:
The ConnectionString property has not been initialized
Is the myGlobals.cs class not being included before all this or does it need to be changed around?
Here is my Data Access Layer:
public DataTable Load()
{
SqlConnection conn = new SqlConnection(MyGlobals.conString);
SqlDataAdapter dAd = new SqlDataAdapter("administratorGetAll", conn);
dAd.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet dSet = new DataSet();
try
{
dAd.Fill(dSet, "AdministratorsTable");
return dSet.Tables["AdministratorsTable"];
}
catch
{
throw;
}
finally
{
dSet.Dispose();
dAd.Dispose();
conn.Close();
conn.Dispose();
}
}
The property 'setter' doesn't get called automatically; its code is executed when you put the property on the left-hand side of an assignment - MyClass.MyProperty = "new value";
You want to be doing this:
public static string conString
{
get { return ConfigurationManager.ConnectionStrings["BaseConnectionString"]; }
}