update statement not updating data in db - c#

I am trying to update the data using an UPDATE statement. I am not getting any run time errors. However, no data is being updated in the database. Looks like something is missing in the WHERE clause.
try
{
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.AppSettings["RL_InventoryConnection"])) /*"*/
{
if (con.State == ConnectionState.Closed)
con.Open();
MySqlCommand cmd = new MySqlCommand("UPDATE vendormaster SET vendor_name = #vendor_name, vendor_contact_Name1 = #vendor_contact_Name1, vendor_contact_phone1 = #vendor_contact_phone1, vendor_contact_email1 = #vendor_contact_email1, vendor_contact_Name2 = #vendor_contact_Name2, vendor_contact_phone2 = #vendor_contact_phone2, vendor_contact_email2 = #vendor_contact_email2, vendor_pan = #vendor_pan, vendor_gst = #vendor_gst, vendor_address = #vendor_address, vendor_pincode = #vendor_pincode, vendor_city = #vendor_city, vendor_country = #vendor_country WHERE vendor_name like '%#vendor_name%'; ", con);
cmd.Parameters.AddWithValue("#vendor_name", getvendorname);
cmd.Parameters.AddWithValue("#vendor_contact_Name1", getcontactperson1);
cmd.Parameters.AddWithValue("#vendor_contact_phone1", getcontactphone1);
cmd.Parameters.AddWithValue("#vendor_contact_email1", getcontactemail1);
cmd.Parameters.AddWithValue("#vendor_contact_Name2", getcontactperson2);
cmd.Parameters.AddWithValue("#vendor_contact_phone2", getcontactphone2);
cmd.Parameters.AddWithValue("#vendor_contact_email2", getpersonemail2);
cmd.Parameters.AddWithValue("#vendor_pan", getvendorPan);
cmd.Parameters.AddWithValue("#vendor_gst", getvendorgst);
cmd.Parameters.AddWithValue("#vendor_address", getvendoraddress);
cmd.Parameters.AddWithValue("#vendor_pincode", getpincode);
cmd.Parameters.AddWithValue("#vendor_city", getcity);
cmd.Parameters.AddWithValue("#vendor_country", getcountry);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}

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!

Update sql database using dataset

I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}

How to call a stored procedure using ADO.NET?

private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****";
conn.Open();
SqlCommand cmd = new SqlCommand();
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
//cmd.CommandText = "Select ChatRoomID=#ChatRoomID,ChatRoomName=#ChatRoomName from tblChatRoom";
//cmd.Connection = conn;
SqlDataAdapter adapt = new SqlDataAdapter("Chatroomapp",conn);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds=new DataSet();
DataTable dt = new DataTable();
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
adapt.Fill(ds, "tblChatRoom");
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
catch (Exception ex)
{
MessageBox.Show("Error", ex.Message);
}
}
While compiling the program I got only connection fails message box, in the database. I found correct, how to overcome the program to get the connection succeeded message box.
Well, you're filling the ds data set - but then you're checking the dt data table for presence of rows... that's never going to work, of course!
If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet. Also, put your SqlConnection and SqlCommand into using blocks like this:
using (SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****"))
using (SqlCommand cmd = new SqlCommand("Chatroomapp", conn))
{
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
// fill the data table - no need to explicitly call `conn.Open()` -
// the SqlDataAdapter automatically does this (and closes the connection, too)
DataTable dt = new DataTable();
adapt.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
And just because you get back no rows in dt.Rows doesn't necessarily mean that your connection failed..... it could just be that there are no rows that match your search critieria! The connection worked just fine - but the SQL command just didn't return any rows.
Connection failed means that something went wrong between your program and the database. No records returned does not mean that the connection failed. It just means that your table is empty - it contains no records.
Using ADO.NET and a stored procedures would have been a little different from what you have done it. If you need to check if the connection failed, maybe it is better to check the type of exception that is returned in the catch part.
Below is how I would have done it. I would have created a separate method that would have handled my call, and then in your button1_Click I would have just called this method:
public async Task<ChatRoom> GetAsync(string chatRoomId, string chatRoomName)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
await sqlConnection.OpenAsync();
using (SqlCommand sqlCommand = new SqlCommand("ChatRooms_Get", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomID", chatRoomId));
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomName", chatRoomName));
using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
ChatRoom chatRoom = null;
if (await sqlDataReader.ReadAsync())
{
chatRoom = new ChatRoom();
chatRoom.Id = sqlDataReader.GetFieldValue<string>(0);
chatRoom.Name = sqlDataReader.GetFieldValue<string>(1);
chatRooms.Add(chatRoom);
}
return chatRoom;
}
}
}
}
catch (Exception exception)
{
// Try checking if the connection failed here
throw exception;
}
}
My chat room domain model could have looked like this:
public class ChatRoom
{
public string Id { get; set; }
public string Name { get; set; }
}
And the stored procedure would have looked like this:
CREATE PROCEDURE [dbo].[ChatRooms_Get]
(
#ChatRoomID VARCHAR(100),
#ChatRoomName VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
ChatRoomID,
ChatRoomName
FROM
tblChatRoom
WHERE
ChatRoomID = #ChatRoomID
AND ChatRoomName = #ChatRoomName;
END
GO
And then in the calling method you would get the chatroom and do with it whatever you need to do with it. For this example I just checked if it exists or not:
try
{
ChatRoom chatRoom = await chatRoomRepository.GetAsync(chatRoomId, chatRoomName);
if (chatRoom != null)
{
MessageBox.Show("Record found");
}
else
{
MessageBox.Show("No record found");
}
}
catch (Exception exception)
{
throw exception;
}
I hope this can help.

How to using oracledataadapter with transaction?

I use a method to gettable using a Select statiments.When i use a select statiment using a link database i got error (ORA-01453 SET TRANSATION must be first statement of transation.)
I know solition but i cant use Transaction methot with Oracledataadapter.
I want to use Commit() ... Rollback().
This is my code:
private System.Data.DataTable GetDataTable_(string SqlStatement, bool fromProcCall)
{
OracleConnection Con = new OracleConnection();
try
{
Con = Connection();
OpenConnection(Con, fromProcCall);
//-----------------------------------------
DateTime startTime = DateTime.Now;
//-----------------------------------------
DataSet ds = new DataSet();
OracleDataAdapter sda = new OracleDataAdapter(SqlStatement, Con);
sda.Fill(ds, "tbl1");
//-----------------------------------------
if (!fromProcCall)
DurationOfIfsAction = DateTime.Now.Subtract(startTime).Milliseconds;
else
DurationOfFirstIfsAction = DateTime.Now.Subtract(startTime).Milliseconds;
//-----------------------------------------
CloseConnection(Con);
return ds.Tables[0];
}
catch (Exception ex)
{
if (Con != null)
{
try
{
CloseConnection(Con);
}
catch (Exception) { }
}
throw new Exception("ERROR[" + ex.Message + "]");
}
}
Basically, you could do something like this:
oraConn = new OracleConnection("CONNECTION STRING");
oraConn.Open();
//Command with transaction
OracleCommand oraCom = oraConn.CreateCommand();
oraCom.CommandText = "INSERT QUERY";
oraCom.Transaction = oraCom.Connection.BeginTransaction(IsolationLevel.ReadCommitted);
//Execute
if (oraCom.Connection.State == ConnectionState.Closed)
{
oraCom.Connection.Open();
}
oraCom.ExecuteNonQuery();
//Commit / Rollback
oraCom.Transaction.Commit(); // or oraCom.Transaction.Rollback();
To use this with DataAdapter, the concept is the same: Create the transaction setting the DataAdapter.SelectCommand.Transaction and then you can control with Commit() and Rollback().

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