Asp.net mvc get data from ms sql server - c#

I am trying to get DataTable from my ms sql server. I added the connection string, tested connection, everything is ok. But each time i get empty result.
ProjectDbConnection.class
public class ProjectDbConnection
{
protected SqlConnection SqlConnection;
#region Open Connection
public bool Open(string Connection = "WebProjectDB")
{
SqlConnection = new SqlConnection(#WebConfigurationManager.ConnectionStrings[Connection].ToString());
try
{
if (SqlConnection.State != ConnectionState.Open)
{
SqlConnection.Open();
}
return true;
}
catch (SqlException ex)
{
return false;
}
}
#endregion
#region Close Connection
public bool Close()
{
try
{
SqlConnection.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region get table
public DataTable GetTable(string sql)
{
var query = sql;
var d = new DataTable();
try
{
if (SqlConnection.State == ConnectionState.Open)
{
var cmd = new SqlCommand(query, SqlConnection);
var reader = cmd.ExecuteReader();
d.Load(reader);
reader.Close();
return d;
}
return d;
}
catch (Exception ex)
{
return d;
}
}
#endregion
}
Here i call the methods:
ProjectDbConnection dbConnection = new ProjectDbConnection();
dbConnection.Open();
DataTable survey = dbConnection.GetTable("SELECT * FROM tbl_survey");
DataTable criteriaClasification = dbConnection.GetTable("SELECT * FROM tbl_criteria_classification");
DataTable criteriaElement = dbConnection.GetTable("SELECT * FROM tbl_criteria");
dbConnection.Close();
Here is Web.config
<connectionStrings>
<add connectionString="Data Source=test-pc;Initial Catalog=WebProject;Integrated Security=True" name="WebProjectDB"/>
</connectionStrings>

It look like SqlConnection is not open. Your connection string using windows authentication, but your network credential may not have access to database server.
Please change you connection to use SQL credential (passing sql username and password) and try to connect. Also change your code as stated below to make sure Gettable method will get called only if connection is open. If possible log the error if connection open failed.
ProjectDbConnection dbConnection = new ProjectDbConnection();
if (dbConnection.Open())
{
DataTable survey = dbConnection.GetTable("SELECT * FROM tbl_survey");
DataTable criteriaClasification = dbConnection.GetTable("SELECT * FROM tbl_criteria_classification");
DataTable criteriaElement = dbConnection.GetTable("SELECT * FROM tbl_criteria");
dbConnection.Close();
}

Related

Best way to create new SqlConnection when is null

I have two methods that connect to the database and I try to avoid double code
one of my methods is one that can run alon (open itself SqlConnection and close it)
another method using existing SqlConnection and using SqlTransaction also (I don't want to open another connection and also I don't want to close it)
my first method :
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
using (SqlConnection openCon = new SqlConnection(connectionString))
{
string query = "SELECT [CSeriesNum],[CCount],[Mark] from [Serieses] " +
"where [TestPrimary]=#deliveryNumber";
SqlCommand command = new SqlCommand(query, openCon);
command.Parameters.AddWithValue("#deliveryNumber", DeliveryReportObject.DeliveryNumber);
openCon.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
CSerieses.Add(new CSerieses(reader.GetString(0), reader.GetInt32(1), reader.GetBoolean(2)));
}
}
openCon.Close();
}
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}
The method that using on the transaction :
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject,
SqlConnection co,SqlTransaction tran)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
using (co)
{
string query = "SELECT [CSeriesNum],[CCount],[Mark] from [Serieses] " +
"where [TestPrimary]=#deliveryNumber";
SqlCommand command = new SqlCommand(query, co, tran);
command.Parameters.AddWithValue("#deliveryNumber", DeliveryReportObject.DeliveryNumber);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
CSerieses.Add(new CSerieses(reader.GetString(0), reader.GetInt32(1), reader.GetBoolean(2)));
}
}
}
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}
I try to combine them :
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject,
SqlConnection co = null,SqlTransaction tran = null)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
using (co ?? new SqlConnection(connectionString))
{
if (co.IsOpened() == false)
{
co.Open();
}
string query = "SELECT [CSeriesNum],[CCount],[Mark] from [Serieses] " +
"where [TestPrimary]=#deliveryNumber";
SqlCommand command = new SqlCommand(query, co, tran);
if(tran != null)
{
command.Transaction = tran;
}
command.Parameters.AddWithValue("#deliveryNumber", DeliveryReportObject.DeliveryNumber);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
CSerieses.Add(new CSerieses(reader.GetString(0), reader.GetInt32(1), reader.GetBoolean(2)));
}
}
}
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}
It does not work for me. I have no idea how to check if it null in using and if yes to create a new instance of SqlConnection that should close at the end of the using statement
And I do it the right way anyway?
This is a major problem:
using (co ?? new SqlConnection(connectionString))
If co is passed in, then you don't own it - the caller does - so: you shouldn't be disposing it. What I would suggest here is:
bool ownConnection = false;
try
{
if (co is null)
{
ownConnection = true;
co = new SqlConnection(...);
co.Open();
}
// your code here
}
finally
{
if (ownConnection)
{
co?.Dispose();
}
}
or wrap that up in a helper - perhaps a custom disposable that takes a connection and connection string:
public readonly struct ConnectionWrapper : IDisposable
{
private readonly bool owned;
public SqlConnection Connection { get; }
public ConnectionWrapper(SqlConnection connection, string connectionString)
{
if (connection is null)
{
owned = true;
Connection = new SqlConnection(connectionString);
Connection.Open();
}
else
{
owned = false;
Connection = connection;
}
}
public void Dispose()
{
if (owned)
{
Connection?.Dispose();
}
}
}
then you can just use:
using var wrapped = new ConnectionWrapper(co, connectionString);
// your code, using wrapped.Connection
This seems that kind of situation that perfectly fits the overload concept.
The GetCSerieses method should have two versions, the first one builds its own connection and transaction, the second one takes both a non optional connection and a non optional transaction. The first one, after creating the connection and the transaction calls the second one.
Now if a third method requires a call the GetCSerieses could pass its own connection and transaction, while a call without them will be handled by the first overload
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject)
{
using(SqlConnection con = new SqlConnection(......))
{
try
{
con.Open();
using(SqlTransaction tran = con.BeginTransaction())
{
return GetCSerieses(DeliveryReportObject, con, tran);
}
// Or, if you don't need a transaction you could call the
// overload passing null
// return GetCSerieses(DeliveryReportObject, con, null);
}
catch(Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
return null; // ?? or return new List<CSerieses>();
}
}
}
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject, SqlConnection co, SqlTransaction tran)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
// We don't own the connection and the transaction object.
// Whoever passed them to us is responsible of their disposal.
string query = "......";
SqlCommand command = new SqlCommand(query, co, tran);
command.Transaction = tran;
....
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}

SQLException : Login Failed for user "xx" when using SQLHelper ExecuteNonQuery

I have a problem when using the SQLHelper class to execute an update stored procedure. I am using SqlTransaction as parameters in SQLHelper.ExecuteNonQuery.
This is my code :
// Create SQLTransaction
public bool Delete()
{
SqlConnection oConn = tsoDAL.OpenConnection();
SqlTransaction oTrans = oConn.BeginTransaction();
try
{
if (Delete(oTrans))
{
oTrans.Commit();
return true;
}
else
{
oTrans.Rollback();
return false;
}
}
catch (SqlException ex)
{
oTrans.Rollback();
throw (ex);
}
finally
{
tsoDAL.CloseConnection(ref oConn);
}
}
// Call SQLHelper
public bool Delete(SqlTransaction p_oTrans)
{
try
{
SqlParameter[] oParams = new SqlParameter[1];
oParams[0] = new SqlParameter("#p_iSalesSoId", m_iSalesSoId);
int iRowAffected = SqlHelper.ExecuteNonQuery(p_oTrans, "uspTSO_DeleteSalesOrder",oParams);
return iRowAffected >= 0;
}
catch (Exception ex)
{
throw ex;
}
}
The code throws an error when it reaches this code in SQLHelper.cs:
private static SqlParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
using (SqlConnection cn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(spName,cn))
{
cn.Open(); // error happens here
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
if (!includeReturnValueParameter)
{
cmd.Parameters.RemoveAt(0);
}
SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];;
cmd.Parameters.CopyTo(discoveredParameters, 0);
return discoveredParameters;
}
}
Error that's shown is
Login Failed for User 'sa'.
I was searching for the solution for this problem, and I still didn't get the solution that can fix my problem.
I need your help, thank you
I have trace the problems and the really problem is SQLTransaction Connectionstring lost it password. So in my connectionstring i added
Persist Security Info=true; and thats solve my problem. Thank you

Opening SQL Server from c#

I have come across a tricky little problem and here and it is to do with opening a SQL Server database
The calling code is
public MainWindow()
{
InitializeComponent();
dbTools = new DataBaseTools();
if (dbTools.DbWorks)
{
label3.Text = "Worked";
}
else
{
label3.Text = "Try Again";
}
label3.AutoSize = true;
}
and the code for connecting to the server is
namespace LeatherCorset
{
public class DataBaseTools
{
private Boolean dbWorks;
private SqlConnection myConn;
public DataBaseTools(){
dbWorks = false;
InitialiseDatabase();
}
private void InitialiseDatabase(){
myConn = new SqlConnection();
String ConnString =
"Server=KEITH\\SQLEXPRESS;Database=Corset;Trusted_Connection=Yes";
myConn.ConnectionString = ConnString;
try{
if (myConn.State == ConnectionState.Open){
dbWorks = true;
}
}catch (SqlException ex) {
dbWorks = false;
}
}
public Boolean DbWorks{
get { return dbWorks; }
set { dbWorks = value; }
}
}
}
When I run the debugger it comes up with connString with having the value of null.
The name of the server is DESKTOP\SQLEXPRESS
The name of the database is Corset
The owner is Desktop\Keith
I am lost at this point in how to get to connect to SQL Server from c#
I would appreciate any advice and help
I don't see where you have opened the connection using Open(). Also, it is better practice here to initialize the SqlConnection with the correct string. Try something like
bool dbWorks = false;
sting cs = "Data Source=KIETH\\SQLEXPRESS;Initial Catalog=Corsit;Trusted_Connection=Yes";
using (SqlConnection conn = new SqlConnection(cs))
{
try
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
dbWorks = true;
}
}
}
I hope this helps.
Can't see how ConnString is null, I think you may be having some debugging issues, that said, try this:
String ConnString = "Server=KEITH\\SQLEXPRESS;Database=Corset;Trusted_Connection=Yes";
using (myConn = new SqlConnection(ConnString)) // This will make sure you actually close the DB
{
myConn.Open(); // You need to open the connection
try
{
if (myConn.State == ConnectionState.Open)
{
dbWorks = true;
}
}
catch (SqlException ex)
{
dbWorks = false;
}
}
I'd also recommend actually taking out the try/catch, because you're hiding an exception that may tell you everything that's going wrong.

How to determine an existing oracle database connection in C#?

Assuming that I call the method below with the right credentials:
private bool Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
bool isConnected = false;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
isConnected = true;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
conn.Close();
}//finally
return isConnected;
}
I have successfully open the connection in my method below:
private bool ValidateUserCode(string usercode)
{
UserAccountDefine def = new UserAccountDefine();
UserAccountService srvc = new UserAccountService();
UserAccountObj obj = new UserAccountObj();
bool returnVal = false;
bool isValid = Connect(def.DB_DUMMY_USERCODE, def.DB_DUMMY_PASSWORD);
if (isValid)
{
obj.SQLQuery = string.Format(def.SQL_LOGIN, usercode.ToLower(), DateTime.Now.ToString("MM/dd/yyy"));
DataTable dt = srvc.Execute(obj, CRUD.READALL);
if (dt.Rows.Count == 1)
{
returnVal = true;
}
}
return returnVal;
}
The question is how can I determine the connection status in ValidateUserCode() method?
How can I close it afterwards?
Note:
I explicitly declare the string variables in UserAccountDefine(); so you don't have to worry about that.
I already tried declaring a new OleDbConnection conn inside the ValidateUserCode() to but the conn.State always returning "Closed".
UPDATE
I have a system with 2-layer security feature. 1st is in application and 2nd is on database. If a user logs in to the application, the username and password is also used to log him/her in to the database. Now, the scenario is when a user forgot his/her password, we can't determine the fullname, email and contact (which are maintained in the database) of the user. I just know his usercode. To determine the contact details, I have to open an active connection using a DUMMY_ACCOUNT.
Note that I never maintain the password inside the database.
First of all, you call Close() in your finally block, which means that at any point in your second method, the connection would be closed. Moreover, even if you don't Close() it,since conn is a local variable in Connect(), when you're back in ValidateUserCode(), the connection is already up for garbage collection, and when it's Dispose()d, it also closes automatically.
I sugges you either make it a member, pass it as an out parameter, return it by the Connect() method (and return null for failure, or something, if you don't like exceptions)..or redesign the code.
private OleDbConnection Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
return conn;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
//you don't want to close it here
//conn.Close();
}//finally
return null;
}
I am not sure how this information helps you.
I had similar problem while using OLEDB connection for Excel Reading. I didn't knew the answer. So, just I added a global variable for OleDbConnection initialized to null.
In my method, I used to check that null, if not close it and again open it.
if (con != null)
{
con.Close();
con.Dispose();
}
try
{
con = new OleDbConnection(connectionString);
}
catch (Exception ex)
{
MessageBox.Show("oledbConnection = " + ex.Message);
}
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show("connection open = " + ex.Message + "\n");
}
I could able to continue after this. You can try, if it works for you its good!
I'm not sure I follow the question quite right. My answer is based on the premise that you want to open/retrieve a connection, take an action, and close/release the connection afterward.
The code you include does not do that well. Typical DAO code resembles this pseudocode, in my case taken from some boilerplate code I use.
public DataSet FetchDataSet(string sql, IDictionary paramHash) {
var cnn = AcquireConnection();
var rtnDS = new DataSet();
try
{
var cmd = cnn.CreateCommand();
cmd.CommandText = sql;
SetParameters(cmd, paramHash);
IDbDataAdapter ida = new DataAdapter { SelectCommand = cmd };
LogSql(sql, paramHash, "FetchDataSet");
ida.Fill(rtnDS);
}
catch (Exception ex)
{
DebugWriteLn("Failed to get a value from the db.", ex);
throw;
}
finally
{
ReleaseConnection(cnn);
}
return rtnDS;
}
Note that the code above is strictly about communicating with the database. There is no assessment of whether the data is right or wrong. You might have a DAO that is a subclass of the one that contains the above code, and it might do this:
public MyItemType FindSomeValue(long Id)
{
const string sql = #"SELECT something from somewhere where id=:id";
var myParams = new Dictionary<string, long> { { "id", Id } };
var ds = FetchDataSet(sql, myParams);
return (from DataRow row in ds.Tables[0].Rows
select new Item
{
Id = Convert.ToInt64(row["ID"], CultureInfo.InvariantCulture),
Name = row["NAME"].ToString()
}).FirstOrDefault();
}
In fact, the above is pseudocode from a DAO implementation that I've used for years. It makes data access relatively painless. Note that there is some real code behind those methods like SetParameters (30 - 80 lines or so), and I have a bunch of other protected methods like FetchScalar, ExecuteSQL, etc.

How to check is connection string valid?

I have to save data and I have to test connection before to save it. How can I test that this connection string is valid for a particular connection?
My code is like this:
static public bool TestConnString(string connectionString)
{
bool returnVal = true;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
if (conn.State != ConnectionState.Open)
returnVal = false;
else
returnVal = true;
}
catch (Exception ex)
{
returnVal = false;
}
}
return returnVal;
}
Connection string is:
Data Source=testSvr03\SQLEXPRESS;Initial Catalog=Test; Connection Timeout=600; Persist Security Info=True;User ID=Test; password=test
If I give wrong data source in connection String then it never returns in this function after conn.open() .I put catch block but it is coming in it
Can anyone Tell me what is solution?
You can let the SqlConnectionStringBuilder constructor check it:
bool isValidConnectionString = true;
try{
var con = new SqlConnectionStringBuilder("ABC");
}catch(Exception)
{
// can be KeyNotFoundException, FormatException, ArgumentException
isValidConnectionString = false;
}
Here's an overview of the ConnectionStringBuilders for the different data providers:
Provider ConnectionStringBuilder
System.Data.SqlClient System.Data.SqlClient.SqlConnectionStringBuilder
System.Data.OleDb System.Data.OleDb.OleDbConnectionStringBuilder
System.Data.Odbc System.Data.Odbc.OdbcConnectionStringBuilder
System.Data.OracleClient System.Data.OracleClient.OracleConnectionStringBuilder
You can put the return statement just in the catch block like this
static bool TestConnectionString(string connectionString)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
try
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
catch
{
return false;
}
}
return false;
}
I have just tried this. It works correctly (returns false value) if you call this function with empty string.
You can just try to open connection
SqlConnection myConnection = new SqlConnection(myConnString);
try
{
myConnection.Open();
}
catch(SqlException ex)
{
//Failure to open
}
finally
{
myConnection.Dispose();
}
You can do it in background thread
and you can set Timeout, If you don't want waiting long
This is what I ended up using:
private bool validateConnectionString(string connString)
{
try
{
var con = new SqlConnectionStringBuilder(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
}
catch
{
return false;
}
}
Try this. This is the easiest way to check a connection.
try
{
using(var connection = new OleDbConnection(connectionString)) {
connection.Open();
return true;
}
}
catch {
return false;
}
you mean connection string?
well, something like this maybe...
try
{
//....try to connect and save it here, if connection can not be made it will throw an exception
}
catch(Exception ex)
{
}
Create a connection object and try to open it.
An exception will be throw if the connection string is invalid.
Something like this:
using(var connection = New SqlConnection("..."))
{
connection.Open();
}

Categories

Resources