I am in the process of adding a new form to an already established Winforms application.
I have a DataGridView on my form and the relevant method in code behind which calls my dbAPI DataTable method. I have written the method with exactly the same code as many others used in the dbAPI class but for some reason it is not initialising the connection string...
public DataTable getMyTable()
{
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
_conn is an SQLConnection object. My connection string is in the app.config...
class dbAPI
{
Utils _utils = new Utils();
//this is the API between the Application Code and the LDB Database
string _ldb_connection_string = (string)dii.Properties.Settings.Default.connLDB; //connection string but with only one \ in settings as it gets converted to \\
int _command_timeout = Convert.ToInt32((string)dii.Properties.Settings.Default.commandTimeOut); //Command time out
SqlConnection _conn = new SqlConnection();
public dbAPI()
{
//constructor
}
#region --------------- Database Connectivity Section
public string openLocalDatabaseConnection()
{
try
{
//try to create the connection
_conn = new SqlConnection(_ldb_connection_string);
_conn.Open();
}
catch (Exception e)
{
return string.Concat("Can't connect to LDB with '", e.Message, "'");
}
return ""; //success
}
public string closeLocalDatabaseConnection()
{
_conn.Close();
_conn.Dispose();
return "";
}
I am getting an empty connection string and 'The ConnectionString property has not been initialized' exception thrown. I don't understand as I have numerous other methods in the class which work without issue. Any ideas?
Thanks
You have to call openLocalDatabaseConnection() function before proceeding further so that your SqlConnection Object will be initilised with Connection String Properly.
Code :
public DataTable getMyTable()
{
openLocalDatabaseConnection();
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
For example add an application config file to your project(or inside the one you have) and place this(the name and the connection string you place yours of course):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="MyConnection" connectionString ="your connection string here"/>
</connectionStrings>
</configuration>
Then in your _ldb_connection_string:
string _ldb_connection_string = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
Related
I am making login window to connect Oracle from my app (C# Entity Framework Code First from existing database). I want to make user able to set his own username\password to connect with DB. I tryed to change connection string in my DbContext, but it is doesn't work. Connection string seems to be changed, but provider returns invalid login\password exception. When I am trying to connect DB with connection string whitch has stored pass everything is ok. I think there is some security reasons for this behaivor. How can I propperly change connection string in runtime?
I am using VS 2017, Entity Framework 6, Oracle.ManagedDataAccess 18.3, Oracle 11.2 Server.
App.config
name="ConnStrPass" connectionString="DATA SOURCE=titan;PASSWORD=REALPASS;PERSIST SECURITY INFO=True;USER ID=BEE" providerName="Oracle.ManagedDataAccess.Client"
name="ConnStrNoPass" connectionString="DATA SOURCE=titan;PASSWORD=QWERTY;PERSIST SECURITY INFO=True;USER ID=BEE" providerName="Oracle.ManagedDataAccess.Client"
DBDemoModel.cs
public partial class DBDemoModel : DbContext
{
public DBDemoModel()
: base("name=ConnStrPass")
{
}
//overriding constructor DBDemoModel to change pass in ConnectionString
public DBDemoModel(string pass)
: base("name=ConnStrNoPass")
{
this.Database.Connection.ConnectionString = this.Database.Connection.ConnectionString.Replace("QWERTY", pass);
}
AbonentsFinder.cs //works fine
public List<ABONENTS> SelectAbonentsByName(string textToFind)
{
using (DBDemoModel db = new DBDemoModel())
{
var cont = db.ABONENTS.Where(a => a.OWNER.Contains(textToFind));
var abon = cont.ToList();
return new List<ABONENTS>(abon);
}
}
AbonentsFinder.cs //doesn't work wrong username\login
public List<ABONENTS> SelectAbonentsByName(string textToFind, string pass)
{
using (DBDemoModel db = new DBDemoModel(pass))
{
var cont = db.ABONENTS.Where(a => a.OWNER.Contains(textToFind));
var abon = cont.ToList(); //exception
return new List<ABONENTS>(abon);
}
}
DBDemoModel.cs //System.NotSupportedException
public DBDemoModel(string pass)
: base(new OracleConnection("DATA SOURCE=titan; PASSWORD="+pass+";USER ID=BEE"), true)
{
}
Problem solved. The problem was with EF profiler I used in my project. I disabled it and now everything works fine. OMG.
All Oracle Database Configure i hope help for anyone. thanks
public static OracleConnection Connection;
public static bool GetConnection()
{
String connectionString = "Data Source=Test;User ID=Test;Password=Test;";
try
{
Connection = new OracleConnection(connectionString);
//Connection.Open();
return true;
}
catch (OracleException ww)
{
MessageBox.Show(ww.ToString());
return false;
}
}
public static int ExecuteStatement(string query)
{
if (fncOpenConnection(false))
{
try
{
OracleCommand cmd = new OracleCommand(query, Connection);
int rowCount = cmd.ExecuteNonQuery();
return rowCount;
}
catch (Exception ex)
{
GlobalApp.ErrorMsg = ex.ToString();
return -1;
}
}
else return -1;
}
public static int ExecuteStatement_TXN(string query)
{
if (fncOpenConnection(false))
{
OracleTransaction txn;
txn = Connection.BeginTransaction();
try
{
OracleCommand cmd = new OracleCommand(query, Connection);
int rowCount = cmd.ExecuteNonQuery();
txn.Commit();
return rowCount;
}
catch (Exception er)
{
GlobalApp.ErrorMsg = er.ToString();
txn.Rollback();
return -1;
}
}
else return -1;
}
public static OracleDataReader GetReader(string query)
{
fncOpenConnection(false);
OracleDataReader dr = null;
try
{
OracleCommand cmd = new OracleCommand(query, Connection);
dr = cmd.ExecuteReader();
return dr;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return dr;
}
}
public static DataTable GetTable(string query, int[] primaryKeyCol = null)
{
DataTable dt = null;
try
{
dt = new DataTable();
OracleDataAdapter oadp = new OracleDataAdapter(query, Connection);
oadp.Fill(dt);
if (primaryKeyCol != null)
{
DataColumn[] keyColumns = new DataColumn[primaryKeyCol.Count()];
int iCount = 0;
foreach (int x in primaryKeyCol)
{
keyColumns[iCount] = dt.Columns[x];
iCount = iCount + 1;
}
dt.PrimaryKey = keyColumns;
}
return dt;
}
catch (Exception)
{
return dt;
}
}
You need to login in order to change your password (similar to the way that most web sites will ask you for your CURRENT password first).
So let them login with their existing password, after which point you can run the following command through your connection object:
"alter user MY_USER identified by TheirNewPassword"
I have a form that checks whether values are in a database before adding them. Each field is in a different table, and to keep everything clean, I have a checkExists method for each field. Is there a way to have a separate method that connects to the database, so that I don't have to connect in every field method?
I'd like to do something like this so that my code is less messy:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
But I get a
local variable set_conn
Argument 2: Cannot Convert from Class_DB to System.Data.SqlClient.SqlConnection
I understand the error, so what can I do to return the correct value, or do I have to establish a connection within my CheckData_Comany() method?
Your method SetConnection should be returning SqlConnection back like:
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
and then you can have something like:
SqlConnection connection = set_conn.SetConnection();
and then pass it in SqlCommand constructor as parameter :
SqlCommand check_Company = new SqlCommand(query_string, connection);
Your complete method implementation would become :
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
and important thing to note is do not forget the close the connection finally by calling connection.Close(), otherwise it might cause eating up the resources that shouldn't happen when we are done with querying the database and we should release the resources occupied.
Hi i am getting the following error while trying to update my database using c# asp.net.
Error:
Server Error in '/' 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:
Line 33: catch (Exception e)
Line 34: {
Line 35: throw e;
Line 36: }
Line 37: }
I am explaining my code below.
index.aspx.cs:
protected void reject_Click(object sender, EventArgs e)
{
//LinkButton lbtn = (LinkButton)(sender);
//lbtn.BackColor = System.Drawing.Color.Red;
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
LinkButton lbtn = (LinkButton)grdrow.FindControl("accept");
LinkButton LRejectBtn = (LinkButton)grdrow.FindControl("reject");
// string status = grdrow.Cells[6].Text;
int healthId = int.Parse(lbtn.CommandArgument);
int result=0;
if (Convert.ToString(lbtn.BackColor) == "Color [Green]")
{
char updatedStatus = 'R';
result = objhealthCommentBL.updateStatusDetails(updatedStatus, healthId);
if (result == 1)
{
LRejectBtn.BackColor = System.Drawing.Color.Red;
lbtn.BackColor = System.Drawing.Color.WhiteSmoke;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status has updated successfully.')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status couldnot updated')", true);
}
}
}
healthCommentBL.cs:
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
result = objhealthCommentDL.updateStatusDetails(updatedStatus, healthId);
return result;
}
catch (Exception e)
{
throw e;
}
}
healthCommentDL.cs:
namespace DataAccess
{
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getHealthCommentDetails()
{
try
{
con.Open();
DataSet ds = new DataSet();
string sql = "SELECT Health_Comment_ID,Health_ID,Health_Comment_Name,Health_comment_Email,Health_Comment_Message,Health_Comment_Website,Health_Comment_Status from T_Health_Comment";
sql += " order by Health_Comment_ID ASC ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
con.Close();
con.Dispose();
}
}
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
con.Open();
string query = "UPDATE T_Health_Comment SET Health_Comment_Status = #status WHERE Health_Comment_ID = #healthid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#healthid", healthId);
cmd.Parameters.AddWithValue("#status", updatedStatus);
result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
catch (Exception e)
{
throw e;
}
}
}
}
I am getting the above error in healthCommentBL.cs file in catch statement.Here i can say that the commentstring is properly working in the getHealthCommentDetails method in healthCommentDL.cs file but at the same time it is not working for the 2nd method of this file.Please help me to resolve this error.
When you write your connection as;
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
It will be a field of healthCommentDL class, not a local variable. And it's properties (like ConnectionString) is not initialiazed. Instead of that, define your connections as a local variables in your methods. ADO.NET is pretty good at maintaining your connections as a local variables. Read: SQL Server Connection Pooling
public DataSet getHealthCommentDetails()
{
SqlConnection con = new SqlConnection(CmVar.convar);
and
public int updateStatusDetails(char updatedStatus, int healthId)
{
SqlConnection con = new SqlConnection(CmVar.convar);
A few things more;
You should always use parameterized sql. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.
I am learning C# and SQL Server. I was following a simple tutorial, which led me to the creation of a class DBconnection that connects and updates the DB. Then I have a simple C# form that navigates back and forth on table rows using a button and a DataSet to clone the data, and then displays the info on some labels.
No problem 'till here, but then I thought, what if I wanted to display a single value(column) of a specific row, say "show me the last name of the person with a certain first name".
I'm familiar with the SQL query commands, so what I want is something like this:
SELECT last_name FROM Employees WHERE first_name = 'Jason'
Follows my code...
DBconnection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cemiGEST
{
/// <summary>
/// A class that makes the connection to the SQL Database
/// </summary>
class DBconnection
{
// variables
private string sql_string;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
// set methods
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
// DataSet
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
// MyDataSet method
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
// Update DB method
public void UpdateDB(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
I am accessing the values (when moving back and forth) by just incrementing by one a variable that updates the row number. Some exemplifying code follows.
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = Properties.Settings.Default.authSQL;
ds = objConnect.GetConnection;
maxRows = ds.Tables[0].Rows.Count;
if (maxRows == 0)
{
MessageBox.Show("No user found. Loading first run wizard.");
NewUser newUser = new NewUser();
newUser.ShowDialog();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
I'm sure this is simple, but I'm not getting there.
EDIT:
I would prefer using my class DBconnection and without external libraries. I'm not at the PC with the project, so can't test anything right now, but after a good night of sleep over the matter, and after (re)looking at my code, I may have found the answer. Please tell me if you think this would do the trick:
In my second class (where I connect to and access the DB), I have already using a SQL query, more specifically here:
objConnect.Sql = Properties.Settings.Default.authSQL;
This query (authSQL), was created by me and embedded on the Settings, and here I am importing it. So, if I do the following instead, do you think it would work:
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
The "Properties.Settings.Default.authSQL" code is nothing more than a shortcut to a string "SELECT * FROM AUTH" - AUTH is my table, which I called Employees for the sake of simplicity.
So, it would be something like this:
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
ds = objConnect.GetConnection;
// Data manipulation here
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
There's no need for a dataset here. If you know the sql you want: use it - perhaps with some parameterization. For example, using "dapper", we can do:
string firstName = "Jason";
var lastNames = con.Query<string>(
"SELECT last_name FROM Employees WHERE first_name = #firstName",
new { firstName }).ToList();
Check this ....hope this also works...
//String Declaration
string Sqlstr = "select CountryCode,Description,Nationality from ca_countryMaster where isDeleted=0 and CountryCode = 'CAN' ";
string DBCon = "Data Source=RAJA;Initial Catalog=CareHMS;Integrated Security=True;";
SqlConnection SqlCon = new SqlConnection(DBCon);
SqlDataAdapter Sqlda;
DataSet ds = new DataSet();
try
{
SqlCon.Open();
Sqlda = new SqlDataAdapter(Sqlstr, SqlCon);
Sqlda.Fill(ds);
gdView.DataSource = ds.Tables[0];
gdView.DataBind();
}
catch (Exception ex)
{
lbl.text = ex.Message;
}
finally
{
ds.Dispose();
SqlCon.Close();
}
Here is my code:
string sql = string.Format("select * from StockInTb ");
DataTable dt = dataAccess.GetDataTable(sql);
UploadService.UploadClient client = new UploadService.UploadClient();
if (client.UpdateTest(dt))
{
MessageBox.Show("suceess");
}
else
{
MessageBox.Show("fail");
}
Here is my dataaccess class:
private static string connString;
private static SQLiteConnection conn;
public SQLiteDataAccess()
{
connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
private void OpenConn()
{
try
{
if (conn == null)
{
conn = new SQLiteConnection(connString);
}
if (conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
private void CloseConn()
{
try
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
public System.Data.DataTable GetDataTable(string sql)
{
DataTable dtResult = new DataTable();
try
{
OpenConn();
SQLiteDataAdapter adpter = new SQLiteDataAdapter(sql, conn);
DataSet ds = new DataSet();
adpter.Fill(ds);//here,I got the error.
if (ds.Tables.Count > 0)
{
dtResult = ds.Tables[0];
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
finally
{
CloseConn();
}
return dtResult;
}
I got the error:
String was not recognized as a valid DateTime.
The database is SQLite, and table StockInTb contains some columns which type is datetime.
I've found some solutions like datetime.toString(s), but that's not what I need.
I don't know how to solve this odd problem. If somebody knows the answers, please tell me.
Thanks.
You can use parameter as below, Assume You have Column called MyDateTime and type is DateTime in your StockInTb Table then your query should be change as below.
Note that #InputDate going to add bay using Command.Parameters.Add method. Need to give the same name in both places and you can directly set parameter from DateTime object ( here it is named as InputDate
Command.CommandText = "select * from StockInTb where MyDateTime = #InputDate";
Command.Parameters.Add("#InputDate", InputDate);