MySqlDataAdapter failed to retrieve data on the first load - asp.net

I use MySQL Connector for ASP.NET to retrieve data from my MySQL server. Everything seems to work fine, but just at the first asynchronous postback of my page, MySQLDataAdapter does not fill my DataSet. After a complete refresh the data is succesfully loaded by asynchronous postback.
I try to assign a bigger value to the command timeout, but it does not seem seem to work.
This does not happen locally, only on the production server.
I have checked that the fill does not work by displaying the request string and also by on each async postback (displaying the count() of my DS.table[0].rows).
This is really the fill method not working.
try
{
using (MySqlConnection conn = new MySqlConnection(_connexionString))
{
string requete = "";
DataSet DS = new DataSet();
requete = "SELECT * from MYTABLE";
using (MySqlDataAdapter MSDA = new MySqlDataAdapter(requete, conn))
{
DS.Clear();
MSDA.Fill(DS);
}
conn.Close();
conn.Dispose();
}
}
catch (MySqlException ex)
{
l_error.Text = ex.ToString();
}

Try putting code into Page_Init event too.

did you checked Page.isPostBack property ? may be you are not checking isPostback, properly. it would be helpful,if you share your entire method.
if(!Page.IsPostBack)
{
//load your datasets and data - adapters.
}

After few investigation in code, i found that it not work, in fact an value of request was empty ... so no data return by mysql server, there was session key which was expire...
thx all for your help !

Related

Why doesn't TransactionScope start a transaction for my following SQL commands

I set up a using block for a TransactionScope at the beginning of an ASP.NET action. Somewhere w/i the block I execute a function that both creates a using block for a SqlCommand and w/i that a using block for my SqlConnection.
The blocks for the command and connection open and close as the function is re-used but all w/i the TransactionScope using block. Eventually I call scope.Complete() and when leaving the TransactionScope using block I get an exception saying that no transaction was started that can be committed. In debugging I find that in fact all database calls are just happening w/o a transaction.
Based off the documentation its seeming like the generation of the TransactionScope should be the generation of the transaction, OR, at least that the first time I open any database connection that a transaction should begin because it's w/i the transaction scope block. However this is not the case and I'm unsure why this is.
I actually had this working fine at one point and then all of a sudden, it was not working. So there's something that I did that caused it but I have no idea what it was as the section this was implemented in was completed long ago.
Here's some code:
Starting the transactionScope
using (TransactionScope transactionScope = new TransactionScope())
{
try
{
LegacyDataManager.Start();
//*******************Replace W/ Controller Logic*********************
ViewBag.Message = "Finish";
...
...
...
LegacyDataManager.Commit();
transactionScope.Complete();
}
finally
{
LegacyDataManager.Stop();
}
}
Call to code that executes database update
var theApproval = LegacyDataManager.PrepareForUpdate(Constants.ObjectApproval, row["objectInstance"].ToString(), row["sourceServer"].ToString());
theApproval.write("approvalaction", Request.Form[val].ToString().Substring(0, 1));
theApproval.write("approvaldate", Data_Legacy.getAodDateTimeNow());
theApproval.saveObject();
The database query execution
Data.executeSP("sp_Object_InsertData", SearchNew.generateSQLParameterString("ObjectType", "ObjectInstance", "Parameter", "ParameterValue", "SourceServer"),
SearchNew.generateSQLParameterString(
ObjectType,
ObjectInstance.ToString(),
theNametext,
Regex.Replace(thetheVal, #"\'", "\'\'").Trim(),
SourceServer));
public static DataTable executeSP(string storedProc, SqlParameter[] parms = null, bool gatherParams = true, int commandTimeout = 0)
{
using (SqlCommand cmd = new SqlCommand())
{
if (commandTimeout != 0)
{
cmd.CommandTimeout = commandTimeout;
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProc;
handleParameters(cmd.Parameters, storedProc, parms, gatherParams);
using (SqlConnection conn = Data.getConnection("AOD"))
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
var da = new SqlDataAdapter();
var dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
Thanks for any suggestions in advance.
The good news is that this can just be removed but the bad news is that it creates an annoying programming environment where the XML data files this system is based don't get updated during an error but the updated SQL data that is mirrored out to is retained... Don't ask why that's how it is... it just is.
Apparently I had added a try/catch block around a function that ran a Stored procedure because the data being passed in would sometimes need the function and sometimes not (and thus fail, hence the try catch). Unfortunately when the db call failed the transaction associated w/ the TransactionScope was dropped and the try catch kept the program going.
I removed the the try catch block and replaced it w/ a check on the data passed into the function before determining whether or not to execute the Stored Procedure and now it is once again operating properly.
TL;DR - Check to see if any database calls are failing w/i the transactionScope as it might lead to dropping of the transaction.

Looping through returned database records in .NET, request made and returned via AJAX

I'm having my app make a AJAX request for records from a SQL Server 2008 DB, by using .NET to handle the server side code. Currently, everything is being returned in DOM elements <Products> and <Product>, but I'd rather get the records fed into an array on the server-side, so when the response is sent, I can't just loop through them on my client side and manipulate as needed. I created the code below from another online resource doing the same thing, but he wanted his in the DOM Products elements (I'm a JavaScriptStack developer, so excuse my nativity).
.Net Code:
{
// 1. Initialize XML Response
Response.ContentType = "text/xml";
if (Request.HttpMethod.ToUpper() == "GET")
{
// 2. Open connection & Create command
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
// Select all by default (Unless there is an ID)
command.CommandText = #"SELECT *****(Hidden)";
// 3. Format XML as needed
// - Use <Products> as document element
// - Use <Product> as the record name
DataSet set = new DataSet("Products");
set.Tables.Add(new DataTable("Product"));
DataTable table = set.Tables[0];
try
{
// 4. Get Database content into DataTable
connection.Open();
SqlDataReader reader = command.ExecuteReader();
table.Load(reader, LoadOption.Upsert);
} catch (Exception ex) {
// Handle exception
writer.WriteLine(#"<Error>" + ex.Message + "</Error>");
}
// 5. Render XML Output
table.WriteXml(writer);
}
}
}
}
}
Note: Excuse the incorrect SQL statement, I don't feel comfortable posting our actual query on SO

Already an open data reader associated with this command. How is this possible?

I have the following class:
public class Data
{
static public SqlDataReader ExecutSql(string sql)
{
var cmd = new SqlCommand(sql, SqlCon.Conn);
var data = cmd.ExecuteReader();
return data;
}
}
It's called from an asp.net webpage and I'm getting the error: "There is already an open DataReader associated with this command which must be closed first."
Clearly I'm instantiating a new SqlCommand the line right before I execute the data reader. I am new to web development (my background is WinForms) but even so I can't comprehend how I can already have an open DataReader associated with a Command that was literally just created?? I could possibly understand if it was a multi-threading sort of issue, but I'm stepping throught the code in the debugger and getting this error.
Someone want to tell me what I'm missing here?
Did you already called this method before ? Your method is returning an SqlDataReader and i am not sure whether it is being closed properly.As per msdn,
You must explicitly call the Close method when you are through using
the SqlDataReader to use the associated SqlConnection for any other
purpose.
I would suggest you to read the data from your reader and close the reader and return the new type( a DataTable / DataSet or your custom class filled with properties)
using(SqlCommand command =new SqlCommand(sql, SqlCon.Conn))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//Fill your object and then use that to return
}
}
When exactly are you calling the SqlDataReader ExecutSql(string sql) method? Is it at page load? Because if it is so, then in asp.net page load gets called everytime any event occurs on the page. To prevent this, you could use the following:
if(!Page.IsPostBack)
{
//call SqlDataReader ExecutSql(string sql)
}
This would ensure that the above method gets called only once when the page is loading when opened. In case of a post back due to any event, this method would not be called.
You can also enable MARS in your connection string:

SqlCacheDependency not working

I would like to add SqlCacheDependency to my app.
So I desided to create littel tesp project and confronted with difficulties.
I use MSSQL 2008. I create new db with table Lines and added several rows.
I executed:
ALTER DATABASE ForTest SET ENABLE_BROKER
in managmeng studio.
Aspx page:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Cache["Lines"] == null)
{
string connectionString =
WebConfigurationManager.ConnectionStrings["ForTest"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string query = "SELECT dbo.Lines.Id, dbo.Lines.Value FROM dbo.Lines";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Lines");
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
Cache.Insert("Lines", ds, empDependency);
}
}
}
protected void btnResult_OnClick(object sender, EventArgs e)
{
var result = Cache["Lines"];
}
}
I run this page and add lines to Cache then I add row in managment studio and when I click on button I expect
that the cache will be changed but cache remains old.
I can't find what I do wrong :( Could you give me some hint how I can solve this problem?
Thanks
Update:
I forger to say that in global.aspx I run:
SqlDependency.Start(
WebConfigurationManager.ConnectionStrings["ForTest"].ConnectionString
);
I had a similar issue. This article: Troubleshooting SqlCacheDependency in SQL Server 2008 and SQL Server 2005 helped me a lot then.
In a few words: the databse was restored from a backup, and the original Windows user that created the database was no longer available. So I changed the database ownership to a valid login, something similar to:
ALTER AUTHORIZATION ON DATABASE::[my_perfect_database_name] TO [sa];
and it works like a charm now.
How did I find the source of the issue? I run the query SELECT * FROM sys.transmission_queue and found the next data in the transmission_status column:
An exception occurred while enqueueing a message in the target queue.
Error: 15517, State: 1. Cannot execute as the database principal
because the principal "dbo" does not exist, this type of principal
cannot be impersonated, or you do not have permission.
This message gave me a key to solving the problem.
There is a mistake in the code;
Definition of sqldependency should be placed before you execute the command,
otherwise it will not subscribe to your sqlcommand, then it won't get notified when your resultset of your command changes.
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Lines");
I also thought I had an issue with the SqlCacheDependency not being cleared after a change to the table.
Turns out it was because of how I was testing. I was simply editing the rows in the SQL table thru management studio and expecting it to notify and clear the cache. That's not the case! If you are editing the table, you must also re-execute the select sql to kick off the clearing of the cache.

Use of SqlCommandBuilder in ASP.NET

I have used the following code to add the feedback entered to the web form into a database.
The code works fine. But when I try to deleted thi statement
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
I am getting an error I mean it is executing the else part.
Can any one tell me what is the use of SqlCommandBuilder?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() == "")
{
Response.Write("<script>alert ('Name Field cannot be left blank')</script>");
return;
}
if (txtFeedBack.Text.Trim() == "")
{
Response.Write("<script>alert('FeedBack Field cannot be left blank')</script>");
return;
}
objSqlConnection.ConnectionString = connectionStringSetting;
objSqlConnection.Open();
try
{
SqlDataAdapter objDa = new SqlDataAdapter("select * from FeedBack", objSqlConnection);
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
DataSet objDs = new DataSet("FeedBack");
objDa.Fill(objDs, "FeedBack");
DataRow dr = objDs.Tables["FeedBack"].NewRow();
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;
dr[3] = txtCity.Text;
dr[4] = txtCountry.Text;
dr[5] = txtEmail.Text;
dr[6] = Convert.ToInt32(txtContactNo.Text);
dr[7] = txtFeedBack.Text;
objDs.Tables["FeedBack"].Rows.Add(dr);
objDa.Update(objDs, "FeedBack");
Response.Write("<script>alert('Your FeedBack has been submitted')</script>");
objSqlConnection.Close();
}
catch (Exception)
{
Response.Write("<script> alert('Error on Page. Please try after sometime')</script>");
objSqlConnection.Close();
}
And is there any way to display the specific error messages like if an user enters a string value instead of Integer value it should display the message as 'Input String not entered in correct format?
Never use catch (Exception). It hides the problem. If an exception is being thrown, then there's something serious wrong. You need to learn about it.
Remove the entire try/catch block (keep the code inside it!). Then run your code again. If there's an exception, then you'll see it on the error page. If not, then use the Event Viewer to look in the Windows Event Log for a warning message from the "ASP.NET" source. It should contain the complete exception.
Final answer is that the line you are talking out is doing a bunch of stuff in the background.
It is adding the insert, update and delete commands to the DataAdapter. So without it, you will crash and burn, unless you add those commands yourself to the DataAdapter.

Resources