"Cannot find Table[0]" - Only in production? - c#

Some code on our production server is suddenly giving us some trouble. Production has not been changed in about a year, and I've confirmed that the database has not changed either.
If I run the same code on my machine (Yay Source Control!), I do not get the error that appears in production and everything works fine. I'll post the code below, but there has to be something else going on.
Correct me if I'm wrong, but if there is no Table[0], that means my query isn't returning any data. Yet, running the same query directly through SQL Management Studio gives me the data I want.
var ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
var ddlDataSet = GetAdds();
}
private List<tAdd> GetAdds()
{
var ds = GetData(queryString);
var aList = new tAdd[ds.Tables[0].Rows.Count];//THIS IS WHERE ERROR HITS
//Do other stuff
...
}
private DataSet GetData(string queryString)
{
var connectionString =
ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
var ds = new DataSet();
try
{
var connection = new SqlConnection(connectionString);
var adapter = new SqlDataAdapter(queryString, connection);
adapter.Fill(ds);
}
catch (Exception ex)
{
ErrorPanel.Visible = true;
ErrorPanel.Enabled = true;
SearchPanel.Enabled = false;
const string NotificationsEmail = "mailto:emailguy#email.com";
ErrorAlertLabel.Text =
"An err happened. " +
"Please contact the people who do stuff ";
ErrorAlertLabel.Visible = true;
ErrorMessageLiteral.Text = "<br />" + "<br />" +
"Message: " + ex.Message + "<br />" +
"StackTrace: " + ex.StackTrace + "<br />" +
"Inner Exception: " + ex.InnerException + "<br />" +
"Full Detals: " + ex + "<br />";
ErrorMessageLiteral.Visible = true;
}
return ds;
}
I may just try republishing the same version again, but who knows if that will fix it. If anyone needs more info please let me know and thank you in advance.
Actual Error Text: "System.IndexOutOfRangeException: Cannot find table 0."

I think you still have a flaw in your error handling that got exposed.
In GetData, you catch any Exception that occurs and set a bunch of UI elements to Visible and populate them with information, but you don't stop the process from continuing. GetData just continues on after the catch block, and returns an empty DataSet. GetAdds is oblivious to the fact that an error occured, tries to access a table in the DataSet that doesn't exist, and throws another exception that is not handled by your code, but is instead handled by ASP.NET, which throws away all of your error information and just shows a generic error page.
I would not use such detailed error handling within a low-level method, but add more global error handling. Since you don't add any meaningful information to the exception, I would just let it bubble up and handle it at the application level.
If you want to add more information to a low-level exception, throw a new exception with more detail, and assign the original exception to the new exception's InnerException property.

Please check whether you have any pdb files in production , if you dont have them than go to your project right click on properties under Build -> Advanced -> debug info -> pdb build this and please run it production,
If you have these than you can get the exact line where it is breaking.
This might occure,if there is a dead lock on the tables on production. or the permissions are missing.

Got it working today. I finally got a-hold of our Web Admin and asked him to restart the web server - this after I'd confirmed that my code and the DB were not the problem.
As soon as the web server booted back up everything was working fine. There are quite a few applications running on the server, so it may have been something getting tangled up.

Related

"database is locked" C# & SQLite

I keep getting this exception over and over. I've tried separating my query into two separate queries, that didn't work. I've checked to make sure the db connection is closed elsewhere before it's opened during this method, it's definitely closed before the function is called and opened before any queries.
Below iss the code for the function. I've set breakpoints and the query itself is fine. The code is the exact same that I used previously for updating a PIN function, with just the query string changed, so I don't know why it's causing issues:
Code:
public void transferMoney(string senderIban, decimal senderBalance, string receiverIban, decimal transferAmount,string messageOptional)
{
//myBankAccount.AccountPin = updatedPin;
DataTable dtUser = new DataTable();
sqlconnConnection.Open();
string strQuery2 = #"UPDATE Accounts SET Balance = Balance + " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + receiverIban + "';"
+ "UPDATE Accounts SET Balance = Balance - " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + senderIban + "';";
// example of a Paramaterised SQL statement.
SQLiteCommand sqlcomCommand2 = new SQLiteCommand(strQuery2, sqlconnConnection);
SQLiteDataAdapter sqldatadptAdapter = new SQLiteDataAdapter(sqlcomCommand2); // local SQL data Adaptor
try
{
// sqldatadptAdapter.Fill(dtUser);
sqlcomCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
// Exception will the "thrown" when there was a problem
throw new Exception($"UPDATE WAS unsuccessful:\n{ex.Message}");
}
finally
{
sqlconnConnection.Close();
}
Maybe you have a DB browser opened? Or you have accessed the DB some other way. This error only occurs when DB is modified or used elsewhere. If you can't find it, I'd suggest restarting PC just in case there something hidden :)
P.S. Posting this as answer as I cannot comment under the question for technical reasons :)

Access Database - Operation must use an updateable query. (Works fine on local)

I checked other questions when i typed the title in, i can't understand anymore. i need to cool down a bit :)
I started asp.net 1,5 week ago everything was working fine on local and i uploaded my site files to ftp server and i'm getting this error:
Operation must use an updateable query.
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.OleDb.OleDbException: Operation must use an updateable query.
Source Error:
//* Goruntulenme sayısını güncelleme //translation updating view count *
// This was the old code after checking other same titled questions i changed to this one and still no luck
//sorgu.Append(" UPDATE sorular SET [goruntulenme] = [goruntulenme] + 1 ");
//sorgu.Append(" WHERE soruid = #soruid ");
//komut = new OleDbCommand(sorgu.ToString(), baglanti);
//komut.Parameters.Add("#soruid", OleDbType.VarChar).Value = sorgusoruid.ToString();
//komut.ExecuteNonQuery();
string SqlString = "UPDATE sorular SET [goruntulenme] = [goruntulenme] + 1 WHERE soruid = ?";
using (OleDbCommand cmd = new OleDbCommand(SqlString, baglanti))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("soruid", sorgusoruid.ToString());
cmd.ExecuteNonQuery();
}
}
Error points to that cmd.ExecuteNonQuery(); line. The things i checked:
*Table has a primary key
*Code works on local just like i need it
*This is a forum part of my project the simplest way i have 3 tables "users" "questions" and "answers"
*i can log in and log out on server. it works fine but can't update. i guess i'm suspecting permissions because this logging in code works (if you want i can translate variable parts of code).
OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("App_Data\\db.accdb"));
baglan.Open();
string k_ad = Kullanici.Text;
string k_sifre = sifre.Text;
OleDbCommand kontrol = new OleDbCommand("SELECT * FROM Kullanicilar WHERE K_Ad='" + k_ad + "' and K_Sfr='" + k_sifre + "'", baglan);
OleDbDataReader oku = kontrol.ExecuteReader();
if (oku.Read())
{
Session.Add("Kullanici", k_ad);
Response.Redirect("Forum.aspx");
lbl.Visible = false;
}
else
{
lbl.Text = "Kullanıcı adı veya şifre yanlış";
lbl.Visible = true;
}
baglan.Close();
baglan.Dispose();
}
I don't know what else i can give here as info. pls let me know if any more info you need about that and how can i find that information :))
Ohh and i'm using ms-access database, using sql database server seems more complicated to me.
Problem solved, i changed database folder permissions on my hosting service provider's website i logged in a panel with same id pw with the ones i use at filezilla there was settings for folders and they were read only i changed them to full access minus deleting and changing ownership

Web service returns different value each time I request

I got a web service running on c# but recently, something strange happened. Even when I query from a simple table with only 1 value like this:
string str = "";
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionStringTD"]))
{
connection.Open();
try
{
SqlCommand selectCommand = new SqlCommand
{
CommandType = CommandType.Text,
Connection = connection,
CommandText = "select Version from TN_Version"
};
str = selectCommand.ExecuteScalar().ToString();
}
catch (Exception exception)
{
str = "ERROR:" + exception.Message + "_" + exception.InnerException.Message;
Console.WriteLine(exception.Message ?? "");
}
return str;
}
This always returns correct value when I debug on local but an error message returned whenever I publish this service on host and execute it:
There is no row at position 0.
It's really strange cuz this is a simple table and absolute nothing changes or delete its value...
Error
And I have to execute the service 3 or 4 times until it gets me the correct value:
<string xmlns="http://webservice.com/">6.7</string>
Please, someone helps me, this have been bugging me to no end. Thanks you so much (really)
The error message simply means that no rows were returned by your query. so maybe, after you hosted the app, either IIS or a firewall causing this problem in the connection. Check with the firewall turned off and check the rights of your IIS user account.

Can't Write to Windows Application Log (C#)

I'm having a really strange problem with an application I wrote a while back. It has worked without issues, but after leaving it alone for a while, it simply stopped functioning. I'll attach the code here:
try
{
using (Process proc = Process.Start(starter))
{
windowHider();
proc.WaitForExit();
DateTime endStamp = DateTime.Now;
endStamp = truncate(endStamp);
TimeSpan diff = endStamp.Subtract(startStamp);
string programSource = "applicationName";
string logLocation = "Application";
string occurance = "Var='" + varName + "' Var2='"+ var2Name + "' Var3='" + var3Name + "' Var4='" + var4Name + "' Var5='" + var5Name + "' Var6='" + var6Name + "'";
try
{
if (!EventLog.SourceExists(programSource))
{
EventLog.CreateEventSource(programSource, logLocation);
}
else
{
EventLog.WriteEntry(programSource, occurance);
}
}
catch (Exception err)
{
string message = "There was an error with usage logging. Please contact IT.";
MessageBox.Show(message);
errorLogger(message, err.ToString(), ((Control)sender).Name);
this.Close();
}
this.Close();
}
}
When the process that was started exits, the program writes to the application log. For some reason, however, I am getting the following error:
Exception: System.ComponentModel.Win32Exception (0x80004005): The
specified path is invalid
It cites this line as the cause:
EventLog.WriteEntry(programSource, occurance);
Any ideas as to what this sudden problem could be?
I figured it out! There was something corrupted in the registry, and there must have been another corrupted component lurking around somewhere. I changed the sourcename, and it worked without any issues.
The original sourcename works on other machines, which makes me think it was definitely just something wonky with the registry.

button sometimes redirects to "This page cannot be displayed"

I have an ASP.NET c# web application published to a server of ours. It consists of three pages, each with a form on them, sort of like a 3-page login. After the third page's form is validated, it sends the user to a different site. Here's a little diagram so I can explain it better:
NamePage ---> DateOfBirthPage ---> IDNumberPage ---> OtherSite
This has been working great in all of our development tests and stress tests. However, after we put it into production, occasionally when the "Next" button on the IDNumberPage is clicked, the user sees "This page cannot be displayed" with a "diagnose connection problems" button. When this occurs for one user, the same problem occurs for all users (meaning once it happens, nobody can fully authenticate). NamePage and DateOfBirthPage always work, and when the crash occurs, the IDNumberPage link doesn't change, suggesting that the crash is occurring on this side of the application, not after it redirects to OtherSite. I have friendly HTTP errors turned off but it's not showing any errors on the page. If we go into the server and restart the application, it works again.
The frustrating part is that we can't replicate this error to see how/why it's occurring.
Some things that are noteworthy:
Each page uses one query on a MS SQL server database
Each page passes up to 4 Session variables (only small Strings containing what was entered into the textbox form on the previous page(s))
The session is abandoned when the final "next" button is clicked.
All resultsets/connections/commands are closed before redirect.
Redirects use the overloaded version using Response.Redirect(siteName, false)
Sorry if all of this is very vague, but the problem itself has done an oddly good job of hiding from us. We have tried hammering the server with test requests (many at once, many over a period of time, etc) and different combinations of logging in/trying to break the page in general, to no avail. Can anyone suggest some things to try to diagnose/fix/replicate this problem?
Edit: The click function on IDNumberPage's code-behind that is causing the problem:
{ SqlConnection dbconn = new SqlConnection(Application["dbconn"].ToString());
SqlCommand sqlValidate = dbconn.CreateCommand();
dbconn.Open();
sqlValidate.CommandText = "SELECT lastName, csn FROM Demographics WHERE lastName = '" + Session["lastName"].ToString() + "' " +
"AND dob = '" + Session["dobCheck"].ToString() + "' AND mrn = " + strMRN;
SqlDataReader results = sqlValidate.ExecuteReader();
if (results.HasRows)
{
string csn = "";
while (results.Read())
{
if (!String.IsNullOrEmpty(results["csn"].ToString()))
{
csn = results["csn"].ToString();
break;
}
}
string url = Application["surveyUrlString"] + "&lastname=" + Session["lastName"].ToString() + "&mrn=" + strMRN + "&dobday=" + Session["dobday"].ToString()
+ "&dobmonth=" + Session["dobmonth"].ToString() + "&dobyear=" + Session["dobyear"].ToString() + "&csn=" + csn;
results.Close();
dbconn.Close();
Response.Redirect(url, false);
}
The problem is due to leaking sql connections.
You aren't properly disposing of your resources. Over time these are going to stack up in the connection pool until you reach a point where the pool overflows and your app dies. Resetting will obviously fix the issue.
Also this issue might not show up in "stress" tests depending on how, exactly you are testing the application.
The solution is to reformat that code to handle your database call better.
{
string url = string.empty;
using (SqlConnection dbconn = new SqlConnection(Application["dbconn"].ToString())) {
using (SqlCommand sqlValidate = dbconn.CreateCommand()) {
dbconn.Open();
sqlValidate.CommandText = "SELECT lastName, csn FROM Demographics WHERE lastName = '" + Session["lastName"].ToString() + "' " +
"AND dob = '" + Session["dobCheck"].ToString() + "' AND mrn = " + strMRN;
using (SqlDataReader results = sqlValidate.ExecuteReader()) {
if (results.HasRows) {
string csn = "";
while (results.Read())
{
if (!String.IsNullOrEmpty(results["csn"].ToString()))
{
csn = results["csn"].ToString();
break;
}
}
url = Application["surveyUrlString"] + "&lastname=" + Session["lastName"].ToString() + "&mrn=" + strMRN + "&dobday=" + Session["dobday"].ToString()
+ "&dobmonth=" + Session["dobmonth"].ToString() + "&dobyear=" + Session["dobyear"].ToString() + "&csn=" + csn;
}
} // sqldatareader
} // using sqlcommand
} // using sqlconnection
if (!String.IsNullOrEmpty(url)) {
Response.Redirect(url, false);
}
}
notice that you aren't redirecting until after everything is cleaned up.
SqlConnection, SqlCommand and SqlDataReader all implement IDisposable. You have to properly clean up after use otherwise the resources will be left hanging. The "best" way of doing this is to wrap them in a using clause. This ensures they are properly removed once the code block is exited as they aren't garbage collected like other objects.
Also note that the above code has a good side benefit. Namely, in case of error it STILL cleans up after you. Whereas the original code that was posted would clearly leak in the event the DB server didn't respond or threw some type of error when running the query.
The query could error out depending on the values contained in dboCheck, lastname and mrn parameters. For example, what if "BOB" was passed in for the dobCheck field, or Nothing was passed in for mrn... If dob is a datetime field in your database then the query will throw an error that will result in a leaked connection. Do that enough times and your site is down.
Upon further review, I'm guessing that's probably what is happening: people are putting in garbage data that your app is allowing to get to this point and the query is failing. Most likely this isn't something that you've handled in your test cases.
Side note: Please don't create your sql statements by using concatentation. That is a complete security no no. At the very least, parameterize those queries.
Nice answer Chris, one question aren't the .Close() statements missing in the Using statements?. Both for the connection and the datareader:
results.Close();
} // using sqldatareader
} // using sqlcommand
dbconn.Close();
} // using sqlconnection

Categories

Resources