System.ArgumentException Value does not fall within the expected range, SQL issue - c#

I'm using .Net Compact 3.5 Windows 7 CE.
I have an application with about 50 users, I have it setup so that I would get an email every time a database transaction failed, with the query.
Every so often I would get an email with a stack trace that starts like this:
System.ArgumentException: Value does not fall within the expected range.
at System.Data.SqlClient.SqlParameterCollection.Validate(Int32 index, SqlParameter value)
at System.Data.SqlClient.SqlParameterCollection.AddWithoutEvents(SqlParameter value)
at System.Data.SqlClient.SqlParameterCollection.Add(SqlParameter value)
at MedWMS.Database.startSqlConnection(String query, SqlParameter[] parameters, SqlConnection connection, SqlCommand cmd)
at MedWMS.Database.<>c__DisplayClasse.b__8()
at MedWMS.Database.retry(Action action)
at MedWMS.Database.executeNonQuery(String query, SqlParameter[] parameters, String connectionString)...
The SQL query which causes this issue is not always the same. I run the same query seconds after I get the email in SQL Server Management Studio with no issues.
I would like to know why this could be happening. This is my first question on SO so please let me know if I'm doing something wrong. I would be happy to answer any questions to provide more detail.
This is a sample of the code that would cause this error:
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = new SqlParameter("#salesOrder", this.salesOrderNumber);
string query = #"
Select InvTermsOverride from SorMaster where SalesOrder = Convert(int, #salesOrder) and InvTermsOverride = '07' --07 is for COD";
DataTable dt = Database.executeSelectQuery(query, parameters, Country.getCurrent().getSysproConnectionStrReportServer());
This is the query that actually gets passed:
Select InvTermsOverride from SorMaster where SalesOrder = Convert(int, '000000001138325') and InvTermsOverride = '07' --07 is for COD
Here is the relevant methods from the Database class:
public static DataTable executeSelectQuery(String query, SqlParameter[] parameters, string connectionString)
{
DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = null;
try
{
retry(() =>
{
cmd = startSqlConnection(query, parameters, connection, cmd);
using (SqlDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
});
}
catch (Exception ex)
{
onDbConnectionCatch(cmd, ex);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
return dt;
}
public static void executeNonQuery(String query, SqlParameter[] parameters, string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = null;
try
{
retry(() =>
{
cmd = startSqlConnection(query, parameters, connection, cmd);
cmd.ExecuteNonQuery();
});
}
catch (Exception ex)
{
onDbConnectionCatch(cmd, ex);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
private static void retry(Action action)
{
int retryCount = 3;
int retryInterval = 1000;
Exception lastException = null;
for (int retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 0)
System.Threading.Thread.Sleep(retryInterval);
action();
lastException = null;
return;
}
catch (Exception ex)
{
lastException = ex;
}
}
if (lastException != null)
{
throw lastException;
}
}
private static SqlCommand startSqlConnection(String query, SqlParameter[] parameters, SqlConnection connection, SqlCommand cmd)
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
cmd = new SqlCommand(query, connection);
if (parameters != null)
{
foreach (SqlParameter sp in parameters)
{
if (sp != null)
{
cmd.Parameters.Add(sp);
}
}
}
return cmd;
}
private static void onDbConnectionCatch(SqlCommand cmd, Exception ex)
{
try
{
new BigButtonMessageBox("", "Unable connect to database").ShowDialog();
sendEmailWithSqlQuery(cmd, ex);
}
catch
{
}
}
private static void sendEmailWithSqlQuery(SqlCommand cmd, Exception ex)
{
string query2 = "cmd was null";
if (cmd != null)
{
query2 = cmd.CommandText;
foreach (SqlParameter p in cmd.Parameters)
{
query2 = query2.Replace(p.ParameterName, "'" + p.Value.ToString() + "'");
}
}
InternetTools.sendEmail("DB ERROR", ex.ToString() + "\r\n" + query2);
}

I had the same issue as Can't solve "Sqlparameter is already contained by another SqlparameterCollection"
For some reason SQL CE has a different error.
Because of my retry method, I couldn't reuse the SqlParameter object, still not sure why it's not allowed
Anyways I changed
cmd.Parameters.Add(sp);
to
cmd.Parameters.Add(sp.ParameterName, sp.Value);

Related

OracleCommand TimeOut not working in C# code

public int ExecuteNonQuery(IDbTransaction dbTransaction, string commandText, CommandType commandType, IDbDataParameter[] parameters)
{
int returnValue = 0;
try
{
var command = database.CreateCommand(commandText, commandType, dbTransaction.Connection);
if (parameters != null)
{
foreach (var parameter in parameters)
{
//check for derived output value with no value assigned
if ((parameter.Direction == ParameterDirection.InputOutput) && (parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
command.CommandTimeout = 600;
returnValue = command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
return returnValue;
}
I am trying to execute db executing using above code through c# window service through Oracle.ManagedDataAccess library. Database is Oracle 11g. Problem here is that Command Timeout is not working even when query is taking more than 15 mins to execute.
Please guide how to make it work?

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;
}

Returning MySqlDataReader

I want to return the value so on the caller i can use for example asd["columnname"] but im getting one error, example/code below.
I have this code
public static MySqlDataReader QueryResultadoMultString(string Query)
{
using (var conn = new MySqlConnection(myConnectionString))
{
try
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = Query;
MySqlDataReader myReader = null;
myReader = cmd.ExecuteReader();
if (myReader.HasRows)
{
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
return myReader;
}
}
return myReader;
}
catch (MySqlException ex)
{
NAPI.Util.ConsoleOutput($"[BaseDados][Erro] {ex.Message}");
return null;
}
}
}
Below is the caller
var asd = BaseDadosSQL.QueryResultadoMultString($"SELECT `socialclub`,`username`,`password` FROM contas WHERE socialclub = '{player.SocialClubName}'");
Console.WriteLine("Result "+asd["username"]);
I'm getting this error
System.Exception: 'No current query in data reader'
The method as written will force you to write code that is horribly vulnerable to sql injection issues. You need a separate set of arguments for parameters.
You want something more like this (which should also fix the issue in your question):
public static class BaseDadosSQL
{
private static string connectionString = "connection string here";
public static IEnumerable<IDataRecord> QueryResult(string Query, params MySqlParameter[] parameters)
{
using (var conn = new MySqlConnection(connectionString))
using (var cmd = new MySqlCommand(Query, conn))
{
if (parameters is object && parameters.Length > 0)
{
cmd.Parameters.AddRange(parameters);
}
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return reader;
}
}
}
}
}
And then call it like this:
//Guessing at type and length here. Use the actual type and length from the database
var p = new MySqlParameter("#SocialClub", MySqlDbType.VarString, 20);
p.Value = player.SocialClubName;
try
{
var asd = BaseDadosSQL.QueryResult($"SELECT `socialclub`,`username`,`password` FROM contas WHERE socialclub = #SocialClub", p);
foreach(var result in asd)
{
Console.WriteLine("Result " + result["username"]);
}
}
catch (MySqlException ex)
{
NAPI.Util.ConsoleOutput($"[BaseDados][Erro] {ex.Message}");
}
This code will let you use Social Club names which includes apostrophes. The original would have blown up. Notice I also moved the exception handling out of the DB code.
Ideally, even the QueryResult() method should also be private, with the BaseDadosSQL class having a separate public method for each query you need to run. So it would look more like this:
public static class BaseDadosSQL
{
private static string connectionString = "connection string here";
private static IEnumerable<IDataRecord> QueryResult(string Query, params MySqlParameter[] parameters)
{
using (var conn = new MySqlConnection(connectionString))
using (var cmd = new MySqlCommand(Query, conn))
{
if (parameters is object && parameters.Length > 0)
{
cmd.Parameters.AddRange(parameters);
}
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return reader;
}
}
}
}
public static IEnumerable<IDataRecord> GetClubLogin(string clubName)
{
//Still guessing at type and length here.
var p = new MySqlParameter("#SocialClub", MySqlDbType.VarString, 20);
p.Value = clubName;
return QueryResult($"SELECT `socialclub`,`username`,`password` FROM contas WHERE socialclub = #SocialClub", p);
}
}
And then called like this:
try
{
foreach(var result in BaseDadosSQL.GetClubLogin(player.SocialClubName))
{
Console.WriteLine("Result " + result["username"]);
}
}
catch (MySqlException ex)
{
NAPI.Util.ConsoleOutput($"[BaseDados][Erro] {ex.Message}");
}
Finally, it's really Really REALLY BAD to store passwords like that. So bad, it's not even okay for testing/learning/proof of concept code. NEVER DO THAT! It's not even okay to store passwords encrypted. Encryption is not good enough.
Passwords should only ever be stored as a fixed-length, salted, cryptographic (not-MD5) hash value. When someone tries to login, you salt and hash the attempted credential, and then compare the hash values, not the actual password. Anything else is just begging to end up on the front page of your newspaper of choice as the latest big data breach.

Connection open and Close issue in Sql Connection

Find to many solution but not a single solution fit on my scenario.
Problem: I am working on online software which is build under asp.net. From the past few days my application is working slow and some time its crash. When I try to find the issue, then I find that connection pool have connections which are in sleeping mode. I know that some connection are open but not closed properly. In below I will show you My DBManager file. Please review it and give me suggestion which can help me to open and close my connection properly.
Note: exception on connection is thrown when user use application fastly.
My application use many data entry operator which are type with speed. And move between pages again and again.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
/// <summary>
/// Summary description for DBManager
/// </summary>
public class DBManager
{
public static SqlConnection _connection;
public static SqlCommand _command;
public static SqlDataReader _reader;
public static SqlDataAdapter _dataAdapter;
public List<SqlParameter> Parameters = new List<SqlParameter>();
public static string _connectionString = "DefaultConnectionString";
SqlTransaction _sqlTransaction;
public DBManager()
{
// TODO: Add constructor logic here
}
public DBManager(SqlTransaction sqlTransaction = null)
{
_sqlTransaction = sqlTransaction;
}
public DBManager(string connectionStringName, SqlTransaction sqlTransaction = null)
{
_connectionString = connectionStringName;
_sqlTransaction = sqlTransaction;
}
public static string CreateConnection()
{
string ConnectionString = ConfigurationManager.ConnectionStrings[_connectionString].ConnectionString;
_connection = new SqlConnection(ConnectionString);
_connection.Open();
return "0";
}
public static void CloseConnection()
{
_connection.Close();
_connection.Dispose();
}
public void AddParameter(string parameterName, object value, SqlDbType sqlDbType, int size)
{
SqlParameter parameter = new SqlParameter(parameterName, sqlDbType, size);
parameter.Value = value;
Parameters.Add(parameter);
}
public void AddParameter(string parameterName, object value, SqlDbType sqlDbType, int size,ParameterDirection parameterDirection)
{
SqlParameter parameter = new SqlParameter(parameterName, sqlDbType, size);
parameter.Value = value;
parameter.Direction = parameterDirection;
Parameters.Add(parameter);
}
public void AddParameter(string parameterName, object value)
{
SqlParameter parameter = new SqlParameter(parameterName,value);
Parameters.Add(parameter);
}
public int ExecuteNonQuery(string procedureName)
{
int result = 0;
try
{
// if (CreateConnection() == "1") { return 0; }
CreateConnection();
_command = new SqlCommand(procedureName, _connection);
if (Parameters.Count != 0)
{
for (int i = 0; i < Parameters.Count; i++)
{
_command.Parameters.Add(Parameters[i]);
}
}
_command.CommandType = CommandType.StoredProcedure;
result = _command.ExecuteNonQuery();
CloseConnection();
_command.Dispose();
}
catch (Exception)
{
CloseConnection();
_command.Dispose();
throw;
}
return result;
}
public SqlDataReader ExecuteReader(string procedureName)
{
SqlDataReader reader;
try
{
CreateConnection();
// if (CreateConnection() == "1") { return reader=0; }
_command = new SqlCommand(procedureName, _connection);
if (Parameters.Count != 0)
{
for (int i = 0; i < Parameters.Count; i++)
{
_command.Parameters.Add(Parameters[i]);
}
}
_command.CommandType = CommandType.StoredProcedure;
reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
CloseConnection();
_command.Dispose();
}
catch (Exception)
{
CloseConnection();
_command.Dispose();
throw;
}
return reader;
}
public DataSet ExecuteDataSet(string procedureName)
{
DataSet dataSet = new DataSet();
try
{
CreateConnection();
_command = new SqlCommand(procedureName, _connection);
if (Parameters.Count != 0)
{
for (int i = 0; i < Parameters.Count; i++)
{
_command.Parameters.Add(Parameters[i]);
}
}
_command.CommandType = CommandType.StoredProcedure;
_dataAdapter = new SqlDataAdapter(_command);
_dataAdapter.Fill(dataSet);
CloseConnection();
_command.Dispose();
_dataAdapter.Dispose();
}
catch (Exception)
{
CloseConnection();
_dataAdapter.Dispose();
_command.Dispose();
throw;
}
return dataSet;
}
public DataTable ExecuteDataTable(string procedureName)
{
DataTable dataTable = new DataTable();
try
{
CreateConnection();
_command = new SqlCommand(procedureName, _connection);
if (Parameters.Count != 0)
{
for (int i = 0; i < Parameters.Count; i++)
{
_command.Parameters.Add(Parameters[i]);
}
}
_command.CommandType = CommandType.StoredProcedure;
_dataAdapter = new SqlDataAdapter(_command);
_dataAdapter.Fill(dataTable);
CloseConnection();
_command.Dispose();
_dataAdapter.Dispose();
}
catch (Exception)
{
CloseConnection();
_dataAdapter.Dispose();
_command.Dispose();
throw;
}
return dataTable;
}
public string ExecuteScalar(string procedureName)
{
string result = "";
try
{
CreateConnection();
_command = new SqlCommand(procedureName, _connection);
if (Parameters.Count != 0)
{
for (int i = 0; i < Parameters.Count; i++)
{
_command.Parameters.Add(Parameters[i]);
}
}
_command.CommandType = CommandType.StoredProcedure;
result = _command.ExecuteScalar().ToString();
CloseConnection();
_command.Dispose();
}
catch (Exception)
{
CloseConnection();
_command.Dispose();
throw;
}
return result;
}
}
Exceptions are:
InnerException System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is connecting.
at System.Data.SqlClient.SqlConnection.
InnerException System.InvalidOperationException: Invalid operation. The connection is closed.
at System.Data.ProviderBase.DbConnectionClosed.
InnerException System.NullReferenceException: Object reference not set to an instance of an object.
You are doing it wrong way all together , you should create connection but should not open it , you should open it when needed and close it
I suggest remove this function also and just make use of using
public static string CreateConnection()
{
string ConnectionString = ConfigurationManager.ConnectionStrings[_connectionString].ConnectionString;
_connection = new SqlConnection(ConnectionString);
//remove this line
//_connection.Open();
return "0";
}
you dont need this function also
public static void CloseConnection()
{
_connection.Close();
_connection.Dispose();
}
make use of using as suggested that will help
Best way I suggest is always make use of using and dispose conenction , as below
using(SqlConnection con = new SqlConnection() )
{
}
If you are worrying about it will create too many object, then for information connection with database is pooled means you can sepecify connection pooling information in connection string, so that way you dont have to worry about making connection when you create connection object.
<add name="sqlConnectionString" connectionString="Data
Source=mySQLServer;Initial Catalog=myDatabase;Integrated
Security=True;Connection Timeout=15;Connection Lifetime=0;Min Pool Size=0;Max
Pool Size=100;Pooling=true;" />
above is connection string which take cares of pooling
Sample code , this i how i did in my poroject , if you see the code i disponse connection object every time by making use of using
public class DbHelper
{
#region Private methods
private static OracleConnection GetConnection()
{
string connectionString = DbConnectionString.ConnectionString;
return new OracleConnection(connectionString);
}
private static OracleCommand GetCommand(OracleConnection connection, string commandText, OracleParameter[] param, bool isProcedure)
{
OracleCommand dbCommand = new OracleCommand();
dbCommand.Connection = connection;
dbCommand.CommandText = commandText;
if (param != null)
dbCommand.Parameters.AddRange(param);
if (isProcedure)
dbCommand.CommandType = CommandType.StoredProcedure;
return dbCommand;
}
#endregion
#region public methods
public static DataTable GetDataTable(string commandText, OracleParameter[] odbcPrams, bool isProcedure = false)
{
DataTable dt = new DataTable();
using (OracleConnection ODBCConn = GetConnection())
{
using (OracleCommand dbCommand = GetCommand(ODBCConn, commandText, odbcPrams, isProcedure))
{
ODBCConn.Open();
OracleDataAdapter da = new OracleDataAdapter(dbCommand);
da.Fill(dt);
}
}
return dt;
}
#endregion
}

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

Categories

Resources