Server version error while i am trying to connect to Heidisql - c#

I must connect one database present in HeidiSql to my .Net project in visual studio. When i debug my project while i am doing connection with db i obtain the error in the field Server Version with the description '.server Version has generated an exception of type System.InvalidOperationException '. Do you know what is the reason?
My connection string is :
<connectionStrings>
<add name="TicketDB"
connectionString="server=localhost;user id=root;password=Omega;database=crm6"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
The code is:
public void getNumberAllTicketOpen()
{
try
{
clDataBase ticketDB = new clDataBase();
string sQuery = "SELECT * from ticket";
DataTable ticket = ticketDB.ExecuteDataTable(sQuery, null, false);
Console.WriteLine("i am here!");
}
catch (Exception e)
{
Console.WriteLine("Errore : " + e.Message);
}
finally
{
}
}
public DataTable ExecuteDataTable(string CommandText, List<SqlParameter> Params = null, bool isStoredProcedure = true)
{
SqlConnection oCnn = null;
SqlCommand oCmd = null;
SqlDataAdapter oAdap = null;
try
{
**oCnn = new SqlConnection(this.connectionString);
oCnn.Open();** //this is the line that launch the error
oCmd = new SqlCommand(CommandText, oCnn);
if (isStoredProcedure)
oCmd.CommandType = System.Data.CommandType.StoredProcedure;
else
oCmd.CommandType = System.Data.CommandType.Text;
oCmd.CommandTimeout = this.commandTimeOut;
if (Params != null)
{
foreach (SqlParameter p in Params)
oCmd.Parameters.Add(p);
}
oAdap = new SqlDataAdapter(oCmd);
DataTable ResultTable = new DataTable();
oAdap.Fill(ResultTable);
return ResultTable;
}
catch (Exception ex)
{
logger.Error("Errore esecuzione " + CommandText, ex, MethodInfo.GetCurrentMethod().Name + " in " + MethodInfo.GetCurrentMethod().Module.Assembly.FullName);
throw;
}
}
oCnn = new SqlConnection(this.connectionString);
oCnn.Open(); //this is the line with error
Thank you for your help!

The error you are showing is an error encountered by the Visual Studio debugger attempting to view a property of a SqlConnection object.
The property in question is ServerVersion. I'm guessing the connection would only know what version of MySQL is running on the server when it actually manages to connect to the server, but at the point you've stopped the code, it hasn't connected yet. It doesn't make sense to return the server version at that point, so throwing an InvalidOperationException is an appropriate response.
I see exceptions like this in the VS debugger quite often. They are nothing to worry about. Not every property on every object is valid all the time.

I have resolved my problem.
I was trying to connect to a mySQL database but there were error in my code. I have resolved with the installation of the package MySql.Data with NuGet and the replacement in the code of SqlConnection, SqlCommand, SqlDataAdapter respectively with MysqlConnection, MySqlCommand, MySqlDataAdapter. Below i write the modified code:
public DataTable ExecuteDataTable(string CommandText, List<MySqlParameter> Params = null, bool isStoredProcedure = true)
{
MySqlConnection oCnn = null;
MySqlCommand oCmd = null;
MySqlDataAdapter oAdap = null;
try
{
oCnn = new MySqlConnection(this.connectionString);
oCnn.Open();
oCmd = new MySqlCommand(CommandText, oCnn);
if (isStoredProcedure)
oCmd.CommandType = System.Data.CommandType.StoredProcedure;
else
oCmd.CommandType = System.Data.CommandType.Text;
oCmd.CommandTimeout = this.commandTimeOut;
if (Params != null)
{
foreach (MySqlParameter p in Params)
oCmd.Parameters.Add(p);
}
oAdap = new MySqlDataAdapter(oCmd);
DataTable ResultTable = new DataTable();
oAdap.Fill(ResultTable);
return ResultTable;
}
catch (Exception ex)
{
logger.Error("Errore esecuzione " + CommandText, ex, MethodInfo.GetCurrentMethod().Name + " in " + MethodInfo.GetCurrentMethod().Module.Assembly.FullName);
throw;
}
finally
{
if (oCnn != null)
{
if (oCnn.State != System.Data.ConnectionState.Closed)
oCnn.Close();
oCnn.Dispose();
}
if (oAdap != null)
oAdap.Dispose();
if (oCmd != null)
oCmd.Dispose();
if (Params != null)
{
Params.Clear();
Params = null;
}
}

Related

Restore SQL Server database failed SMO C#

I'm trying to restore a SQL-Server database but I don't know why it's throwing exception which message is "Restore failed for server '.'".
I'm executing two methods. One is defines as CheckDatabase and second one is RestoreDatabase. If I execute RestoreDatabase method first it works fine, but if I execute it after CheckDatabase method it explodes
This is my CheckDatabase():
private static void CheckDatabase(string period)
{
string connString = Config.ConnectionStrings.ConnectionStrings["connString"].ConnectionString;
string controlProcesoCommand = "select top 5 * from ControlProceso order by FechaInicio desc;";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand command = new SqlCommand(controlProcesoCommand, conn))
{
try
{
conn.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
int lastPeriodDb = int.Parse(reader["Periodo"].ToString());
int actualPeriod = int.Parse(period);
if (period.Equals(reader["Periodo"].ToString()))
throw new Exception(Resources.Messages.Period_already_processed);
else if (lastPeriodDb > actualPeriod)
throw new Exception(Resources.Messages.Period_saved_after_actual_period);
else break;
}
reader.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
conn.Dispose();
command.Cancel();
command.Dispose();
}
}
}
And this is my RestoreDatabase():
private static void RestoreDatabase()
{
try
{
SqlConnection conn = new SqlConnection(Config.ConnectionStrings.ConnectionStrings["connString"].ConnectionString);
string dbName = conn.Database;
string restoreFilePath = Config.AppSettings.Settings["RestoreFilePath"].Value;
Server myServer = new Server(conn.DataSource);
Database itauDatabase = new Database(myServer, dbName);
Restore dbRestore = new Restore();
dbRestore.Action = RestoreActionType.Database;
dbRestore.Database = itauDatabase.Name;
dbRestore.Devices.AddDevice(restoreFilePath, DeviceType.File);
dbRestore.ReplaceDatabase = true;
dbRestore.SqlRestore(myServer);
}
catch (Exception ex)
{
throw ex;
}
}
Each method works fine when I execute them separated.
Thanks!

How can I specify a login\password at runtime to connect Oracle via EF6 in C#?

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"

The ConnectionString property has not been initialized using c# asp.net

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.

Retrieving a value from a C# DataLibrary to be placed in ASP.Net label

I have a DataClassLibrary attached to my ASP.Net project. I use it to access the database to get my values. I want to take the values given in the Line1 class and put them in the corresponding label. I tried DataLibraryClass.Line1 NewDataA = new DataLibraryClass.Line1(); but it gives me a zero I know that they have values. Could it be that my NewDataA = new is causing it to return zero? I also used breakpoints in the Line1 class and it never reaches the database query. How can I get the data I need into the labels properly?
DataLibraryClass
Line1:
var sqlString = new StringBuilder();
sqlString.Append("SELECT CaseNum6, CaseNum9, Group, Completion ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE Group = 1 OR Group = 2 ");
sqlString.Append("AND Completion = 0 ");
SqlDataReader reader = null;
SqlConnection dbConn = DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseNum6", CaseNum6 )};
try
{
reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
if (reader != null)
{
if (reader.Read())
{
CaseNum6 = (int)reader["CaseNum6"];
CaseNum9 = (int)reader["CaseNum9"];
Group = (int)reader["Group"];
Completion = (bool)reader["Completion"];
}
else
throw new Exception("No record returned");
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
DataLibraryClass
DBHelper:
private DBHelper() { }
public static SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
}
public static SqlConnection getFRESHConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["FRESHConnection"].ConnectionString);
}
public static SqlDataReader executeQuery(SqlConnection dbConn, string sqlString, SqlParameter[] parameters)
{
SqlCommand cmd = null;
SqlDataReader reader = null;
try
{
if (dbConn.State == ConnectionState.Closed)
dbConn.Open();
cmd = dbConn.CreateCommand();
cmd.CommandText = sqlString;
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
reader = cmd.ExecuteReader();
cmd.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return reader;
Code behind ASP page:
DataClassLibrary.LineAData NewDataA = new DataClassLibrary.LineAData();
DataClassLibrary.LineBData NewDataB = new DataClassLibrary.LineBData();
protected void Page_Load(object sender, EventArgs e)
{
L1.Text = NewDataA.CaseNum6.ToString();
L2.Text = NewDataA.CaseNum9.ToString();
L4.Text = NewDataB.CaseNum6.ToString();
L5.Text = NewDataB.CaseGNum9.ToString();
}
Upon setting up the webpage I failed to realize the behind code was set to .vb not .cs which is why everything was not working.

Why would ExecuteReader crash reading a specific data field of certain records, when ExecuteScalar works fine?

I've got an ASP.NET webforms site using C# and .NET 4.0.
I've created a class for loading information from a SQL table into an object, which has been working fine for a while. Recently a couple of specific records crash the SqlDataReader I use to populate this class with a database timeout error. I can't find any reason for these records to crash the reader.
I've isolated the crash to the [Address] int type datafield that when excluded from the query, the reader works fine. I've checked the database and the values stored are not unusual, and changing them to 0, null, or other working data, still results in a timeout error. If I call the fields using ExecuteScalar(), the data populates properly without error.
What could be causing this behavior?
Here is the content of the error:
Server Error in '/' Application.
A transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - The specified network name
is no longer available.)
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.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - The specified network name
is no longer available.)
Source Method
public void Populate(Guid UserId)
{
DAL db = new DAL();
using (SqlConnection con = db.GetConnection())
{
SqlCommand RowCount = new SqlCommand("SELECT COUNT([UserId]) FROM aspnet_Membership WHERE [UserId]=#UserId", con);
RowCount.Parameters.Add(new SqlParameter("#UserId", SqlDbType.UniqueIdentifier));
RowCount.Parameters["#UserId"].Value = UserId;
SqlDataReader rdr = null;
string sqlQuery = "SELECT [ApplicationId],[UserId],[Password],[PasswordFormat],[PasswordSalt],[MobilePIN],"+
"[Email],[LoweredEmail],[PasswordQuestion],[PasswordAnswer],[IsApproved],[IsLockedOut],[CreateDate],[LastLoginDate],[LastPasswordChangedDate],[LastLockOutDate]," +
"[FailedPasswordAttemptCount],[FailedPasswordAttemptWindowStart],[FailedPasswordAnswerAttemptCount],[FailedPasswordAnswerAttemptWindowStart],[Comment]," +
"[FirstName],[LastName],[Address] FROM aspnet_Membership WHERE [UserId]=#UserId";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, con);
sqlCommand.Parameters.Add(new SqlParameter("#UserId", SqlDbType.UniqueIdentifier));
sqlCommand.Parameters["#UserId"].Value = UserId;
try
{
con.Open();
int Rows = (int)RowCount.ExecuteScalar();
if (Rows > 0)
{
rdr = sqlCommand.ExecuteReader();
while (rdr.Read())
{
this.ApplicationId = (Guid)rdr["ApplicationID"];
this.UserId = (Guid)rdr["UserId"];
this.Password = common.Coalesce(rdr["Password"], "");
this.PasswordFormat = common.Coalesce(rdr["PasswordFormat"], 0);
this.PasswordSalt = common.Coalesce(rdr["PasswordSalt"], "");
this.MobilePIN = common.Coalesce(rdr["MobilePIN"], "");
this.Email = common.Coalesce(rdr["Email"], "");
this.LoweredEmail = common.Coalesce(rdr["LoweredEmail"], "");
this.PasswordQuestion = common.Coalesce(rdr["PasswordQuestion"], "");
this.PasswordAnswer = common.Coalesce(rdr["PasswordAnswer"], "");
this.IsApproved = (bool)rdr["IsApproved"];
this.IsLockedOut = (bool)rdr["IsLockedOut"];
this.CreateDate = common.Coalesce(rdr["CreateDate"], DateTime.Now);
this.LastLoginDate = common.Coalesce(rdr["LastLoginDate"], DateTime.Now);
this.LastPasswordChangedDate = common.Coalesce(rdr["LastPasswordChangedDate"], DateTime.Now);
this.LastLockOutDate = common.Coalesce(rdr["LastLockOutDate"], DateTime.Now);
this.FailedPasswordAttemptCount = common.Coalesce(rdr["FailedPasswordAttemptCount"], 0);
this.FailedPasswordAttemptWindowStart = common.Coalesce(rdr["FailedPasswordAttemptWindowStart"], DateTime.Now);
this.FailedPasswordAnswerAttemptCount = common.Coalesce(rdr["FailedPasswordAnswerAttemptCount"], 0);
this.FailedPasswordAnswerAttemptWindowStart = common.Coalesce(rdr["FailedPasswordAnswerAttemptWindowStart"], DateTime.Now);
this.Comment = common.Coalesce(rdr["Comment"], "");
this.FirstName = common.Coalesce(rdr["FirstName"], "");
this.LastName = common.Coalesce(rdr["LastName"], "");
this.Address = common.Coalesce(rdr["Address"], 0);
}
rdr.Close();
}
con.Close();
}
catch (Exception ex) { if (con != null) { con.Close(); } throw ex; }
finally { if (con != null) { con.Close(); } }
}
}
Here's the modified method that doesn't error.
public void Populate(Guid UserId)
{
DAL db = new DAL();
using (SqlConnection con = db.GetConnection())
{
SqlCommand RowCount = new SqlCommand("SELECT COUNT([UserId]) FROM aspnet_Membership WHERE [UserId]=#UserId", con);
RowCount.Parameters.Add(new SqlParameter("#UserId", SqlDbType.UniqueIdentifier));
RowCount.Parameters["#UserId"].Value = UserId;
SqlDataReader rdr = null;
string sqlQuery = "SELECT [ApplicationId],[UserId],[Password],[PasswordFormat],[PasswordSalt],[MobilePIN],"+
"[Email],[LoweredEmail],[PasswordQuestion],[PasswordAnswer],[IsApproved],[IsLockedOut],[CreateDate],[LastLoginDate],[LastPasswordChangedDate],[LastLockOutDate]," +
"[FailedPasswordAttemptCount],[FailedPasswordAttemptWindowStart],[FailedPasswordAnswerAttemptCount],[FailedPasswordAnswerAttemptWindowStart],[Comment]," +
"[FirstName],[LastName] FROM aspnet_Membership WHERE [UserId]=#UserId";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, con);
sqlCommand.Parameters.Add(new SqlParameter("#UserId", SqlDbType.UniqueIdentifier));
sqlCommand.Parameters["#UserId"].Value = UserId;
try
{
con.Open();
int Rows = (int)RowCount.ExecuteScalar();
if (Rows > 0)
{
rdr = sqlCommand.ExecuteReader();
while (rdr.Read())
{
this.ApplicationId = (Guid)rdr["ApplicationID"];
this.UserId = (Guid)rdr["UserId"];
this.Password = common.Coalesce(rdr["Password"], "");
this.PasswordFormat = common.Coalesce(rdr["PasswordFormat"], 0);
this.PasswordSalt = common.Coalesce(rdr["PasswordSalt"], "");
this.MobilePIN = common.Coalesce(rdr["MobilePIN"], "");
this.Email = common.Coalesce(rdr["Email"], "");
this.LoweredEmail = common.Coalesce(rdr["LoweredEmail"], "");
this.PasswordQuestion = common.Coalesce(rdr["PasswordQuestion"], "");
this.PasswordAnswer = common.Coalesce(rdr["PasswordAnswer"], "");
this.IsApproved = (bool)rdr["IsApproved"];
this.IsLockedOut = (bool)rdr["IsLockedOut"];
this.CreateDate = common.Coalesce(rdr["CreateDate"], DateTime.Now);
this.LastLoginDate = common.Coalesce(rdr["LastLoginDate"], DateTime.Now);
this.LastPasswordChangedDate = common.Coalesce(rdr["LastPasswordChangedDate"], DateTime.Now);
this.LastLockOutDate = common.Coalesce(rdr["LastLockOutDate"], DateTime.Now);
this.FailedPasswordAttemptCount = common.Coalesce(rdr["FailedPasswordAttemptCount"], 0);
this.FailedPasswordAttemptWindowStart = common.Coalesce(rdr["FailedPasswordAttemptWindowStart"], DateTime.Now);
this.FailedPasswordAnswerAttemptCount = common.Coalesce(rdr["FailedPasswordAnswerAttemptCount"], 0);
this.FailedPasswordAnswerAttemptWindowStart = common.Coalesce(rdr["FailedPasswordAnswerAttemptWindowStart"], DateTime.Now);
this.Comment = common.Coalesce(rdr["Comment"], "");
this.FirstName = common.Coalesce(rdr["FirstName"], "");
this.LastName = common.Coalesce(rdr["LastName"], "");
}
rdr.Close();
string sqlQuery2 = "SELECT [Address] FROM aspnet_Membership WHERE [UserId]=#UserId";
SqlCommand sqlCommand2 = new SqlCommand(sqlQuery2, con);
sqlCommand2.Parameters.Add(new SqlParameter("#UserId", SqlDbType.UniqueIdentifier));
sqlCommand2.Parameters["#UserId"].Value = UserId;
this.Address = common.Coalesce(sqlCommand2.ExecuteScalar(), 0);
}
con.Close();
}
catch (Exception ex) { if (con != null) { con.Close(); } throw ex; }
finally { if (con != null) { con.Close(); } }
}
}
You should show us more of your code than this, i assume that this is only a consequential error.
Normally opening already opened connections or closing already closed connections results in an Invalid Operation Exception and this is what you're doing here.
try{
con.Open();
//do something
con.Close(); //will be closed when no error was raised
}catch (Exception ex){
if (con != null){
// this will close if the error was raised in "do something"
con.Close();
}
throw ex; // you better thow the exception by throw (instead of throw ex) to keep the stacktrace
}finally {
if (con != null) {
// this will definitely cause an Invalid Operation Exception since the connection was already closed
con.Close();
}
}
You should instead use the using-statement to close and dispose the connection implicitely. If you want to close it manually, you should also check it's ConnectionState:
if (con != null && con.State != System.Data.ConnectionState.Closed){con.Close();}
An example which circumvents this with using-statement:
try{
using (var con = new System.Data.SqlClient.SqlConnection(conString)) {
using(var cmd = new System.Data.SqlClient.SqlCommand(command, con)){
con.open();
var reader = cmd.ExecuteReader();
while (reader.Read()) {
//do something
}
}
}//will automatically close connection
}
catch (Exception ex) {
//log exception and/or throw
throw;
}
I've modified your code a bit, cleaned it and added Using Statements. now the connections would close as they need to. BTW, you were trying to add a UserId parameter twice. Here's how it looks like now. a bit easier to read:
public void Populate(Guid UserId)
{
DAL db = new DAL();
using (SqlConnection con = db.GetConnection())
{
con.Open();
string sqlQuery = "SELECT [ApplicationId],[UserId],[Password],[PasswordFormat],[PasswordSalt],[MobilePIN]," +
"[Email],[LoweredEmail],[PasswordQuestion],[PasswordAnswer],[IsApproved],[IsLockedOut],[CreateDate],[LastLoginDate],[LastPasswordChangedDate],[LastLockOutDate]," +
"[FailedPasswordAttemptCount],[FailedPasswordAttemptWindowStart],[FailedPasswordAnswerAttemptCount],[FailedPasswordAnswerAttemptWindowStart],[Comment]," +
"[FirstName],[LastName],[Address] FROM aspnet_Membership WHERE [UserId]=#UserId";
using (SqlCommand sqlCommand = new SqlCommand(sqlQuery, con))
{
sqlCommand.Parameters.Add(new SqlParameter("#UserId", SqlDbType.UniqueIdentifier) { Value = UserId });
try
{
using (SqlDataReader rdr = sqlCommand.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
this.ApplicationId = (Guid)rdr["ApplicationID"];
this.UserId = (Guid)rdr["UserId"];
this.Password = common.Coalesce(rdr["Password"], "");
this.PasswordFormat = common.Coalesce(rdr["PasswordFormat"], 0);
this.PasswordSalt = common.Coalesce(rdr["PasswordSalt"], "");
this.MobilePIN = common.Coalesce(rdr["MobilePIN"], "");
this.Email = common.Coalesce(rdr["Email"], "");
this.LoweredEmail = common.Coalesce(rdr["LoweredEmail"], "");
this.PasswordQuestion = common.Coalesce(rdr["PasswordQuestion"], "");
this.PasswordAnswer = common.Coalesce(rdr["PasswordAnswer"], "");
this.IsApproved = (bool)rdr["IsApproved"];
this.IsLockedOut = (bool)rdr["IsLockedOut"];
this.CreateDate = common.Coalesce(rdr["CreateDate"], DateTime.Now);
this.LastLoginDate = common.Coalesce(rdr["LastLoginDate"], DateTime.Now);
this.LastPasswordChangedDate = common.Coalesce(rdr["LastPasswordChangedDate"], DateTime.Now);
this.LastLockOutDate = common.Coalesce(rdr["LastLockOutDate"], DateTime.Now);
this.FailedPasswordAttemptCount = common.Coalesce(rdr["FailedPasswordAttemptCount"], 0);
this.FailedPasswordAttemptWindowStart = common.Coalesce(rdr["FailedPasswordAttemptWindowStart"], DateTime.Now);
this.FailedPasswordAnswerAttemptCount = common.Coalesce(rdr["FailedPasswordAnswerAttemptCount"], 0);
this.FailedPasswordAnswerAttemptWindowStart = common.Coalesce(rdr["FailedPasswordAnswerAttemptWindowStart"], DateTime.Now);
this.Comment = common.Coalesce(rdr["Comment"], "");
this.FirstName = common.Coalesce(rdr["FirstName"], "");
this.LastName = common.Coalesce(rdr["LastName"], "");
this.Address = common.Coalesce(rdr["Address"], 0);
}
}
}
}
catch
{
throw;
}
}
}
}
UPD: i've edited the code, to ignore the counting of rows, and modified the line common.Coalesce(rdr["Address"], 0);
I think you need to run SQL Profiler and attach it to your database to watch the queries come across and get the responses.
You might also execute your query directly in Management Studio.
I'm wondering if there isn't a covering index that the first query is pulling data from that is somehow corrupted.
Either way, the profiler ought to give you a few more hints.
Regarding the initial rowcount select. I don't understand your comment about it being there to protect against dbnulls and program crashes. If a record doesn't exist for that ID then when the call to while(reader.read()) { .. } isn't going to enter that branch, which is all your rowcount test is preventing.

Categories