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();
}
}
Related
private void button1_Click(object sender, EventArgs e)
{
try
{
if (transaction_idTextBox.Text == "" || lastnameTextBox.Text == "" || firstnameTextBox.Text == "" || middlenameTextBox.Text == "" || txtYear.Text == "" || txtDoI.Text == "" || txtPoI.Text == "" || txtAddress.Text == "" || CB_Sex.Text == "" || txtCS.Text == "" || txtDoB.Text == "" || txtPoB.Text == "" || txtAmount.Text == "")
{
MessageBox.Show("All Fields Are Compulsory");
}
else
{
SqlCommand cmdinsert = new SqlCommand("Insert into [Transaction] values( ' " + transaction_idTextBox.Text + " ','" + lastnameTextBox.Text + "','" + firstnameTextBox.Text + " ','" + middlenameTextBox.Text + "','" + txtYear.Text + "','" + txtDoI.Text + "','" + txtPoI.Text + "','" + txtAddress.Text + "','" + CB_Sex.Text + "','" + txtCS.Text + "','" + txtDoB.Text + "','" + txtPoI.Text + "','" + txtAmount.Text + "' )", con);
con.Open();
cmdinsert.CommandType = CommandType.Text;
cmdinsert.ExecuteNonQuery();
MessageBox.Show("Data Added");
transactionDataGridView.Update();
transactionDataGridView.Refresh();
transaction_idTextBox.Text = "";
lastnameTextBox.Text = "";
firstnameTextBox.Text = "";
middlenameTextBox.Text = "";
txtYear.Text = "";
txtDoI.Text = "";
txtPoI.Text = "";
txtAddress.Text = "";
CB_Sex.Text = "";
txtCS.Text = "";
txtDoB.Text = "";
txtPoB.Text = "";
txtAmount.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
For first : Add "LoadData();" at the end of Your code
Secondly add this to populate DataGridView:
public void LoadDataEQ()
{
DataTable AllDataTable = new DataTable();
string SqlCommand = "SELECT * FROM Transaction";
SqlDataAdapter SQLDA = new SqlDataAdapter(SqlCommand , con);
SQLDA.Fill(AllDataTable);
SQLDA.Dispose();
dataGridView1.DataSource = AllDataTable;
}
I wanted to insert data to microsoft access using c# and need to use class.
I've tried removing some textbox and look for some error and I feel that there might be some mistake in IF condition.
private void registerbutton_Click(object sender, EventArgs e)
{
-- CLASS --
RegStudent reg = new RegStudent();
reg.stdfname = fnametextbox.Text;
reg.stdlname = lnametextbox.Text;
reg.username = usernametextbox.Text;
reg.password = passwordtextbox.Text;
reg.dob = dobtextbox.Text;
reg.city = citytextbox.Text;
reg.state = statetextbox.Text;
reg.email = emailtextbox.Text;
reg.phoneno = ctcnotextbox.Text;
reg.phoneno2 = ctcnotextbox2.Text;
reg.course = coursetextbox.Text;
reg.emergencyname = emergencynametextbox.Text;
reg.emergencyphoneno = emergencynumbertextbox.Text;
reg.registerdate = registerdatetextbox.Text;
if (tptextbox.Text != "" && fnametextbox.Text != "" && lnametextbox.Text != "" && dobtextbox.Text != "" && usernametextbox.Text != "" && passwordtextbox.Text != "" && citytextbox.Text != "" && statetextbox.Text != "" && registerdatetextbox.Text != "" && emailtextbox.Text != "" && ctcnotextbox.Text != "" && ctcnotextbox2.Text != "" && coursetextbox.Text != "" && emergencynametextbox.Text != "" && emergencynumbertextbox.Text != "")
{
registerconnection.Open();
OleDbCommand insert = new OleDbCommand();
insert.Connection = registerconnection;
insert.CommandText = "Insert into StudentDatabase values (" + reg.stdfname + "','" + reg.stdlname + "','" + reg.username + "','" + reg.password + "','" + reg.dob + "','" + reg.city + "','" + reg.state + "','" + reg.email + "','" + reg.phoneno + "','" + reg.phoneno2 + "','" + reg.course + "','" + reg.emergencyname + "','" + reg.emergencyphoneno + ");";
insert.CommandType = CommandType.Text;
insert.Connection = registerconnection;
insert.ExecuteNonQuery();
MessageBox.Show("Data Have Been Registered.");
}
else
{
MessageBox.Show("error");
}
}
I expected that the output will be that the data will be saved.
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 a web form,asp.net, to save specific information into my local database in Visual Studio. Some of this web form components are html components.
After clicking an "add" button, which is as asp.net button, the data is saved successfully into the database, but when I look to my database table, it shows me "System.Web.UI.HtmlControls.HtmlInputText" in some fields as shown in the picture below:
What confuses me is that I don't know why some values are saves correctly and the others not ! the eventName, EventDuration, EventAdmission, EventWebsite and EventVenue are all html textboxes .. and as seen in the image above for all of these fields the saved value is "System.Web.UI.HtmlControls.HtmlInputText" while the EventVenue value is saved correctly!! even though the codes are the same .. see the example below:
<div class="6u$ 12u$(small)">
<label for="website">Website</label>
<input type="text" id="website" name="website" runat="server" />
</div>
<div class="6u$ 12u$(small)">
<label for="venue">Venue</label>
<input type="text" id="venue" name="venue" runat="server" />
And here is my source code:
protected void addbtn_Click(object sender, EventArgs e)
{
string latitude = "";
string longitude = "";
string imagesArr = null;
bool fields = false;
string eventname = Request.Form["name"].ToString();
string disc = Request.Form["TextArea3"].ToString();
string startDate = DropDownList1.Text + "/" + category.Value + "/" + DropDownList2.Text;
string endDate = DropDownList4.Text + "/" + days.Value + "/" + DropDownList5.Text;
string eventduration = Request.Form["duration"].ToString()
string eventadmission = admission.Value;
string categ = DropDownList3.Text;
string contact = Request.Form["TextArea4"].ToString();
string eventwebsite = website.Value;
string location = venue.Value;
country.Disabled = true;
string eventcountry = Request.Form["country"].ToString();
if (Session["Latitude"].ToString() == null && Session["Longitude"].ToString() == null)
{
latitude = "";
longitude = "";
}
else if (Session["Latitude"].ToString() != null && Session["Longitude"].ToString() != null)
{
latitude = Session["Latitude"].ToString();
longitude = Session["Longitude"].ToString();
}
if (Session["ImagesArray"].ToString() != null)
{
imagesArr = Session["ImagesArray"].ToString();
}
if (DropDownList2.Text.Equals("Year") || DropDownList1.Text.Equals("Month") || category.Value.Equals("Day") || DropDownList5.Text.Equals("Year") || DropDownList4.Text.Equals("Month") || days.Value.Equals("Day") || name == null || disc == null || duration == null || admission == null || categ == null || contact == null || website == null || location == null)
{
fields = true;
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert(' Make sure to enter all the required data')", true);
}
else { fields = false; }
if (fields == false)
{
command.CommandText = "INSERT INTO EventsEnglish(EventName,EventDescription,EventStartDate,EventEndDate,EventDuration, EventAdmission, EventCategory, EventContact, EventWebsite, EventVenue, EventMapLatitude, EventMapLongitude, CountryName, EventImages) values(N'" + name + "', N'" + disc + "',N'" + startDate + "',N'" + endDate + "',N'" + duration + "',N'" + admission + "', N'" + categ + "', N'" + contact + "', N'" + website + "', N'" + location + "', N'" + latitude + "', N'" + longitude + "', N'" + country + "', N'" + imagesArr + "')";
//command.ExecuteNonQuery();
int result = command.ExecuteNonQuery();
if (result == 1)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert(' New event has been added')", true);
name.Value = "";
TextArea3.InnerText = "";
DropDownList1.Text = "Month";
category.Value = "Day";
DropDownList2.Text = "Year";
DropDownList4.Text = "Month";
days.Value = "Day";
DropDownList5.Text = "Year";
duration.Value= "";
admission.Value = "";
DropDownList3.Text = "Category";
TextArea4.InnerText = "";
website.Value = "";
venue.Value = "";
Session.Remove("ImagesArray");
Session.Remove("Latitude");
Session.Remove("Longitude");
}
con.Close();
}
}
As seen in the codes above, I've used two different ways to get the value of an html text box value, such as "Request.Form["name"].ToString();" and "name.Value;" and none of them worked, except that the second way has worked for "Venue" field only.
Do you have any idea to solve this???
Well, I've figured out my issue .. in this code
command.CommandText =
"INSERT INTO EventsEnglish( " +
"EventName, EventDescription, EventStartDate, EventEndDate, " +
"EventDuration, EventAdmission, EventCategory, EventContact, " +
"EventWebsite, EventVenue, EventMapLatitude, EventMapLongitude, " +
"CountryName, EventImages) " +
"VALUES (" +
"N'" + name + "', N'" + disc + "', N'" + startDate + "', " +
"N'" + endDate + "',N'" + duration + "',N'" + admission + "', " +
"N'" + categ + "', N'" + contact + "', N'" + website + "', " +
"N'" + location + "', N'" + latitude + "', N'" + longitude + "', " +
"N'" + country + "', N'" + imagesArr + "')";
I just had to add the string local variables instead of the html text boxes names .. I don't know how i didn't notice this!!
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);
}
};