I'm trying to find out why tweetinvi streaming library is getting stuck when it's getting too much tweets from the followers, that I add with the function AddFollow(). In this function I'm putting 600 followers using a list that I create. Each of these tweets that I receive on my application go directly to a database but in at a uncertain time the application just stops bringing tweets and it doesn't show any error or exception in the debugging mode. The program it's in C# and I'm using visual studio 2012
Here is my code:
public void getTweets()
{
string[] sports = new string[] { "NFL" };
long[] list1 = critter_connex(sports);
int cont = 0;
DateTime pastDate = DateTime.MinValue;
string tweetType = "";
int id = 0;
using (var webClient = new WebClient())
{
webClient.Proxy = WebRequest.DefaultWebProxy;
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
webClient.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webClient.Headers["User-Agent"] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
//using app key NECESITO VER TWEETS3
var credentials = TwitterCredentials.CreateCredentials("XXXXX", "XXXXX", "XXXXX", "XXXXX");
try
{
TwitterCredentials.ExecuteOperationWithCredentials(credentials, () =>
{
cont++;
var filteredStream = Stream.CreateFilteredStream();
for (int i = 0; i < list1.Length; i++)
{
filteredStream.AddFollow(list1[i]);
}
try
{
filteredStream.MatchingTweetReceived += (sender, arg) =>
{
try
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
MySqlCommand command = new MySqlCommand();
MySqlDataReader reader;
command.Connection = conn;
command.CommandText = "SELECT sportName, specTeam FROM twitter_userids where userId = " + arg.Tweet.Creator.Id.ToString() + "";
command.Prepare();
reader = command.ExecuteReader();
try
{
if (reader.Read())
{
tweet.setSport(reader.GetString(0));
tweet.setTeam(reader.GetString(1));
}
}
finally
{
reader.Close();
conn.Close();
}
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex.Message);
}
try
{
cont++;
if (cont == 10)
{
filteredStream.StopStream();
DateTime date = DateTime.Now;
getTweets();
}
if (tweetType == "Tweet")
{
if (pastDate > arg.Tweet.CreatedAt)
{
filteredStream.StopStream();
DateTime date = DateTime.Now;
getTweets();
}
}
if (arg.Tweet.IsRetweet)
{
tweet.setUser_name(arg.Tweet.RetweetedTweet.Creator.ScreenName);
tweet.setText(arg.Tweet.RetweetedTweet.Text);
tweet.setPublish_date(arg.Tweet.RetweetedTweet.CreatedAt);
tweet.setRetweet_date(arg.Tweet.CreatedAt);
tweetType = "Retweet";
tweet.setState("Retweet");
tweet_text = tweet.getText();
Console.WriteLine(tweet.getUser_name());
Console.WriteLine(tweet.getText());
string rt_final_date = tweet.getPublish_date().ToString("yyyy-MM-dd HH:mm:ss");
string rt_date = tweet.getRetweet_date().ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(rt_final_date);
Console.WriteLine(rt_date);
Console.WriteLine(tweet.getSport());
Console.WriteLine(tweet.getTeam());
Console.WriteLine("Retweet");
Console.WriteLine("\n");
if (tweet_text.IndexOf("http://") > -1)
{
int index = tweet_text.IndexOf("http://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
else
if (tweet_text.IndexOf("https://") > -1)
{
int index = tweet_text.IndexOf("https://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
MySqlCommand insert_rt = conn.CreateCommand();
if (tweet.getLink() != "")
{
insert_rt.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_link, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM (SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + tweet.getLink().Replace("'", "") + "', '" + rt_final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "' LIMIT 50) LIMIT 1";
}
else
{
insert_rt.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM (SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + rt_final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "' LIMIT 50) LIMIT 1";
}
conn.Open();
id = insert_rt.ExecuteNonQuery();
conn.Close();
tweet.setLink("");
}
else
{
tweet.setUser_name(arg.Tweet.Creator.ScreenName);
tweet.setText(arg.Tweet.Text);
pastDate = arg.Tweet.CreatedAt;
tweet.setPublish_date(arg.Tweet.CreatedAt);
tweetType = "Tweet";
tweet.setState("Tweet");
tweet_text = tweet.getText();
Console.WriteLine(tweet.getUser_name());
Console.WriteLine(tweet.getText());
string final_date = tweet.getPublish_date().ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(final_date);
Console.WriteLine(tweet.getSport());
Console.WriteLine(tweet.getTeam());
Console.WriteLine(tweet.getState());
Console.WriteLine("\n");
if (tweet_text.IndexOf("http://") > -1)
{
int index = tweet_text.IndexOf("http://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
else
if (tweet_text.IndexOf("https://") > -1)
{
int index = tweet_text.IndexOf("https://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
MySqlCommand insert_t = conn.CreateCommand();
if (tweet.getLink() != "")
{
insert_t.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_link, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM ( SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + tweet.getLink().Replace("'", "") + "', '" + final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "') LIMIT 1";
}
else
{
insert_t.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM ( SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "') LIMIT 1";
}
conn.Open();
id = insert_t.ExecuteNonQuery();
conn.Close();
tweet.setLink("");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
};
filteredStream.StartStreamMatchingAllConditions();
}
catch (Exception ex)
{
Console.WriteLine(ex);
getTweets();
}
tweet_text = "";
getTweets();
filteredStream.StartStreamMatchingAllConditions();
});
getTweets();
}
catch (Exception ex)
{
getTweets();
Console.WriteLine(ex);
}
getTweets();
}
}
Thanks.
Have you tried to register to the StreamStopped event and check that everything is working correcly?
filteredStream.StreamStopped += (sender, args) =>
{
Console.WriteLine(args.DisconnectMessage.Reason);
if (args.Exception != null)
{
Console.WriteLine(args.Exception);
}
};
Related
I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}
I have grid view in which all question has been display from access database . now I want to perform the search operation in given text boxes ,user may enter the data in 1 text box or else in all text boxes ,depends upon user needs .My question is how many times condition has been give so that whatever user give information in any text box ,filtration is performed accordingly.
for eg : user gave only standard and marks than filtration must be perform where standard = "given value" and marks = "given value" only
I have given various condition on each control but its become too huge coding. now wants to minimize this so any suggestion must recommended.
My Code:
private void txt_marks_TextChanged(object sender, EventArgs e)
{
string marks = Convert.ToString(txt_marks.Text);
string q_type = Convert.ToString(cmbQType.SelectedValue);
if (q_type.Contains("[") || q_type.Contains("]") || q_type.Contains("*") || q_type.Contains("%"))
{
q_type = replacestring(q_type);
}
if (btnlanguage.Text != "" && txt_sub.Text != "" && txt_std.Text != "" && cmbQType.SelectedIndex != -1 && txt_marks.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '" + txt_std.Text.ToString() + "'and Chapter Like '" + btnlanguage.Text.ToString() + "%' and QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1 && txt_sub.Text != "" && txt_std.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '"+ txt_std.Text.ToString()+ "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1 && txt_sub.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format(" QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Marks = '"+ marks +"'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else
{
load_grid_view();
}
Similarly above coding has been done to every given control.
Thank you .
What about using some Function that take n arguments to do some checks?
private void txt_marks_TextChanged(object sender, EventArgs e)
{
string marks = Convert.ToString(txt_marks.Text);
string q_type = Convert.ToString(cmbQType.SelectedValue);
char[] q_types = { '[', ']', '%'};
if (ContainsChars(q_types, q_type))
{
q_type = replacestring(q_type);
}
if (NoEmpty(btnlanguage.Text, txt_sub.Text, txt_std.Text, txt_marks.Text) && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '" + txt_std.Text.ToString() + "'and Chapter Like '" + btnlanguage.Text.ToString() + "%' and QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (NoEmpty(txt_marks.Text, txt_sub.Text, txt_std.Text) && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '"+ txt_std.Text.ToString()+ "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (NoEmpty(txt_marks.Text, txt_sub.Text) && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format(" QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Marks = '"+ marks +"'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else
{
load_grid_view();
}
}
public static bool NoEmpty(params string[] strings)
{
return strings.All( x => x != string.Empty );
}
public static bool ContainsChars(IEnumerable<char> chars, string toTest)
{
return chars.Any(x => toTest.Contains(x));
}
Please note that I've written it with notepad++ so I don't have typo checks, so excuse me if there's any typo
Perhaps you can store the field query in the Tag property of each control (e.g. txt_marks.Tag would be set to "Marks ='{0}'") then you can define an extensiom method to get the query from a TextBox and another for the drop down, something like:
internal static string GetQuery(this TextBox textBox)
{
if(string.IsNullOrEmpty(textBox.Text)) return string.Empty;
return string.Format(textBox.Tag.ToString(), textBox.Text)
}
internal static string GetQuery(this ComboBox cmbBox)
{
if(cmbBox.SelectedIndex == -1) return string.Empty;
return string.Format(cmbBox.Tag.ToString(), cmbBox.SelectedValue)
}
Then you can just loop through the controls, call GetQuery and do a string.Join("and ", controlQueries.Where(q => !string.IsNullOrEmpty(q))
Thank you #KMoussa and #Sid .
With your Combine Both suggestion I made a Dynamic query in function and call this function on every control and also like to share with this site .
My function :
public void searching_query()
{
string grid_query = "";
int cnt_coma = 0;
string q_type = "";
if (txt_marks.Text != "")
{
string marks = Convert.ToString(txt_marks.Text);
}
if (cmbQType.SelectedIndex != -1)
{
q_type = Convert.ToString(cmbQType.SelectedValue);
// Removing the wild character in question type .
if (q_type.Contains("[") || q_type.Contains("]") || q_type.Contains("*") || q_type.Contains("%"))
{
q_type = replacestring(q_type);
}
}
// counting the number of fields has been enter ->(for entering "and" in between in query)
{
if (txt_std.Text != "")
cnt_coma = 1;
if (txt_sub.Text != "")
cnt_coma = 2;
if (Txt_chp.Text != "")
cnt_coma = 3;
if (cmbQType.SelectedIndex != -1)
cnt_coma = 4;
if (txt_marks.Text != "")
cnt_coma = 5;
}
// making query for searching .
if (txt_std.Text != "")
{
if (cnt_coma > 1)
grid_query = grid_query + "Standard Like '" + txt_std.Text.ToString() + "' and ";
else if (cnt_coma <= 1)
grid_query = grid_query + "Standard Like '" + txt_std.Text.ToString() + "'";
}
if (txt_sub.Text != "")
{
if (cnt_coma > 2)
grid_query = grid_query + "Subject Like '" + txt_sub.Text.ToString() + "%' and ";
else if (cnt_coma <= 2 )
grid_query = grid_query + "Subject Like '" + txt_sub.Text.ToString() + "%' ";
}
if (Txt_chp.Text != "")
{
if (cnt_coma > 3)
grid_query = grid_query + "Chapter Like '" + Txt_chp.Text.ToString() + "%' and ";
else if (cnt_coma <= 3 )
grid_query = grid_query + "Chapter Like '" + Txt_chp.Text.ToString() + "%'";
}
if (cmbQType.SelectedIndex != -1)
{
if (cnt_coma > 4)
grid_query = grid_query + "QuestionType Like '" + q_type + "' and ";
else if (cnt_coma <= 4 )
grid_query = grid_query + "QuestionType Like '" + q_type + "'";
}
if (txt_marks.Text != "")
{
grid_query = grid_query + "Marks = '" + Convert.ToString(txt_marks.Text) + "'";
}
//---------- Grid view Filteration
if (cnt_coma > 0)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format(grid_query);
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else
{
load_grid_view();
}
}
i get an error of
"This SqlTransaction has completed; it is no longer"
while multiple insert in a single table
mclDb.trans = mclDb.mCon.BeginTransaction();
try
{
foreach (DataGridViewRow dgvRow in dgvDetail.Rows) // get rows in details
{
ht.Clear();
string dtlPoCode = dgvRow.Cells[2].Value.ToString();
if (poCode == dtlPoCode) // check if po code matches
{
ht.Add("dtlPoCode", dtlPoCode);
ht.Add("dtlPoLine", dgvRow.Cells[3].Value.ToString());
ht.Add("dtlwhouse", dgvRow.Cells[12].Value.ToString());
ht.Add("dtlSkuCode", dgvRow.Cells[4].Value.ToString());
ht.Add("dtlUom", dgvRow.Cells[6].Value.ToString());
ht.Add("dtlmrQty", dgvRow.Cells[7].Value.ToString());
ht.Add("dtlBCode", dgvRow.Cells[10].Value.ToString());
ht.Add("dtlBExp", dgvRow.Cells[11].Value.ToString());
ht.Add("dtlBin", dgvRow.Cells[9].Value.ToString());
ht.Add("custPoCode", custPoCode);
ht.Add("grnCode", grnCode);
ht.Add("refCode", refCode);
mclDb.IUD(ht);
}
}
MessageBox.Show("Transaction Complete");
mclDb.trans.Commit();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "Error Encountered", MessageBoxButtons.OK, MessageBoxIcon.Error); mclDb.trans.Rollback();
}
here is my IUD method
public void IUD(Hashtable ht)
{
try
{
Connect();
string cmd = "";
cmd = mStatements.getQuery(ht);
mAdptr = new SqlDataAdapter(cmd,mCon);
ds = new DataSet();
mAdptr.Fill(ds);
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}
and my getquery method
public string getQuery(Hashtable ht)
{
StringBuilder qry = new StringBuilder();
qry.Append(" Insert into mTable values ");
qry.Append(" ('" + ht["custPoCode"] + "','" + ht["dtlPoCode"] + "', ");
qry.Append(" " + ht["dtlPoLine"] + ",'" + ht["dtlwhouse"] + "', ");
qry.Append(" '" + ht["dtlSkuCode"] + "','" + ht["dtlUom"] + "', ");
qry.Append(" " + ht["dtlmrQty"] + ",'" + ht["grnCode"] + "', ");
qry.Append(" '" + ht["refCode"] + "','" + ht["dtlBCode"] + "', ");
qry.Append(" '" + ht["dtlBExp"] + "','" + ht["dtlBin"] + "', ");
qry.Append(" '" + ht["dtlmrQty"] + "','' ) ");
return qry.ToString();
}
the number of rows to be inserted in the table will depend on how many rows are selected in dgvDetail (which is a datagridview)
any suggestions in how to use sqltransaction on my codes ?
tia
i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me
You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}
I receive this error on cmd.ExecuteNonQuery()... I think I am wrong on cmd.CommandText...
Syntax error (missing operator) in query expression 'Nr_Crt='1' and Varsta '3' and KG '2' and Specie 'Iepure' and Risc'Nu' and Tip1 'Diurn' and Tip2 'Carnivor''.
private void button2_Click_1(object sender, EventArgs e)
{
if (txtNr_Crt.Text != " " & txtVarsta.Text != " " & txtKG.Text != " " & txtSpecie.Text != " " & txtRisc.Text != " " & txtTip1.Text != " " & txtTip1.Text != " " & txtTip2.Text != "")
{
cn.Open();
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta '" + txtVarsta.Text + "' and KG '" + txtKG.Text + "' and Specie '" + txtSpecie.Text + "' and Risc'" + txtRisc.Text + "' and Tip1 '" + txtTip1.Text + "' and Tip2 '" + txtTip2.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
txtNr_Crt.Text = "";
txtVarsta.Text = "";
txtKG.Text = "";
txtSpecie.Text = "";
txtSex.Text = "";
txtRisc.Text = "";
txtTip1.Text = "";
txtTip2.Text = "";
}
}
You code is vulnerable to SQL injection, i'd fix that.
The issue is that you are missing the = from each of your subsequent and's:
cn.Open();
cmd.Parameters.AddWithValue("#Nr_Crt", txtNr_Crt.Text);
cmd.Parameters.AddWithValue("#Varsta", txtVarsta.Text);
cmd.Parameters.AddWithValue("#KG", txtKG.Text);
cmd.Parameters.AddWithValue("#Specie", txtSpecie.Text);
cmd.Parameters.AddWithValue("#Risc", txtRisc.Text);
cmd.Parameters.AddWithValue("#Tip1", txtTip1.Text);
cmd.Parameters.AddWithValue("#Tip2", txtTip2.Text);
cmd.CommandText = "DELETE from Animale Where Nr_Crt= #Nr_Crt and Varsta = #Varsta and KG = #KG and Specie = #Specie and Risc = #Risc and Tip1 = #Tip1 and Tip2 = #Tip2";
cmd.ExecuteNonQuery();
cn.Close();
This should fix it (and the SQL injection risk)
Your query is wrong. You are missing = when comparing the columns
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta='" + txtVarsta.Text + "' and KG='" + txtKG.Text + "' and Specie='" + txtSpecie.Text + "' and Risc='" + txtRisc.Text + "' and Tip1='" + txtTip1.Text + "' and Tip2='" + txtTip2.Text + "'";
foreach(Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
ctrl.text="";
}
}
For cleaning all textbox at once :) you can create a Method that performs it when you need it