Recreating a list with values from an updated database - c#

I would like to recreate my list after it is updated (at allocate positions) so that it includes the new columns in the position table. Is this possible? How would I go about doing it?
I've tried clearing it and attempting to read the dataReader again, but with little success, will I have to rerun the SQL query?
public List<BidList> AllocateBids()
{
// Determine positions
string query =
"SELECT t1.operator_id, t1.datetime, t1.plot_id, t1.position, t2.market_access FROM bid t1 " +
"JOIN operator t2 ON t1.operator_id = t2.id WHERE t1.status='Queued' AND t1.postcode='" + _plot + "'" +
"ORDER BY t2.market_access ASC, t1.datetime ASC";
var bidList = new List<BidList>();
var cmd = new MySqlCommand(query, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
var item = new BidList
{
OperatorId = dataReader["operator_id"] + "",
PlotId = dataReader["plot_id"] + "",
Position = dataReader["position"] + "",
Datetime = dataReader["datetime"] + "",
MarketAccess = dataReader["market_access"] + "",
};
bidList.Add(item);
}
// Allocate positions
for (var i = 0; i < bidList.Count; i++)
{
var position = i + 1;
query = "UPDATE bid SET position='" + position + "' WHERE operator_id='" + bidList[i].OperatorId +
"'";
var dbObject = new DbConnect();
dbObject.InsertBooking(query);
}
return bidList;
// Recreate list
//bidList.Clear();
//while (dataReader.Read())
//{
// var item = new BidList
// {
// OperatorId = dataReader["operator_id"] + "",
// PlotId = dataReader["plot_id"] + "",
// Position = dataReader["position"] + "",
// Datetime = dataReader["datetime"] + "",
// MarketAccess = dataReader["market_access"] + "",
// };
// bidList.Add(item);
//}
//CloseConnection();
//return bidList;
}

instead of recreate the list, if you're updating only 1 field, and it's the position one, why don't you reorder it like this:
// Allocate positions
for (var i = 0; i < bidList.Count; i++)
{
var position = i + 1;
bidList[i].Position = position;
query = "UPDATE bid SET position='" + position + "' WHERE operator_id='" + bidList[i].OperatorId +
"'";
var dbObject = new DbConnect();
dbObject.InsertBooking(query);
}
return bidList.OrderBy(bid => bid.Position);
bidList.OrderBy() will return the same List, ordered by the position values you just assigned it

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

Populate dynamically created textboxes with SQL query

I need to dynamically create controls and display some database values in them.
For now I did :
SqlCommand cmdBE = new SqlCommand("SELECT COUNT (type) FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%' ", con);
Int32 countBE = (Int32) cmdBE.ExecuteScalar();
Console.WriteLine("nb BE : " +countBE);
SqlCommand cmdBEName = new SqlCommand("SELECT codeArticleComposant FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%'", con);
SqlDataReader readerBE = cmdBEName.ExecuteReader();
if (readerBE.Read())
{
Console.WriteLine(readerBE["codeArticleComposant"].ToString());
int pointXBE = 20;
int pointYBE = 20;
panelBE.Controls.Clear();
panelBE.Focus();
for (int i = 0; i < countBE; i++)
{
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
pointYBE += 30;
}
readerBE.Close();
}
My problem is that if several Controls are created, "readerBE["codeArticleComposant"].ToString()" does not change.
How can I make it loop on the different results that I need ?
You actually need to keep reading until all the records are being read using While loop, so change your if to While like:
int i =0; // use local variable for generating controls unique names
While(readerBE.Read())
{
//............
//........... your code here
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
i++; // increment after each read
}

C# DataTable Date format in query

To start with, I would like to point out that I know to avoid using a string directly from a TextBox or DatePicker in an SQL query as is shown in the code below. After I figure out how to make this work I intend to fix all of those, but for simplicity while initially coding and testing, I am using it for now. I point this out because everything I've found on Google points that out, but then doesn't seem to give an actual answer to the real question. :) That being said, here goes...
I have an Access 2010 database (.accdb) that I need to read data from in order to fill multiple TextBoxes in WPF. No matter how I format the Date in the query, I get an Exception of one kind or another. The code I've been using is:
public void UpdateEarlyStageData(string filePath, string query)
{
List<string> departments = new List<string>();
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=" + filePath + ";" +
#"User Id=;Password=;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection))
{
System.Data.DataTable table = new System.Data.DataTable();
adapter.Fill(table);
massCellRecords.Text = table.Rows[0]["MASSCellRecords"].ToString();
massCellDials.Text = table.Rows[0]["MASSCellDials"].ToString();
massCellSaturation.Text = table.Rows[0]["MASSCellSaturation"].ToString();
massCellPercentTotal.Text = table.Rows[0]["MASSCellPercentVolume"].ToString();
massCellPercentWorked.Text = table.Rows[0]["MASSCellPassPenetration"].ToString();
massCellPassPercent.Text = table.Rows[0]["MASSCellTotalPassPenFactor"].ToString();
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void recordDateES_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
string filePath = "C:\\Dialer Team Back-End Database\\DialerTeam_be.accdb";
DateTime targetDate = DateTime.Parse(recordDateES.ToString());
//string queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #" + DateTime.Today.ToShortDateString() + "#";
string queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #" + targetDate.ToShortDateString() + "#";
//queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #" + targetDate + "#";
queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #05//02//2016#";
UpdateEarlyStageData(filePath, queryString);
}
The exceptions I've seen are:
InvalidOperationException: The provider could not determine the Double value.
This one happens when I format the query as queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #05/02/2016#";. I assume what's happening here is it's trying to divide 05 by 02, and that result by 2016.
OleDbException: Syntax error in date in query expression 'CallDate = #05//02//2016'
This one happens when I format the query as queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #05//02//2016#";. I don't know why this would be the case, as I have other queries that use this format, the only difference is that they aren't using a DataTable but rather just a direct OleDbDataReader.
Each of the commented-out lines in the code above reflects various attempts to make this work but none of them works...please help!
UPDATE:
I haven't found a solution or answer to this exactly, but I do have working code that accomplishes the same thing. Rather than use a DataTable, I'm just using an OleDbConnection directly. As this isn't really a solution to the question asked, I don't think this is really an answer per se, so I'm just going to paste the code below so that anyone having a similar issue in the future can reference this.
private void saveData_Click(object sender, RoutedEventArgs e)
{
if (departmentSelector.SelectedIndex == 2)
{
string query = "";
string filePath = "C:\\Dialer Team Back-End Database\\DialerTeam_be.accdb";
DateTime targetDate = DateTime.Parse(recordDateES.ToString());
string massCellString = "MASSCellRecords = #massCellRecords, MASSCellDials = #massCellDials, MASSCellSaturation = #massCellSaturation," +
" MASSCellPercentVolume = #massCellPercentVolume, MASSCellPassPenetration = #massCellPassPenetration, MASSCellTotalPassPenFactor = #massCellTotalPassPenFactor";
string miCellString = "MICellRecords = #miCellRecords, MICellDials = #miCellDials, MICellSaturation = #miCellSaturation," +
" MICellPercentVolume = #miCellPercentVolume, MICellPassPenetration = #miCellPassPenetration, MICellTotalPassPenFactor = #miCellTotalPassPenFactor";
string allString = "AllRecords = #allRecords, AllDials = #allDials, AllSaturation = #allSaturation," +
" AllPercentVolume = #allPercentVolume, AllPassPenetration = #allPassPenetrationOne, AllTotalPassPenFactor = #allTotalPassPenFactorOne," +
" AllPassPenetrationTwo = #allPassPenetrationTwo, AllTotalPassPenFactorTwo = #allTotalPassPenFactorTwo," +
" AllPassPenetrationThree = #allPassPenetrationThree, AllTotalPassPenFactorThree = #allTotalPassPenFactorThree";
string massString = "MASSRecords = #massRecords, MASSDials = #massDials, MASSSaturation = #massSaturation," +
" MASSPercentVolume = #massPercentVolume, MASSPassPenetration = #massPassPenetration, MASSTotalPassPenFactor = #massTotalPassPenFactor";
string nhString = "NHRecords = #nhRecords, NHDials = #nhDials, NHSaturation = #nhSaturation," +
" NHPercentVolume = #nhPercentVolume, NHPassPenetration = #nhPassPenetration, NHTotalPassPenFactor = #nhTotalPassPenFactor";
string nonContString = "NonContRecords = #nonContRecords, NonContDials = #nonContDials, NonContSaturation = #nonContSaturation," +
" NonContPercentVolume = #nonContPercentVolume, NonContPassPenetration = #nonContPassPenetration, NonContTotalPassPenFactor = #nonContTotalPassPenFactor";
string orString = "ORRecords = #orRecords, ORDials = #orDials, ORSaturation = #orSaturation," +
" ORPercentVolume = #orPercentVolume, ORPassPenetration = #orPassPenetration, ORTotalPassPenFactor = #orTotalPassPenFactor";
string combinedString = "CombinedRecords = #combinedRecords, CombinedDials = #combinedDials, CombinedSaturation = #combinedSaturation," +
" CombinedPassPenetration = #combinedPercentWorkedOne," +
" CombinedPassPenetrationTwo = #combinedPercentWorkedTwo," +
" CombinedPassPenetrationThree = #combinedPercentWorkedThree";
query = "UPDATE ESDialsPerList SET " + massCellString + ", " + miCellString + ", " + allString + ", " + massString + ", " +
nhString + ", " + nonContString + ", " + orString + ", " + combinedString +
" WHERE CallDate = #" + targetDate.ToString() + "#";
WriteEarlyStageData(filePath, query);
}
else if (departmentSelector.SelectedIndex == 3)
{
}
else if (departmentSelector.SelectedIndex == 4)
{
}
}
public void WriteEarlyStageData(string filePath, string query)
{
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=" + filePath + ";" +
#"User Id=;Password=;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
{
try
{
connection.Open();
command.Parameters.AddWithValue("#massCellRecords", Int32.Parse(massCellRecords.Text));
command.Parameters.AddWithValue("#massCellDials", Int32.Parse(massCellDials.Text));
command.Parameters.AddWithValue("#massCellSaturation", Double.Parse(massCellSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#massCellPercentVolume", Double.Parse(massCellPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#massCellPassPenetration", Double.Parse(massCellPercentWorked.Text));
command.Parameters.AddWithValue("#massCellTotalPassPenFactor", Double.Parse(massCellPassPercent.Text));
command.Parameters.AddWithValue("#miCellRecords", Int32.Parse(miCellRecords.Text));
command.Parameters.AddWithValue("#miCellDials", Int32.Parse(miCellDials.Text));
command.Parameters.AddWithValue("#miCellSaturation", Double.Parse(miCellSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#miCellPercentVolume", Double.Parse(miCellPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#miCellPassPenetration", Double.Parse(miCellPercentWorked.Text));
command.Parameters.AddWithValue("#miCellTotalPassPenFactor", Double.Parse(miCellPassPercent.Text));
command.Parameters.AddWithValue("#allRecords", Int32.Parse(allRecords.Text));
command.Parameters.AddWithValue("#allDials", Int32.Parse(allDials.Text));
command.Parameters.AddWithValue("#allSaturation", Double.Parse(allSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#allPercentVolume", Double.Parse(allPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#allPassPenetrationOne", Double.Parse(allPercentWorkedOne.Text));
command.Parameters.AddWithValue("#allTotalPassPenFactorOne", Double.Parse(allPassPercentOne.Text));
command.Parameters.AddWithValue("#allPassPenetrationTwo", Double.Parse(allPercentWorkedTwo.Text));
command.Parameters.AddWithValue("#allTotalPassPenFactorTwo", Double.Parse(allPassPercentTwo.Text));
command.Parameters.AddWithValue("#allPassPenetrationThree", Double.Parse(allPercentWorkedThree.Text));
command.Parameters.AddWithValue("#allTotalPassPenFactorThree", Double.Parse(allPassPercentThree.Text));
command.Parameters.AddWithValue("#massRecords", Int32.Parse(massRecords.Text));
command.Parameters.AddWithValue("#massDials", Int32.Parse(massDials.Text));
command.Parameters.AddWithValue("#massSaturation", Double.Parse(massSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#massPercentVolume", Double.Parse(massPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#massPassPenetration", Double.Parse(massPercentWorked.Text));
command.Parameters.AddWithValue("#massTotalPassPenFactor", Double.Parse(massPassPercent.Text));
command.Parameters.AddWithValue("#nhRecords", Int32.Parse(nhRecords.Text));
command.Parameters.AddWithValue("#nhDials", Int32.Parse(nhDials.Text));
command.Parameters.AddWithValue("#nhSaturation", Double.Parse(nhSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#nhPercentVolume", Double.Parse(nhPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#nhPassPenetration", Double.Parse(nhPercentWorked.Text));
command.Parameters.AddWithValue("#nhTotalPassPenFactor", Double.Parse(nhPassPercent.Text));
command.Parameters.AddWithValue("#nonContRecords", Int32.Parse(nonContRecords.Text));
command.Parameters.AddWithValue("#nonContDials", Int32.Parse(nonContDials.Text));
command.Parameters.AddWithValue("#nonContSaturation", Double.Parse(nonContSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#nonContPercentVolume", Double.Parse(nonContPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#nonContPassPenetration", Double.Parse(nonContPercentWorked.Text));
command.Parameters.AddWithValue("#nonContTotalPassPenFactor", Double.Parse(nonContPassPercent.Text));
command.Parameters.AddWithValue("#orRecords", Int32.Parse(orRecords.Text));
command.Parameters.AddWithValue("#orDials", Int32.Parse(orDials.Text));
command.Parameters.AddWithValue("#orSaturation", Double.Parse(orSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#orPercentVolume", Double.Parse(orPercentTotal.Text.Replace("%","")));
command.Parameters.AddWithValue("#orPassPenetration", Double.Parse(orPercentWorked.Text));
command.Parameters.AddWithValue("#orTotalPassPenFactor", Double.Parse(orPassPercent.Text));
command.Parameters.AddWithValue("#combinedRecords", Int32.Parse(combinedRecords.Text));
command.Parameters.AddWithValue("#combinedDials", Int32.Parse(combinedDials.Text));
command.Parameters.AddWithValue("#combinedSaturation", Double.Parse(combinedSaturation.Text.Replace("%","")));
command.Parameters.AddWithValue("#combinedPercentWorkedOne", Double.Parse(combinedPercentWorkedOne.Text));
command.Parameters.AddWithValue("#combinedPercentWorkedTwo", Double.Parse(combinedPercentWorkedTwo.Text));
command.Parameters.AddWithValue("#combinedPercentWorkedThree", Double.Parse(combinedPercentWorkedThree.Text));
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Why not a parameterised query?
string queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #callDate";
OleDbCommand oleCmd = new OleDbCommand(queryString);
oleCmd.Parameters.Add("#callDate", OleDbType.Date).Value = targetDate;
And a small change in the method signature too to accept an OleDbCommand instead for a string
public void UpdateEarlyStageData(string filePath, OleDbCommand queryCommand)
{
//Connection string initializer
using (OleDbConnection connection = new OleDbConnection("connectionString"))
{
queryCommand.Connection = connection;
using (OleDbDataAdapter adapter = new OleDbDataAdapter(queryCommand))
{
System.Data.DataTable table = new System.Data.DataTable();
adapter.Fill(table);
// assignment operations
}
}
}
You just need to force a non-localized format when converting the date value to a string expression:
string queryString = "SELECT * FROM ESDialsPerList WHERE CallDate = #" + DateTime.Today.ToString("yyyy'/'MM'/'dd") + "#";
string
The result string will be #2016/05/02# which Access SQL accepts.

for a single click it has to read a text file till the end of text in c#

i'm reading a text file and storing it to a data base.For a single click i'm able to read a single line from text file and it can be stored to a database.
But my text file is huge,so i need a method so that a single click will start reading the file and it can be stored to a database till the end of file.
this is my code:
Program problem = new Program();
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Billing;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
string line = "";
string billno = null;
string billdate = null;
string hosp_no = null;
string ip_no = null;
string name = null;
string test = null;
string ward = null;
string rad = null;
string pathNames = "C:\\Users\\Administrator\\Desktop\\Ex_1\\KHL.txt";
ArrayList rawData = new ArrayList();
try
{
StreamReader readFile = new StreamReader(pathNames);
do
{
//tim
if ((line = readFile.ReadLine()) != null)
{
// Console.WriteLine(line);
if (line.Contains("RADIOLOGY"))
{
rawData.Add(line);
//Console.ReadKey();
}
}
else
{
line = null;
}
} while (line != null);
int rIn = rawData.Count;
for (int i = 0; i < rIn; i++)
{
con.Open();
string[] data = (rawData[i] + "").Split('~');
string da = "";
hosp_no = data[1].Substring(data[1].Length - 8, 8);
ip_no = data[2].Substring(data[1].Length - 7, 7);
name = data[8].Replace("'", "''");
billno = data[3];
billdate = data[4].Substring(5, 2) + "/" + data[4].Substring(8, 2) + "/" + data[4].Substring(0, 4);
test = data[5];
ward = data[16];
if (data.Length == 1 && data[0] == "") da = "Finish";
else
{
cmd = new SqlCommand("insert into ex_1 values('" + hosp_no + "','" + ip_no + "','" + name.Replace(" ' ", " '' ") + "','" + billno + "','" + billdate + "','" + ward + "','" + test + "')", con);
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
con.Close();
Console.Read();
}
//Console.WriteLine(da);
Console.Read();
}
}
catch (Exception f)
{
Console.WriteLine(f.Message);
Console.Read();
}
You can use as follows
string text = System.IO.File.ReadAllText(#pathNames);
or
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#pathNames);
using (TextReader reader = File.OpenText(#"your file path"))
{
string line = reader.ReadToEnd();
Console.WriteLine(line);
}
Reader Class, ReadToEnd Method
Reader Class
File.OpenText Method

Program stops responding when deployed

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

Categories

Resources