Program stops responding when deployed - c#

I am having a problem where my application works fine on the development enviroment, but when deployed to a customer just hangs without tripping any exceptions.
In order to deploy I have to change the login details (removed) and sql statements to those shown, which I suppose might be the issue but I'd expect any sql syntex errors to throw an exception. I have excluded infinite loops as a possibility (I think).
The only possibility I'm aware of is to use multithreading and hope the problem is solved, but I don't have that kind of time unless I can be certain that is the solution.
Frankly I'm at a loss and any tips / advice for extracting any kind of lead on the problem is appricated.
Here is the code:
but_exit.Enabled = false;
but_manual.Enabled = false;
//switch off gui timer to allow process messages
guiTimer.Enabled = false;
lbl_dyn_status.Text = "Finding records...";
/*create connection resources*/
/*MYSQl*/
//connect to mysql
/*
*/
var db_name = "";
var db_host = "";
var db_user = "";
var db_password = "";
var connectionString = "SERVER=" + db_host + ";" + "DATABASE=" +
db_name + ";" + "UID=" + db_user + ";" + "PASSWORD=" + db_password + ";";
MySqlConnection mysql_con = new MySqlConnection(connectionString);
//Create a list to store the result
List<string>[] mysql_idlist = new List<string>[1];
mysql_idlist[0] = new List<string>();
/*MSSQL*/
//connect to mssyql
db_user = "";
db_password = "";
db_name = "";
db_host = "";
System.Data.SqlClient.SqlConnection mssql_con = new System.Data.SqlClient.SqlConnection();
mssql_con.ConnectionString = "SERVER=" + db_host + ";" + "DATABASE=" +
db_name + ";" + "UID=" + db_user + ";" + "PASSWORD=" + db_password + ";";
//Create a list to store the result
List<string>[] mssql_idlist = new List<string>[2];
mssql_idlist[0] = new List<string>();
mssql_idlist[1] = new List<string>();
/*Processing logic*/
//first pass on mysql
try
{
mysql_con.Open();
//get id list
string mysql_idlist_query = "SELECT product_code FROM cscart_products";
MySqlCommand cmd = new MySqlCommand(mysql_idlist_query, mysql_con);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
mysql_idlist[0].Add(dataReader["product_code"] + "");
}
//close Data Reader
dataReader.Close();
//test content
/*foreach (var id in mysql_idlist[0]) {
lbl_dev.Text = lbl_dev.Text + id + " - ";
}*/
//close mysql connection
mysql_con.Close();
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
lbl_dev.Text = "(mysql) Cannot connect to server. Contact administrator";
break;
case 1045:
lbl_dev.Text = "(mysql) Invalid username/password, please try again";
break;
default:
lbl_dev.Text = "Unknown mysql error.";
break;
}
}
catch
{
lbl_dev.Text = "first mysql error";
}
//first pass on mssql
try
{
mssql_con.Open();
//get id list
//protect for duplicate skus
string mssql_idlist_query = "SELECT substring (RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) as SKU, ID FROM Denton_multi.dbo.JH_TblFurniture6Colour WHERE substring (RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) IN (SELECT substring(RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10))";
SqlCommand cmd = new SqlCommand(mssql_idlist_query, mssql_con);
//Create a data reader and Execute the command
SqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
mssql_idlist[0].Add(dataReader["SKU"] + "");
mssql_idlist[1].Add(dataReader["ID"] + "");
}
//close Data Reader
dataReader.Close();
mssql_con.Close();
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
lbl_dev.Text = "(mssql) Cannot connect to server. Contact administrator";
break;
case 1045:
lbl_dev.Text = "(mssql) Invalid username/password, please try again";
break;
default:
lbl_dev.Text = "Unknown mssql error. " + ex.Number; ;
break;
}
}
catch
{
lbl_dev.Text = "first mssql error";
}
//compare lists and get ids that need inserting in mysql
List<string>[] insert_idlist = new List<string>[10];
insert_idlist[0] = new List<string>();//product code
insert_idlist[1] = new List<string>();//short description
insert_idlist[2] = new List<string>();//full description
insert_idlist[3] = new List<string>();//product id
insert_idlist[4] = new List<string>();//weight
insert_idlist[5] = new List<string>();//rrp price
insert_idlist[6] = new List<string>();//our price
insert_idlist[7] = new List<string>();//categories
insert_idlist[8] = new List<string>();//denton side id
insert_idlist[9] = new List<string>();//insert / update tag
List<string> dup_list = new List<string>();
var about_to_insert = 0;
foreach (var id in mssql_idlist[0])
{
if (mysql_idlist[0].Contains(id) == false)
{
//insert list
insert_idlist[0].Add(id);
insert_idlist[9].Add("i");
}
else
{
//update_list
insert_idlist[0].Add(id);
insert_idlist[9].Add("u");
}
}
//construct full mssql dataset for insert items
//final pass on mssql
try
{
mssql_con.Open();
foreach (var id in insert_idlist[0])
{
//top 1 for duplicate removal
var mssql_select = "SELECT Denton_Multi.dbo.tblproductcategorys.*, Denton_Multi.dbo.JH_TblFurniture6Colour.*, substring(RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) as SKU, suppliers.[supplier name], (select top 1 [item description] from Denton_Multi.dbo.JH_TblFurniture4item where [supplier code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[supplier code] and [item code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[item code] And [Delete] = 0) as [item description], (select top 1 [model description] from Denton_Multi.dbo.JH_TblFurniture3Range where [supplier code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[supplier code] and [model code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[model code]) as [range description] FROM Denton_Multi.dbo.JH_TblFurniture6Colour join Denton_Multi.dbo.tblproductcategorys on Denton_Multi.dbo.tblproductcategorys.CategoryID = Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] join Denton_Multi.dbo.Suppliers on Denton_Multi.dbo.Suppliers.[supplier code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[supplier code] WHERE ExportWeb = 1 AND substring(RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) = '"+id+"'";
SqlCommand cmd = new SqlCommand(mssql_select, mssql_con);
//Create a data reader and Execute the command
SqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
insert_idlist[1].Add(dataReader["Supplier Name"] + " " + dataReader["Range Description"] + " " + dataReader["Item Description"]);
insert_idlist[3].Add(dataReader["Sale Price"] + "");
insert_idlist[2].Add(dataReader["WebDesc"] + "");
//insert_idlist[3].Add(dataReader["id"] + "");removed
insert_idlist[4].Add(dataReader["WebDimensions"] + "");
insert_idlist[5].Add(dataReader["RRP"] + "");
insert_idlist[6].Add(dataReader["Normal Price"] + "");
insert_idlist[7].Add("482"); //add me
insert_idlist[8].Add(dataReader["ID"] + "");
about_to_insert = about_to_insert + 1;
}
lbl_dyn_status.Text = "Record 0 of " + about_to_insert + "updated.";
dataReader.Close();
}
//close mysql connection
mssql_con.Close();
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
lbl_dev.Text = "(mssql) Cannot connect to server. Contact administrator";
break;
case 1045:
lbl_dev.Text = "(mssql) Invalid username/password, please try again";
break;
default:
lbl_dev.Text = "Unknown mssql error. "+ex.Number;
break;
}
}
catch
{
lbl_dev.Text = "second mssql error";
}
//insert data in mysql db
try
{
//final mysql pass
var inc = insert_idlist[0].Count() - 1;
if (about_to_insert > 0 && insert_idlist[0][0].Count() > 0)
{
mysql_con.Open();
for (int x = 0; x <= inc; x++)
{
int pid = 0;
if (insert_idlist[9][x] == "u")
{
//get web side product_id for updates
var sku = insert_idlist[0][x];
var get_id = "SELECT product_id FROM cscart_products WHERE product_code = '" + sku + "' LIMIT 1";
MySqlCommand do_get_id = new MySqlCommand(get_id, mysql_con);
MySqlDataReader rpid = do_get_id.ExecuteReader();
//get id
while (rpid.Read())
{
pid = Convert.ToInt32(rpid["product_id"]);
}
rpid.Close();
}
/*main record*/
var mysql_product = "";
if (insert_idlist[9][x] == "u")
{
mysql_product = "UPDATE cscart_products SET product_code = #product_code, list_price = #rrp, status='D' WHERE product_id = '" + pid + "'";
}
else
{
mysql_product = "INSERT INTO cscart_products (product_code, list_price, status) VALUES (#product_code, #rrp, 'D')";
}
MySqlCommand product_insert = new MySqlCommand(mysql_product, mysql_con);
product_insert.Parameters.Add(new MySqlParameter("#product_code", insert_idlist[0][x]));
product_insert.Parameters.Add(new MySqlParameter("#rrp", insert_idlist[5][x]));
product_insert.ExecuteNonQuery();
var insertid = product_insert.LastInsertedId;
//get mssql id records
var sql_ID = insert_idlist[8][x];
var stock_sql = "SELECT * FROM dbo.TblSupplierDelivery INNER JOIN dbo.TblManagerStockListings ON dbo.TblSupplierDelivery.ID = dbo.TblManagerStockListings.ID WHERE dbo.TblSupplierDelivery.ID = '" + sql_ID + "'";
mssql_con.Open();
SqlCommand cmd = new SqlCommand(stock_sql, mssql_con);
//Create a data reader and Execute the command
SqlDataReader dataReader = cmd.ExecuteReader();
//insert extended data fields
while (dataReader.Read())
{
var delivery_time = dataReader["Delivery Weeks"];
var stock_quant = Convert.ToInt16(dataReader["WHTotal"]) - Convert.ToInt16(dataReader["TotalAv"]);
var sale_price = insert_idlist[3][x];
var prod_ex = "";
if (insert_idlist[9][x] == "u")
{
prod_ex = "UPDATE cscart_oo_product_extend SET product_id = '" + pid + "', transfer_date = now(), sale_price = '" + sale_price + "', stock_due_date = '" + delivery_time + "' WHERE product_id = '" + pid + "'";
}
else
{
prod_ex = "INSERT INTO cscart_oo_product_extend (product_id, transfer_date, sale_price, stock_due_date) VALUES ('" + insertid + "', now(), '" + sale_price + "', '" + delivery_time + "')";
}
MySqlCommand product_ex_insert = new MySqlCommand(prod_ex, mysql_con);
product_ex_insert.ExecuteNonQuery();
//this is always an update
if (Convert.ToString(insertid) == "0")
{
insertid = pid;
}
var stock_insert = "UPDATE cscart_products SET amount = '" + stock_quant + "' WHERE product_id = '" + insertid + "'";
MySqlCommand product_stock_insert = new MySqlCommand(stock_insert, mysql_con);
product_stock_insert.ExecuteNonQuery();
}
//close Data Reader
dataReader.Close();
mssql_con.Close();
/*description*/
var mysql_desc = "";
if (insert_idlist[9][x] == "u")
{
mysql_desc = "UPDATE cscart_product_descriptions SET product_id = #id, product = #product_name, full_description = #product_desc WHERE product_id = #id";
}
else
{
mysql_desc = "INSERT INTO cscart_product_descriptions (product_id, product, full_description) VALUES (#id, #product_name, #product_desc)";
}
MySqlCommand product_desc = new MySqlCommand(mysql_desc, mysql_con);
product_desc.Parameters.Add(new MySqlParameter("#id", insertid));
product_desc.Parameters.Add(new MySqlParameter("#product_name", insert_idlist[1][x]));
product_desc.Parameters.Add(new MySqlParameter("#product_desc", insert_idlist[2][x]));
product_desc.ExecuteNonQuery();
//category
var mysql_cat = "";
if (insert_idlist[9][x] == "i")
{
mysql_cat = "INSERT INTO cscart_products_categories (product_id, category_id) VALUES (#id, #cat_id)";
MySqlCommand product_cat = new MySqlCommand(mysql_cat, mysql_con);
product_cat.Parameters.Add(new MySqlParameter("#id", insertid));
product_cat.Parameters.Add(new MySqlParameter("#cat_id", insert_idlist[7][x]));
product_cat.ExecuteNonQuery();
}
//price
var mysql_price = "";
if (insert_idlist[9][x] == "u")
{
mysql_price = "UPDATE cscart_product_prices SET product_id = #id, price = #our_price, lower_limit = '1' WHERE product_id = #id";
}
else
{
mysql_price = "INSERT INTO cscart_product_prices (product_id, price, lower_limit) VALUES (#id, #our_price, '1')";
}
MySqlCommand product_price = new MySqlCommand(mysql_price, mysql_con);
product_price.Parameters.Add(new MySqlParameter("#id", insertid));
product_price.Parameters.Add(new MySqlParameter("#our_price", insert_idlist[6][x]));
product_price.ExecuteNonQuery();
lbl_dyn_status.Text = "Record " + x + " of " + about_to_insert + "updated.";
}
mysql_con.Close();
}
}
catch
{
lbl_dev.Text = "upload error";
}
//reset gui timer for next idle period
minutes_left = 10;
lbl_dyn_status.Text = "Time until next automatic update: " + minutes_left + " minutes.";
guiTimer.Start();
but_exit.Enabled = true;
but_manual.Enabled = true;
}

OK. I have determined the issue is with slow response from an sql statement

Related

How to lock Oracle table using select statement in C# ? I tried using NOLOCK but still cannot lock.I'm getting conflicts while using tasks

First, I am checking the table then update the row. Within this process I am getting a conflict. Like I have Windows Forms, if I open 2 windows the same application both are working at the same time. I suspect if I use Lock can able to avoid this type of conflict. Web very easy but Windows Forms I don't know. I am using Oracle.
public Tasks GetTaskDetails()
{
Tasks tasks = new Tasks();
DataLayer datalayer = new DataLayer(_strConn);
OracleCommand ocdSelect = new OracleCommand();
Sqlquery = "SELECT * FROM basictasks NOLOCK WHERE STATUS = 1 and rownum = 1 order by TASKID";
ocdSelect.CommandText = Sqlquery;
DataTable dt = datalayer.GetResultDT(ocdSelect, false);
if (dt.Rows.Count > 0)
{
tasks.TaskID = Convert.ToInt32(dt.Rows[0]["TASKID"]);
tasks.MechineName = dt.Rows[0]["MACHINENAME"].ToString();
tasks.Parameters = dt.Rows[0]["PARAMETERS"].ToString();
tasks.TaskName = dt.Rows[0]["TASKNAME"].ToString();
tasks.Description = dt.Rows[0]["DESCRIPTION"].ToString();
tasks.Status = 2;
tasks.StartTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
tasks.FinishJob = false;
UpdateTaskDetails(tasks);
return tasks;
}
return null;
}
public void UpdateTaskDetails(Tasks task)
{
DataLayer datalayer = new DataLayer(_strConn);
OracleCommand cmd = new OracleCommand();
try
{
Sqlquery = "BEGIN ";
if (task.FinishJob)
Sqlquery += string.Format("UPDATE basictasks SET STATUS = " + task.Status + ", ENDTIME = SYSDATE,REMARK = '" + task.Remarks + "' WHERE TASKID = " + task.TaskID + " ;");
else
Sqlquery += string.Format("UPDATE basictasks SET STATUS = " + task.Status + ", STARTTIME = SYSDATE WHERE TASKID = " + task.TaskID + " ;");
Sqlquery += " END;";
datalayer.TableOperation_BySQL(Sqlquery, true);
if (datalayer != null)
datalayer.CheckTransaction(true);
}
catch(Exception ex)
{
}
}

Migrate data from informix db to sqlserver db

I try to Migrate the data for list of employees from informix db to sqlserver2012 db ,so firstly i select
-The data from the tables in informix like this :
string cmdText = "select * from permission where emp_num in( " + emplyeeRange + " ) and perm_date>=? and perm_date <=?";
DataTable permissionDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
cmdText = "select * from holid where emp_num in( " + emplyeeRange + " ) and end_date>=? and start_date<=? ";
DataTable vacationDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
cmdText = "select * from empmission where emp_num in( " + emplyeeRange + " ) and date(to_date)>=? and date(from_date)<=? ";
DataTable missionDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
-Then i delete the data from sqlserver in the same range date like this :
cmdText = "delete from permission where emp_num in( " + emplyeeRange + " ) and perm_date>=#from_date and perm_date <=#to_date";
sql_command.CommandType = CommandType.Text;
sql_command.Parameters.AddWithValue("#from_date", from_date.ToShortDateString());
sql_command.Parameters.AddWithValue("#to_date", to_date.ToShortDateString());
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "delete from holid where emp_num in( " + emplyeeRange + " ) and end_date>=#from_date and start_date<=#to_date ";
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "delete from empmission where emp_num in( " + emplyeeRange + " ) and to_date>=#from_date and from_date<=#to_date";
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
}
}
-Then Insert the updated data in sqlserver like this :
cmdText = "insert into permission select * from #permissionDT ";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#permissionDT", permissionDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.permissionType";
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "insert into holid select * from #vacationDT";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#vacationDT", vacationDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.holidType";
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "insert into empmission select * from #missionDT";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#missionDT", missionDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.empmissionType";
result = sql_command.ExecuteNonQuery();
}
}
My Main problem is :
This process takes so long time and decrease the performance of sqlserver ,How to optimize this code and the queries concerning the db operations ?
Replace your SQLCommand ("insert into holid select * from #vacationDT") by SQLBulkCopy it will write you your server a lot faster.
e.g.:
using (var sbc = new SqlBulkCopy(myCOnnection)
{
sbc.DestinationTableName = "holid";
sbc.WriteToServer(vacationDT);
}
You may have to set ColumnMappings and/or set identity insert/on-off before and after this. More on SQLBulkCopy: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx
Also, check if your DB has all the right indexes especially on start_date and end_date

C# ODBC mysql (null output)

can anyone help me? i am getting null output. though data exists in database.
string retrivenp = "select emp_email from E_details where emp_ID ='" + c_c +
"'AND emp_name = '" + s_s + "'AND emp_address = '" + n_n +
"'AND Date_joining = '" + Calendar1.SelectedDate + "'";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.ToString();
Label1.Text = url_path.ToString();
}
}
}
i think the string with many quotes is the problem when it will be executed it may give the wrong query
use command parameters it's better
string retrivenp = "select emp_email from E_details where emp_ID = ? AND emp_name = ? AND emp_address = ? AND Date_joining = ?";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
comm1.Parameters.Add("#p1", OleDbType.Int).Value = c_c;
comm1.Parameters.Add("#p2", OleDbType.Text).Value = s_s;
comm1.Parameters.Add("#p3", OleDbType.Text).Value = n_n;
comm1.Parameters.Add("#p4", OleDbType.Date).Value = Calendar1.SelectedDate;
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.GetString(0);
Label1.Text = url_path.ToString();
}
read.Close();
}
}

Tweetinvi Unable to get tweets constantly 24/7 with not getting stuck

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);
}
};

Check if a record exists in the database

I am using these lines of code to check if the record exists or not.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
But I am getting an error:
Object reference not set to an instance of an object.
I want to do:
if (UserExist > 0)
// Update record
else
// Insert record
ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method.
From MSDN;
Return Value
The first column of the first row in the result set, or a null
reference if the result set is empty.
You might need to use COUNT in your statement instead which returns the number of rows affected...
Using parameterized queries is always a good practise. It prevents SQL Injection attacks.
And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also.
As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand:
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}
The ExecuteScalar method should be used when you are really sure your query returns only one value like below:
SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
If you want the whole row then the below code should more appropriate.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
//User Exists
}
else
{
//User NOT Exists
}
sqlConnection.Open();
using (var sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "'", sqlConnection))
{
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
lblMessage.Text ="Record Already Exists.";
}
else
{
lblMessage.Text ="Record Not Exists.";
}
reader.Close();
reader.Dispose();
}
sqlConnection.Close();
MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
// Exist
}
else {
// Add
}
I would use the "count" for having always an integer as a result
SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist == 1) //anything different from 1 should be wrong
{
//Username Exist
}
try this
public static bool CheckUserData(string phone, string config)
{
string sql = #"SELECT * FROM AspNetUsers WHERE PhoneNumber = #PhoneNumber";
using (SqlConnection conn = new SqlConnection(config)
)
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#PhoneNumber", phone);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
return true; // data exist
}
else
{
return false; //data not exist
}
}
}
}
Use try catch:
try
{
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
// Update query
}
catch
{
// Insert query
}
You can write as follows:
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
//Username Exist
}
}
I was asking myself the same question, and I found no clear answers, so I created a simple test.
I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository.
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault()
If e Is Nothing Then
employees.Insert(newE)
End If
Next
2.1 seconds
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Try
employees.Insert(newE)
Catch ex As Exception
End Try
Next
3.1 seconds
sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM tblAttendance",con);
sda.Fill(dt);
string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);
if (bar >= 1){
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "empty");
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
string s = #"SELECT * FROM tbl1 WHERE CodNo = #CodNo";
SqlCommand cmd1 = new SqlCommand(s, con);
cmd1.Parameters.AddWithValue("#CodNo", txtid.Text);
con.Open();
int records = (int)cmd1.ExecuteScalar();
if (records > 0)
{
Response.Write("<script>alert('Record not Exist')</script>");
}
else
{
Response.Write("<script>alert('Record Exist')</script>");
}
}
private void insert_data()
{
SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(#CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',#image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',#NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);
flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
string img = #"~/File/" + flpimage.FileName;
flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
string img1 = #"~/Tazkiera/" + flpnidcard.FileName;
comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
comm.Parameters.AddWithValue("image", flpimage.FileName);
comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);
comm.ExecuteNonQuery();
con.Close();
Response.Redirect("~/SecondPage.aspx");
//Response.Write("<script>alert('Record Inserted')</script>");
}
}
Use the method Int.Parse() instead. It will work.
I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.
var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
if (result == null) {
register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
} else {
MessageBox.Show("User Alreay Exist. Try with Different Username");
}

Categories

Resources