Stop Upload when a some data already exists - c#

I have an upload button that can upload excel file and save it to my database. What I want to happen is that if there's one or more data in that excel file that already existing the other data will also not be uploaded though it's not yet existing. My code for adding it to the database and upload button are below.
Add to database
private void AddNewTrainee(string strdelname, string strrank, string strcomp, string strcourse, string strcenter, string strinst,
string strsdate, string stredate, string strcissued, string strcnumber, string strremark, int recdeleted, string credate, string update, int fromupload)
{
connection.Open();
String checkDateAndName = "Select count(*) from Trainees where StartDate= '" + strsdate + "' and Delegate='" + strdelname + "' and REC_DELETED = 0 ";
SqlCommand cmd = new SqlCommand(checkDateAndName, connection);
int dataRepeated = Convert.ToInt32(cmd.ExecuteScalar().ToString());
bool boolDataRepated;
connection.Close();
if (!(dataRepeated >= 1))
{
boolDataRepated = false;
}
else
boolDataRepated = true;
connection.Open();
string certNumber = "Select * from CertID_Table update CertID_Table set CertificateID = CertificateID + 1 from CertID_Table ";
SqlCommand cmdCert = new SqlCommand(certNumber, connection);
using (SqlDataReader oReader = cmdCert.ExecuteReader())
{
while (oReader.Read())
{
string test1 = oReader["CertificateID"].ToString();
ViewState["certnumber"] = test1;
}
}
connection.Close();
strcnumber = (string)ViewState["certnumber"];
if (boolDataRepated == false)
{
string path = "D:\\Intern\\BASSWeb\\SQLCommands\\AddSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
try
{
connection.Open();
SqlCommand cmd1 = new SqlCommand(sql, connection);
cmd1.Parameters.AddWithValue("#delName", strdelname);
cmd1.Parameters.AddWithValue("#rank", strrank);
cmd1.Parameters.AddWithValue("#comp", strcomp);
cmd1.Parameters.AddWithValue("#course", strcourse);
cmd1.Parameters.AddWithValue("#center", strcenter);
cmd1.Parameters.AddWithValue("#instructor", strinst);
cmd1.Parameters.AddWithValue("#sdate", strsdate);
cmd1.Parameters.AddWithValue("#edate", stredate);
cmd1.Parameters.AddWithValue("#cissued", strcissued);
cmd1.Parameters.AddWithValue("#cnumber", strcnumber);
cmd1.Parameters.AddWithValue("#remark", strremark);
cmd1.Parameters.AddWithValue("#rdeleted", recdeleted);
cmd1.Parameters.AddWithValue("#cdate", credate);
cmd1.Parameters.AddWithValue("#udate", update);
cmd1.Parameters.AddWithValue("#fupload", fromupload);
cmd1.CommandType = CommandType.Text;
cmd1.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
}
else
{
string script = "alert(\"The data already exists\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
Upload Button
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/Datas/") + path);
String ExcelPath = Server.MapPath("~/Datas/") + path;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmdX = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmdX.ExecuteReader();
while (dr.Read())
{
delegateName = dr[0].ToString();
rankPos = dr[1].ToString();
company = dr[2].ToString();
courseTitle = dr[3].ToString();
trainingCenter = dr[4].ToString();
instructor = dr[5].ToString();
staDa = DateTime.Parse(dr[6].ToString());
string startDate = staDa.ToString("MM/dd/yyyy");
endDa = DateTime.Parse(dr[7].ToString());
string endDate = endDa.ToString("MM/dd/yyyy");
certIssued = dr[8].ToString();
certNum = dr[9].ToString();
remarks = dr[10].ToString();
recDeleted = 0;
dateCreated = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
dateUpdated = string.Empty;
fromUpload = 1;
AddNewTrainee(delegateName, rankPos, company, courseTitle, trainingCenter, instructor,
startDate, endDate, certIssued, certNum, remarks, recDeleted, dateCreated, dateUpdated, fromUpload);
}
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: " + ex.Message.ToString() + " \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
else
{
string errorMessage = "alert(\"ERROR: You have not specified a file \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
PopulateData();
}

You have to set the transferMode to 'Streamed', otherwise you will always get one file.
Have a look at this article: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-enable-streaming

I think there is a few things you'll need to tackle to reach your end goal.
Use a multiselect method and a get a post list of all files required
for upload.
Do your processing requirements in a Transaction
When your done processing, commit or rollback the transaction as necessary and keep the data you want.
Study the link I posted a little bit. At first transaction seem a little bit overwhelming, but they are actually very simple. Maybe I can help you get started in your understandings. There are really only three extra steps;
1.
Initialize a transaction object after you create a command.
SqlTransaction transaction = connection.BeginTransaction();
2.
On all of your Sql Commands (Inserts,updates, deletes ect) attach the transaction.
cmd.Transaction = transaction;
This will allow you to Execute the SqlCommands without actually putting them into your database. Lastly, when you've processed all of your inserts and updates you can do the final step. The using statement is not required, just good practice. That could be the next thing you'll want to understand it is very helpful.
3.
Commit all SqlCommands to the database.
transaction.Commit();
If at any point during your data processing, something goes wrong than you can rollback every transaction like this.
transaction.Rollback();

Related

Is there a way to validate the connection string if the server is closed or down?

I have problem regarding inserting the loop process. So when the connection string determine that the server is down, the inserting process stop looping. My question, is there way to determine whether this connection string is down or not? I have research they answer is to make if condition sqlconn.State == ConnectionState.Open I will show you guys the sample error that I encounter.
string connetionString = null;
MySqlConnection cnn;
connetionString = "server=localhost;database=sample_db_xx;uid=root;pwd=;";
cnn = new MySqlConnection(connetionString);
try
{
var arpp_pro = new List<string>();
cnn.Open();
MySqlCommand command = new MySqlCommand("SELECT store_id,CONCAT(boh,'\\\\sqlexpress') as boh FROM db_cua.stores WHERE " +
"is_active = 1 AND boh != '' ", cnn);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
arpp_pro.Add(reader[1].ToString());
}
}
cnn.Close();
foreach (var arpp_pro_data in arpp_pro)
{
string connetionString_SQL = #"Server=" + arpp_pro_data + " \sqlexpress;Database=Site5;User ID=sa;Password=dospos";
//#"Server=" + arpp_pro_data + ";Database=Site5;User ID=sa;Password=dospos";
var date_minus_one_day = DateTime.Today.AddDays(-1);
var formatted_date_minus_one_day = date_minus_one_day.ToString("yyyy-MM-dd");
var year = DateTime.Now.ToString("yyyy");
var month = DateTime.Now.ToString("MM");
var date = DateTime.Today.AddDays(-1);
var date_formatted = date.ToString("dd");
string get_sos_orders_details = #"SELECT
Convert(nvarchar(50),dbo.SOS_ORDERS.OrderId)+ '-'+ Convert(nvarchar(50),dbo.SOS_ORDERS.TransTime) + Convert(nvarchar(50),dbo.Sales.TransactionId)+ Convert(nvarchar(50),dbo.Sales.TotalDeptName) as result,
dbo.Sales.StoreId,
Convert(nvarchar(50),dbo.SOS_ORDERS.TransTime) as TransTime,
dbo.Transactions.OperatorName as Cashier,
dbo.Sales.TotalDeptName as Transaction_Type,
dbo.Sales.TransactionId,
(dbo.SOS_ORDERS.DTOT + dbo.SOS_ORDERS.ASSM) as Cashier_Time,
(dbo.SOS_ORDERS.KIT) as Preparation_Time,
(dbo.SOS_ORDERS.KIT + dbo.SOS_ORDERS.DTOT + dbo.SOS_ORDERS.ASSM) as Total_Time
FROM dbo.SOS_ORDERS INNER JOIN
dbo.Sales ON dbo.SOS_ORDERS.OrderId = dbo.Sales.StoredOrderIndex INNER JOIN
dbo.Transactions ON dbo.Sales.Sequence = dbo.Transactions.Sequence
where dbo.Sales.businessdate= #date_minus_one_day
OR(DATEPART(yy, dbo.SOS_ORDERS.TransTime) = #year
AND DATEPART(mm, dbo.SOS_ORDERS.TransTime) = #month
AND DATEPART(dd, dbo.SOS_ORDERS.TransTime) = #date_today )
AND(dbo.Sales.TotalDeptName in ('01 SALLE MANGER', '02 EMPORTER')
or dbo.Sales.TotalDeptName in ('01 DINE IN', '02 TAKE OUT'))
GROUP BY dbo.SOS_ORDERS.OrderId, dbo.Sales.StoreId, dbo.SOS_ORDERS.TransTime, dbo.SOS_ORDERS.DTOT, dbo.SOS_ORDERS.LINE, dbo.SOS_ORDERS.WIND, dbo.SOS_ORDERS.SERV, dbo.SOS_ORDERS.HOLD,
dbo.SOS_ORDERS.TOTL, dbo.SOS_ORDERS.ASSM, dbo.SOS_ORDERS.CASH, dbo.SOS_ORDERS.FTOT, dbo.SOS_ORDERS.PAY, dbo.SOS_ORDERS.KIT, dbo.Sales.TransactionId,
dbo.Transactions.OperatorName, dbo.Sales.TotalDeptName order by dbo.SOS_ORDERS.TransTime DESC";
using (SqlConnection sqlconn = new SqlConnection(connetionString_SQL))
{
sqlconn.Open();
if (sqlconn.State == ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand(get_sos_orders_details, sqlconn);
cmd.Parameters.AddWithValue("#date_minus_one_day", formatted_date_minus_one_day);
cmd.Parameters.AddWithValue("#year", year);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#date_today", date_formatted);
SqlDataReader rs = cmd.ExecuteReader();
while (rs.Read())
{
// access your record colums by using reader
Console.WriteLine(rs["StoreId"]);
cnn.Open();
MySqlCommand comm = cnn.CreateCommand();
comm.CommandText = #"INSERT INTO master_data.so_v2 (StoreId,TransTime,Cashier,Transaction_Type,TransactionId,Cashier_Time,Preparation_Time)
VALUES(#Storeid, #TransTime, #Cashier, #Transaction_Type, #TransactionId, #Cashier_Time, #Preparation_Time)";
comm.Parameters.AddWithValue("#Storeid", rs["StoreId"]);
comm.Parameters.AddWithValue("#TransTime", rs["TransTime"]);
comm.Parameters.AddWithValue("#Cashier", rs["Cashier"]);
comm.Parameters.AddWithValue("#Transaction_Type", rs["Transaction_Type"]);
comm.Parameters.AddWithValue("#TransactionId", rs["TransactionId"]);
comm.Parameters.AddWithValue("#Cashier_Time", rs["Cashier_Time"]);
comm.Parameters.AddWithValue("#Preparation_Time", rs["Preparation_Time"]);
comm.ExecuteNonQuery();
cnn.Close();
}
}
sqlconn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Thank you.
I suppose if all you wanted was a way to test and make sure a connection string is valid and that you can connect to the server and to the database, you could use a method like this:
public bool IsConnectionStringValid(string cs)
{
try
{
using (MySqlConnection conn = new MySqlConnection(cs))
{
conn.Open();
return true;
}
}
catch
{
return false;
}
}
Although I have to admit, in all my years of developing in C#, I've never used anything like this. Normally, as people have said in the comments, you already know before runtime that your connection string is valid and working.

c# mysql unable to output query to a textbox

here is my code:
private void searchInDatabase()
{
MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
MySqlCommand mcd;
MySqlDataReader mdr;
String query;
try
{
c.Open();
query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
mcd = new MySqlCommand(query, c);
mdr = mcd.ExecuteReader();
if(mdr.Read())
{
firstName.Text = mdr.GetString("first_name");
middleName.Text = mdr.GetString("middle_name");
lastName.Text = mdr.GetString("last_name");
age.Text = mdr.GetString("age");
}
else
{
MessageBox.Show("Result Not Found");
}
}
catch(Exception error)
{
MessageBox.Show("Error: "+error.Message);
}
finally
{
c.Close();
}
}
I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.
According to MSDN you need to pass the column number as parameter
public override string GetString(int i)
So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then
firstName.Text = mdr.GetString(0);
UPDATE
Try to use MySqlConnectionStringBuilder
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
First of all look at this sample of connection string and change your connection string:
'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;'
If connection is OK send erorr message or full exception.

Trapping error and keep trucking

I have written a c# monitoring program to check values in a database. It runs 4 separate checks then outputs the results (Winform).
It was all running great then last week the first check hit a problem and whole program stopped.
So my question is how would I trap any errors in any of the 4 checks and keep going/ trucking?
Can I do it with try catch or would this halt program?
Code Sample
bool bTestDate;
object LastDataDate;
//-- Check A - Table 1
OdbcConnection DbConnection = new OdbcConnection("DSN=EDATA");
try
{
DbConnection.Open();
}
catch (OdbcException ex)
{
Console.WriteLine("connection to the DSN '" + connStr + "' failed.");
Console.WriteLine(ex.Message);
return;
}
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = "SELECT NAME, UNAME, DATIME_ENDED FROM XPF WHERE NAME='XXXX'";
OdbcDataReader DbReader = DbCommand.ExecuteReader();
int fCount = DbReader.FieldCount;
string myBatch;
string myUser;
string myDate;
while (DbReader.Read())
{
Console.Write(":");
myBatch = DbReader.GetString(0);
myUser = DbReader.GetString(1);
myDate = DbReader.GetString(2);
myDate = myDate.Remove(myDate.Length - 10);
for (int i = 0; i < fCount; i++)
{
String col = DbReader.GetString(i);
Console.Write(col + ":");
}
tbxxx.Text = string.Format("{0:dd/M/yy H:mm:ss}", myDate);
bool TestDate;
TestDate = CheckDate(Convert.ToDateTime(myDate));
CheckVerif(TestDate, lblVerifixxx);
}
//-- Check B - Table 2
string cnStr = setConnectionString();
string mySQL = "Select Max(TO_DATE(TIME_ID, 'DD/MM/YYYY')) FROM table";
OracleConnection cn = new OracleConnection(cnStr);
cn.Open();
OracleCommand cmd = new OracleCommand(mySQL, cn);
LastDataDate = cmd.ExecuteScalar();
cmd.Dispose();
tbLastDate.Text = string.Format("{0:dd MMM yy}", LastDataDate);
bTestDate = CheckDate(Convert.ToDateTime(LastDataDate));
CheckVerif(bTestDate, lblVerif);
//-- Check C - Table 3
mySQL = "Select Max(xxx_DATE) from AGENT";
OracleCommand cmd2 = new OracleCommand(mySQL, cn);
LastDataDate = cmd2.ExecuteScalar();
cmd2.Dispose();
tbxxx2.Text = string.Format("{0:dd MMM yy}", LastDataDate);
bool TestDatex;
TestDatex = CheckDate(Convert.ToDateTime(LastDataDate));
CheckVerif(TestDatex, lblVerif2);
You can use a try catch block with the expected exceptions and a general one, just to be certain you catch them all and not throw the exception, therefore not halting the program.
try
{
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
// Least specific:
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
}
Check https://msdn.microsoft.com/en-us/library/0yd65esw.aspx

C# ASP.Net Processing Issue - Reading Table While Deleting Rows

Simply, I have an application that has one page that deletes and then re-adds/refreshes the records into a table every 30 seconds. I have another page that runs every 45 seconds that reads the table data and builds a chart.
The problem is, in the read/view page, every once in a while I get a 0 value (from a max count) and the chart shows nothing. I have a feeling that this is happening because the read is being done at the exact same time the delete page has deleted all the records in the table but has not yet refreshed/re-added them.
Is there a way in my application I can hold off on the read when the table is being refreshed?
Best Regards,
Andy
C#
ASP.Net 4.5
SQL Server 2012
My code below is run in an ASP.Net 4.5 built Windows service. It deletes all records in the ActualPlot table and then refreshes/adds new records from a text file every 30 seconds. I basically need to block (lock?) any user from reading the ActualPlot table while the records are being deleted and refreshed. Can you PLEASE help me change my code to do this?
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
// Open the SAP text files, clear the data in the tables and repopulate the new SAP data into the tables.
var cnnString = ConfigurationManager.ConnectionStrings["TaktBoardsConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(cnnString);
SqlConnection conndetail = new SqlConnection(cnnString);
SqlConnection connEdit = new SqlConnection(cnnString);
SqlCommand cmdGetProductFile = new SqlCommand();
SqlDataReader reader;
string sql;
// Delete all the records from the ActualPlot and the ActualPlotPreload tables. We are going to repopulate them with the data from the text file.
sql = "DELETE FROM ActualPlotPreload";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Delete Error:";
msg += ex.Message;
Library.WriteErrorLog(msg);
}
finally
{
conn.Close();
}
sql = "DELETE FROM ActualPlot";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Delete Error:";
msg += ex.Message;
Library.WriteErrorLog(msg);
}
finally
{
conn.Close();
}
// Read the SAP text file and load the data into the ActualPlotPreload table
sql = "SELECT DISTINCT [BoardName], [ProductFile], [ProductFileIdent] FROM [TaktBoards].[dbo].[TaktBoard] ";
sql = sql + "JOIN [TaktBoards].[dbo].[Product] ON [Product].[ProductID] = [TaktBoard].[ProductID]";
cmdGetProductFile.CommandText = sql;
cmdGetProductFile.CommandType = CommandType.Text;
cmdGetProductFile.Connection = conn;
conn.Open();
reader = cmdGetProductFile.ExecuteReader();
string DBProductFile = "";
string DBTischID = "";
string filepath = "";
string[] cellvalues;
DateTime dt, DateCheckNotMidnightShift;
DateTime ldSAPFileLastMod = DateTime.Now;
string MyDateString;
int FileRecordCount = 1;
while (reader.Read())
{
DBProductFile = (string)reader["ProductFile"];
DBTischID = (string)reader["ProductFileIdent"];
filepath = "c:\\inetpub\\wwwroot\\WebApps\\TaktBoard\\FilesFromSAP\\" + DBProductFile;
FileInfo fileInfo = new FileInfo(filepath); // Open file
ldSAPFileLastMod = fileInfo.LastWriteTime; // Get last time modified
try
{
StreamReader sr = new StreamReader(filepath);
FileRecordCount = 1;
// Populate the AcutalPlotPreload table from with the dates from the SAP text file.
sql = "INSERT into ActualPlotPreload (ActualDate, TischID) values (#ActualDate, #TischID)";
while (!sr.EndOfStream)
{
cellvalues = sr.ReadLine().Split(';');
if (FileRecordCount > 1 & cellvalues[7] != "")
{
MyDateString = cellvalues[7];
DateTime ldDateCheck = DateTime.ParseExact(MyDateString, "M/dd/yyyy", null);
DateTime dateNow = DateTime.Now;
string lsDateString = dateNow.Month + "/" + dateNow.Day.ToString("d2") + "/" + dateNow.Year;
DateTime ldCurrentDate = DateTime.ParseExact(lsDateString, "M/dd/yyyy", null);
string lsTischID = cellvalues[119];
if (ldDateCheck == ldCurrentDate)
{
try
{
conndetail.Open();
SqlCommand cmd = new SqlCommand(sql, conndetail);
cmd.Parameters.Add("#ActualDate", SqlDbType.DateTime);
cmd.Parameters.Add("#TischID", SqlDbType.VarChar);
cmd.Parameters["#TischID"].Value = cellvalues[119];
MyDateString = cellvalues[7] + " " + cellvalues[55];
dt = DateTime.ParseExact(MyDateString, "M/dd/yyyy H:mm:ss", null);
cmd.Parameters["#ActualDate"].Value = dt;
// Ignore any midnight shift (12am to 3/4am) units built.
DateCheckNotMidnightShift = DateTime.ParseExact(cellvalues[7] + " 6:00:00", "M/dd/yyyy H:mm:ss", null);
if (dt >= DateCheckNotMidnightShift)
{
cmd.ExecuteNonQuery();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
Library.WriteErrorLog(msg);
}
finally
{
conndetail.Close();
}
}
}
FileRecordCount++;
}
sr.Close();
}
catch
{ }
finally
{ }
}
conn.Close();
// Get the unique TischID's and ActualDate from the ActualPlotPreload table. Then loop through each one, adding the ActualUnits
// AcutalDate and TischID to the ActualPlot table. For each unique TischID we make sure that we reset the liTargetUnits to 1 and
// count up as we insert.
SqlCommand cmdGetTischID = new SqlCommand();
SqlDataReader readerTischID;
int liTargetUnits = 0;
string sqlInsert = "INSERT into ActualPlot (ActualUnits, ActualDate, TischID) values (#ActualUnits, #ActualDate, #TischID)";
sql = "SELECT DISTINCT [ActualDate], [TischID] FROM [TaktBoards].[dbo].[ActualPlotPreload] ORDER BY [TischID], [ActualDate] ASC ";
cmdGetTischID.CommandText = sql;
cmdGetTischID.CommandType = CommandType.Text;
cmdGetTischID.Connection = conn;
conn.Open();
readerTischID = cmdGetTischID.ExecuteReader();
DBTischID = "";
DateTime DBActualDate;
string DBTischIDInitial = "";
while (readerTischID.Read())
{
DBTischID = (string)readerTischID["TischID"];
DBActualDate = (DateTime)readerTischID["ActualDate"];
if (DBTischIDInitial != DBTischID)
{
liTargetUnits = 1;
DBTischIDInitial = DBTischID;
}
else
{
liTargetUnits++;
}
try
{
conndetail.Open();
SqlCommand cmd = new SqlCommand(sqlInsert, conndetail);
cmd.Parameters.Add("#ActualUnits", SqlDbType.Real);
cmd.Parameters.Add("#ActualDate", SqlDbType.DateTime);
cmd.Parameters.Add("#TischID", SqlDbType.VarChar);
cmd.Parameters["#TischID"].Value = DBTischID;
cmd.Parameters["#ActualDate"].Value = DBActualDate;
cmd.Parameters["#ActualUnits"].Value = liTargetUnits;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
Library.WriteErrorLog(msg);
}
finally
{
conndetail.Close();
}
}
conn.Close();
Library.WriteErrorLog("SAP text file data has been imported.");
}
If the data is being re-added right back after the delete (basically you know what to re-add before emptying the table), you could have both operation within the same SQL transaction, so that the data will be available to the other page only when it has been re-added.
I mean something like that :
public bool DeleteAndAddData(string connString)
{
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbTransaction tran = null;
try
{
conn.Open();
tran = conn.BeginTransaction();
OleDbCommand deleteComm = new OleDbCommand("DELETE FROM Table", conn);
deleteComm.ExecuteNonQuery();
OleDbCommand reAddComm = new OleDbCommand("INSERT INTO Table VALUES(1, 'blabla', 'etc.'", conn);
reAddComm.ExecuteNonQuery();
tran.Commit();
}
catch (Exception ex)
{
tran.Rollback();
return false;
}
}
return true;
}
If your queries don't take too long to execute, you can start the two with a difference of 7.5 seconds, as there is a collision at every 90 seconds when the read/write finishes 3 cycles, and read/view finishes 2 cycles.
That being said, it's not a fool-proof solution, just a trick based on assumptions, in case you wan't to be completely sure that read/view never happens when read/write cycle is happening, try considering having a Read Lock. I would recommend reading Understanding how SQL Server executes a query and Locking in the Database Engine
Hope that helps.
I would try a couple of things:
Make sure your DELETE + INSERT operation is occurring within a single transaction:
BEGIN TRAN
DELETE FROM ...
INSERT INTO ...
COMMIT
If this isn't a busy table, try locking hints your SELECT statement. For example:
SELECT ...
FROM Table
WITH (UPDLOCK, HOLDLOCK)
In the case where the update transactions starts while your SELECT statement is running, this will cause that transaction to wait until the SELECT is finished. Unfortunately it will block other SELECT statements too, but you don't risk reading dirty data.
I was not able to figure this out but I changed my code so the program was not deleting all the rows in the ActualPlot table but checking to see if the row was there and if not adding the new row from the text file.

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