Array of Background Worker to Read Tcpclient continuously - c#

We have developed Window service in C# to read data using TcpClient with the help of background worker. Here, we are reading data from multiple IP's so using array of background worker to achieve this. Our service works perfectly fine but after few hours one of thread stops running. For Here i am pasting functions which is related to this problem.
Calling sequence
1. StartMonitoring
2. Dowork
Assuming two rows are coming from database so two background worker objects are creating which will call backgroundWorkerFiles_DoWork function.
In backgroundWorkerFiles_DoWork function the int i = (int)e.Argument; first comes 0 then 1 and according to 0 and 1 they connect there IP with its port. But after some time i always comes 1 not 0. Intially both runs but one thread stop running and always gives 1 to connect the IP not 0.
Kindly help us out from this problem. i am also trying. I can paste complete code also if you want.
public static string SERVICE_TIMER =Convert.ToString(ConfigurationSettings.AppSettings["SERVICE_TIMER"]);
public static int READING_TIMER = Convert.ToInt32(ConfigurationSettings.AppSettings["READING_TIMER"]);
public static string PLANT = Convert.ToString(ConfigurationSettings.AppSettings["PLANT"]);
public static string FAMILY = Convert.ToString(ConfigurationSettings.AppSettings["FAMILY"]);
public static BackgroundWorker[] BackgroundWorker_Controllers = new BackgroundWorker[maxThreads];
public static TcpClient[] tcpClientRead = new TcpClient[maxThreads];
public static TcpClient[] tcpClientWrite = new TcpClient[maxThreads];
public CONTROLLERS[] listObj = new CONTROLLERS[maxThreads];
public Thread _thread;
private void startMonitoring()
{
//while (true)
//{`enter code here`
try
{
CHECK:
WriteLog("startsMonitoring");
Thread.Sleep(1000 * 20);
if (ReadSetting())
{
Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\\Control Panel\\International", "sShortDate", "dd-MMM-yyyy");
CreateTables();
query = "select * from XXES_CONTROLLERS where active='Y'";
DataTable dt = returnDataTable(query);
if (dt.Rows.Count > 0)
{
maxThreads = dt.Rows.Count;
if (maxThreads > 0)
{
BackgroundWorker_Controllers = new BackgroundWorker[maxThreads];
tcpClientRead = new TcpClient[maxThreads];
tcpClientWrite = new TcpClient[maxThreads];
listObj = new CONTROLLERS[maxThreads];
int Counter = 0;
foreach (DataRow dr in dt.Rows)
{
listObj[Counter] = new CONTROLLERS();
listObj[Counter].DID = Convert.ToString(dr["DID"]).Trim();
listObj[Counter].IP_ADDR = Convert.ToString(dr["IP_ADDR"]).Trim();
listObj[Counter].PORT = Convert.ToString(dr["PORT"]).Trim();
listObj[Counter].STAGE = Convert.ToString(dr["STAGE"]).Trim();
listObj[Counter].INPUT_MODE = Convert.ToString(dr["INPUT_MODE"]).Trim();
listObj[Counter].READING_TYPE = Convert.ToString(dr["READING_TYPE"]).Trim();
Counter++;
}
for (int f = 0; f < maxThreads; f++)
{
BackgroundWorker_Controllers[f] = new BackgroundWorker();
BackgroundWorker_Controllers[f].DoWork += new DoWorkEventHandler(backgroundWorkerFiles_DoWork);
BackgroundWorker_Controllers[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerFiles_RunWorkerCompleted);
//BackgroundWorker_Controllers[f].ProgressChanged +=
// new ProgressChangedEventHandler(backgroundWorkerFiles_ProgressChanged);
//BackgroundWorker_Controllers[f].WorkerReportsProgress = true;
BackgroundWorker_Controllers[f].WorkerSupportsCancellation = false;
}
for (int threadNum = 0; threadNum < maxThreads; threadNum++)
{
if (!BackgroundWorker_Controllers[threadNum].IsBusy)
{
BackgroundWorker_Controllers[threadNum].RunWorkerAsync(threadNum);
}
}
}
}
}
else
{
goto CHECK;
}
}
catch (Exception ex)
{
ErrorLog("Module:startMonitoring: " + ex.Message.ToString());
}
finally { }
// }
}
private void backgroundWorkerFiles_DoWork(object sender, DoWorkEventArgs e)
{
string ip = ""; bool toggle = false; DateTime todaysdate = new DateTime();
try
{
BackgroundWorker sendingWorker = (BackgroundWorker)sender;//Capture the BackgroundWorker that fired the event
int i = (int)e.Argument;
#region Main
while (!sendingWorker.CancellationPending)
{
#region MainTry
try
{
try
{
StreamWriter sw = new StreamWriter(AppPath + "\\Live.txt");
sw.WriteLine(DateTime.Now);
sw.Close();
}
catch { }
finally { }
#region WhileLOOP
todaysdate = GetServerDateTime();
if (listObj[i].toggle == false)
{
try
{ if (tcpClientRead[i].Connected) tcpClientRead[i].Close(); }
catch { }
finally { }
tcpClientRead[i] = new System.Net.Sockets.TcpClient();
tcpClientRead[i].Connect(listObj[i].IP_ADDR, Convert.ToInt32(listObj[i].PORT));
}
//if (tcpClientRead[i].Connected)
if (isPinging(listObj[i].IP_ADDR) && tcpClientRead[i].Connected)
{
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and data_type='ERROR'";
EXEC_QUERY(query);
listObj[i].toggle = true;
//NetworkStream myNetworkStream = tcpClientRead[i].GetStream();
listObj[i].myNetworkStream = tcpClientRead[i].GetStream();
if (listObj[i].myNetworkStream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
// StringBuilder myCompleteMessage = new StringBuilder();
listObj[i].myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
while (listObj[i].myNetworkStream.DataAvailable)
{
listObj[i].myNetworkStream.Flush();
numberOfBytesRead = listObj[i].myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
listObj[i].myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
Thread.Sleep(READING_TIMER);
}
if (!string.IsNullOrEmpty(Convert.ToString(listObj[i].myCompleteMessage)))
{
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and data_type='MSG'";
EXEC_QUERY(query);
//query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,SRLNO,STAGE,SCAN_DATE,DATA_TYPE) values('" + PLANT + "','" + FAMILY + "','" + Convert.ToString(listObj[i].myCompleteMessage) + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG')";
//EXEC_QUERY(query);
if (listObj[i].STAGE == "BP")
{
WriteLog("Before Paint : " + Convert.ToString(listObj[i].myCompleteMessage));
if (string.IsNullOrEmpty(BP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Length == 4)
BP_HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
if (string.IsNullOrEmpty(BP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Length != 4)
BP_JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
}
if (listObj[i].STAGE == "AP")
{
WriteLog("After Paint : " + Convert.ToString(listObj[i].myCompleteMessage).Trim());
if (string.IsNullOrEmpty(AP_HOOK) && Convert.ToString(listObj[i].myCompleteMessage).Trim().Length == 4)
AP_HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
if (string.IsNullOrEmpty(AP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Trim().Length != 4)
AP_JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
}
if (Convert.ToString(listObj[i].myCompleteMessage).Trim().Length == 4)
listObj[i].HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
else if (Convert.ToString(listObj[i].myCompleteMessage).Trim().Length > 4)
listObj[i].JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
if (!string.IsNullOrEmpty(listObj[i].HOOK) && !string.IsNullOrEmpty(listObj[i].JOB) && listObj[i].STAGE.Trim() == "BP")
{
bool isCheck = false;
Data = "";
Data = get_Col_Value("select fcode_id || '#' || ITEM_CODE || '#' || final_label_date from XXES_JOB_STATUS where jobid='" + listObj[i].JOB.Trim() + "'"); // and final_label_date is null");
if (Data.Contains('#'))
{
listObj[i].fcode_id = Convert.ToString(Data.Split('#')[0]).Trim();
listObj[i].ITEM_CODE = Convert.ToString(Data.Split('#')[1]).Trim();
listObj[i].FINAL_DATE = Convert.ToString(Data.Split('#')[2]).Trim();
}
else
{
listObj[i].FINAL_DATE=listObj[i].fcode_id = listObj[i].ITEM_CODE = "";
}
if (string.IsNullOrEmpty(listObj[i].fcode_id))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB :" + listObj[i].JOB + " is not buckleup','" + listObj[i].JOB + "')";
EXEC_QUERY(query);
WriteLog("JOB :" + listObj[i].JOB + " is not buckleup");
}
else
{
if (!string.IsNullOrEmpty(listObj[i].FINAL_DATE))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "Final sticker already taken for JOB :" + listObj[i].JOB + "','" + listObj[i].JOB + "')";
EXEC_QUERY(query);
isCheck = true;
WriteLog("Final sticker already taken for JOB :" + listObj[i].JOB + "");
}
else if (!string.IsNullOrEmpty(listObj[i].HOOK))
{
query = "select * from (select JOBID from XXES_CONTROLLERS_DATA where hook_no='" + listObj[i].HOOK.Trim() + "' order by ENTRY_DATE DESC) where rownum=1";
string jobid = get_Col_Value(query).Trim();
if (!string.IsNullOrEmpty(jobid))
{
if (CheckExits("select count(*) from XXES_JOB_STATUS where jobid='" + jobid + "' and plant_code='" + PLANT.Trim() + "' and family_code='" + FAMILY.Trim() + "' and final_label_date is null"))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB " + jobid + " already in paint shop on HOOK " + listObj[i].HOOK + "','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
isCheck = true;
WriteLog("JOB " + jobid + " already working on HOOK " + listObj[i].HOOK + "");
}
}
}
}
if (isCheck == false)
{
query = "select count(*) from XXES_CONTROLLERS_DATA where JOBID='" + listObj[i].JOB.Trim() + "' and stage='" + listObj[i].STAGE.Trim() + "' and plant_code='" + PLANT.Trim().ToUpper() + "' and FAMILY_CODE='" + FAMILY.Trim() + "'";// and flag is null";
if (CheckExits(query))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB: " + listObj[i].JOB + " Already HOOKED UP','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
WriteLog("JOB: " + listObj[i].JOB + " Already HOOKED UP");
}
}
else
{
query = #"insert into XXES_CONTROLLERS_DATA(PLANT_CODE,FAMILY_CODE,JOBID,HOOK_NO,STAGE,ENTRY_DATE,FCODE_ID,ITEM_CODE)
values('" + PLANT.Trim().ToUpper() + "','" + FAMILY.Trim().ToUpper() + "','" + listObj[i].JOB.Trim() + "','" + listObj[i].HOOK.Trim() + "','" + listObj[i].STAGE + "',SYSDATE,'" + listObj[i].fcode_id.Trim() + "','" + listObj[i].ITEM_CODE.Trim() + "')";
if (EXEC_QUERY(query))
{
WriteLog("Inserted= " + query);
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "LAST JOB: " + listObj[i].JOB + " HOOKED UP','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
WriteLog("LAST JOB: " + listObj[i].JOB + " HOOKED UP");
}
}
}
}
}
listObj[i].FINAL_DATE=listObj[i].ITEM_CODE= listObj[i].fcode_id=listObj[i].JOB = listObj[i].HOOK = "";
}
else if (!string.IsNullOrEmpty(listObj[i].HOOK) && listObj[i].STAGE.Trim() == "AP")
{
string data = "";
data = get_Col_Value("select jobid || '#' || fcode_id || '#' || ITEM_CODE from XXES_CONTROLLERS_DATA where HOOK_NO='" + listObj[i].HOOK.Trim() + "' and stage='BP' and plant_code='" + PLANT.Trim().ToUpper() + "' and FAMILY_CODE='" + FAMILY.Trim() + "' and flag is null");
if (!string.IsNullOrEmpty(data) && data.Trim().Contains('#'))
{
listObj[i].JOB = data.Split('#')[0].Trim();
listObj[i].fcode_id = data.Split('#')[1].Trim();
listObj[i].ITEM_CODE = data.Split('#')[2].Trim();
query = #"insert into XXES_CONTROLLERS_DATA(PLANT_CODE,FAMILY_CODE,JOBID,HOOK_NO,STAGE,ENTRY_DATE,FCODE_ID,ITEM_CODE)
values('" + PLANT.Trim().ToUpper() + "','" + FAMILY.Trim().ToUpper() + "','" + listObj[i].JOB.Trim() + "','" + listObj[i].HOOK.Trim() + "','" + listObj[i].STAGE + "',SYSDATE,'" + listObj[i].fcode_id.Trim() + "','" + listObj[i].ITEM_CODE.Trim() + "')";
if (EXEC_QUERY(query))
{
query = "update XXES_CONTROLLERS_DATA set flag='Y' where HOOK_NO='" + listObj[i].HOOK.Trim() + "' and flag is null";
if (EXEC_QUERY(query))
{
WriteLog("Hook :" + listObj[i].HOOK + " Out from After Paint");
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "LAST JOB: " + listObj[i].JOB + " HOOK DOWN','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
WriteLog("LAST JOB: " + listObj[i].JOB + " HOOKED DOWN");
}
}
}
}
else
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','HookNo " + listObj[i].HOOK + " not found at before paint stage or already scanned','" + listObj[i].HOOK + "')";
EXEC_QUERY(query);
WriteLog("HookNo " + listObj[i].HOOK + " not found at before paint stage or already scanned");
}
listObj[i].JOB = listObj[i].HOOK = "";
}
else if (!string.IsNullOrEmpty(listObj[i].JOB) && listObj[i].STAGE.Trim() == "AP")
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','Please scan valid Hook','" + listObj[i].JOB + "')";
EXEC_QUERY(query);
WriteLog("Please scan valid Hook");
listObj[i].JOB = listObj[i].HOOK = "";
}
}
}
}
else
{
listObj[i].toggle = false;
throw new SocketException(10060);
}
Thread.Sleep(Convert.ToInt32(SERVICE_TIMER) * 1000);
#endregion WhileLOOP
}
catch (SocketException ex)
{
#region ERROR
string error = "";
if (ex.ErrorCode.Equals(10060))
{
error = listObj[i].IP_ADDR + " not connected. Please check the network";
}
else
{
if (ex.Message.Length > 500)
error = ex.Message.Substring(0, 498);
else
error = ex.Message.ToString();
}
listObj[i].toggle = false;
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and DATA_TYPE='ERROR'";
EXEC_QUERY(query);
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'ERROR','" + error.Trim() + "')";
EXEC_QUERY(query);
ErrorLog("Module:While Connecting Controller: " + ex.Message.ToString());
if (tcpClientRead[i].Connected)
tcpClientRead[i].Close();
#endregion ERROR
}
catch (Exception ex)
{
#region ERROR
string error = "";
if (ex.Message.Length > 500)
error = ex.Message.Substring(0, 498);
else
error = ex.Message.ToString();
error = listObj[i].STAGE + "=>" + error;
listObj[i].toggle = false;
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and DATA_TYPE='ERROR'";
EXEC_QUERY(query);
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'ERROR','" + error.Trim() + "')";
EXEC_QUERY(query);
ErrorLog("Module:While Connecting Controller: " + ex.Message.ToString());
#endregion ERROR
}
finally
{
// toggle = false;
//tcpClientRead[i].Close();
}
#endregion MainTry
//}
Thread.Sleep(Convert.ToInt32(SERVICE_TIMER) * 1000);
}
#endregion MAIN
}
catch (Exception ex)
{
ErrorLog("Module:DoWork: " + ex.Message.ToString());
}
finally { }
}
public static bool isPinging(string ip)
{
bool isPing = false;
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(ip, 1000);
if (reply != null)
{
if (reply.Status.ToString().ToUpper() == "SUCCESS")
isPing = true;
else
isPing = false;
}
return isPing;
}
catch { return isPing; }
finally { }
}
//}
//private void backgroundWorkerFiles_ProgressChanged(object sender, ProgressChangedEventArgs e)
//{
// // Use this method to report progress to GUI
//}
private void backgroundWorkerFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
WriteLog("Worker Completed");
for (int i = 0; i < maxThreads; i++)//Start a for loop
{
if (tcpClientRead[i].Connected)
tcpClientRead[i].Close();
}
}
catch { }
finally { }
}

I have converted the background worker into TASK library. Now problem is solved thanks. Changed the following things:-
public static Task[] BackgroundWorker_Controllers = new Task[maxThreads]; //declration
//calling
for (int f = 0; f < maxThreads; f++)
{
var ii = f;
BackgroundWorker_Controllers[f] = new Task(() =>
{
ConnectControllers(ii, dt.Rows.Count); }, TaskCreationOptions.None);
BackgroundWorker_Controllers[f].Start();
}

Related

Operation is not valid due to current state of object while executing C# window service code

I have made a windows service in C# and while running the code, its giving the excpetion
Operation not valid due to current state of object
on ExecuteNOnQuery line. I have used similar code before but haven't faced this issue.
public void CCP_to_WRM()
{
DBConnection.Open_Connection();
//Reading data from CCP Table in Gateway PC
String sql = "select HEAT_NAME,STEEL_GRADE_ID,PRODUCTION,BILLET_STATUS,CASTER_NO from CCP_BILLET";
DBConnection.ComndCCP.CommandText = sql;
DBConnection.ComndCCP.ExecuteNonQuery(); //--> Exception occurs here.
OracleDataReader ReadWRM = DBConnection.ComndCCP.ExecuteReader();
while (ReadWRM.Read())
{
HeatId = ReadWRM[0].ToString().TrimEnd();
StGr = ReadWRM[1].ToString().TrimEnd();
BillN = int.Parse(ReadWRM[2].ToString().TrimEnd());
BS = int.Parse(ReadWRM[3].ToString().TrimEnd());
CsNo = int.Parse(ReadWRM[4].ToString().TrimEnd());
//Inserting data from CCP into Mills DB
int i = 0;
int LayerNo = 0;
int BilletId = 0;
int BilletSeq = 0;
int RowCount = 0;
//string sqlD = "delete from stg_billet where heat_id='" + InHeat + "'";
//DBConnection.ComndWRM.CommandText = sqlD;
//DBConnection.ComndWRM.ExecuteNonQuery();
string sql1 = "select layer_no from stg_bil_layer order by layer_no asc";
DBConnection.ComndWRM.CommandText = sql1;
DBConnection.ComndWRM.ExecuteNonQuery();
OracleDataReader ReadLayer = DBConnection.ComndWRM.ExecuteReader();
while (ReadLayer.Read())
{
LayerNo = int.Parse(ReadLayer[0].ToString().TrimEnd());
}
LayerNo++;
//DialogResult result2 = MessageBox.Show("Inserting"+LayerNo);
string sql2 = "insert into stg_bil_layer values ('1','BOX1'," + LayerNo + ",'SQUARE 150X150'," + BillN + "," + 0 + ",'"
+ StGr + "','" + HeatId + "'," + 2100 + "," + 12000 + "," + "'CASTER'," + "'CASTER'," + "'CASTER'," + "'$SNT',sysdate)";
//to_date('"+DateTime.Now.ToString("DD/MM/YYYY")+"','DD/MM/YYYY')
DBConnection.ComndWRM.CommandText = sql2;
int RowS = DBConnection.ComndWRM.ExecuteNonQuery();
if (RowS >= 1)
{
//DialogResult result3 = MessageBox.Show("Record Inserted !!!!"+RowS);
string sql3 = "select billet_id from stg_billet order by billet_id asc";
DBConnection.ComndWRM.CommandText = sql3;
DBConnection.ComndWRM.ExecuteNonQuery();
OracleDataReader ReadBI = DBConnection.ComndWRM.ExecuteReader();
while (ReadBI.Read())
{
BilletId = int.Parse(ReadBI[0].ToString().TrimEnd());
//BilletSeq = int.Parse(ReadBI[1].ToString().TrimEnd());
}
sql3 = "select billet_seq from stg_billet order by billet_seq asc";
DBConnection.ComndWRM.CommandText = sql3;
DBConnection.ComndWRM.ExecuteNonQuery();
OracleDataReader ReadBS = DBConnection.ComndWRM.ExecuteReader();
while (ReadBS.Read())
{
//BilletId = int.Parse(ReadBI[0].ToString().TrimEnd());
BilletSeq = int.Parse(ReadBS[0].ToString().TrimEnd());
}
//DialogResult result4 = MessageBox.Show("Bilet ID " + BilletId+'\n'+"Billet Sequence "+BilletSeq);
for (i = 0; i < BillN; i++)
{
//DialogResult result1 = MessageBox.Show("Inside Loop");
BilletId++;
BilletSeq++;
string sql4 = "insert into stg_billet values (" + BilletId + "," + BilletSeq + ","
+ 1 + ",'BOX1'," + LayerNo + "," + CsNo + ","
+ 1 + ",'" + HeatId + "'," + "'PLAN' " + ",'" + StGr + "'," + "'1234567890',"
+ 0 + ",sysdate,sysdate," + 0 + "," + 3 + "," + 1 + "," + 150 + "," + 150 + "," + 12000 + "," + 2100 + ","
+ 3 + "," + 1 + "," + 10 + "," + "'$SNT',sysdate)";
DBConnection.ComndWRM.CommandText = sql4;
int RowB = DBConnection.ComndWRM.ExecuteNonQuery();
RowCount = RowCount + RowB;
}
/*
if (RowCount >= 1)
{
DialogResult result1 = MessageBox.Show("Record Inserted !!!!" + '\n' + RowCount + " Billets");
}
DBConnection.Close_Connection();
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
*/
}
/*
else
{
DialogResult result4 = MessageBox.Show("Failed to Insert !!!!" + RowS);
DBConnection.Close_Connection();
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
*/
}
DBConnection.Close_Connection();
}
I have used a DBConnection class for making connection to the database(DBConnection).
I have even tried making connection in the same script but it didn't work.

Error with SQL Server request using data.sqlclient in UWP

I am trying to run a SQL query on my UWP code. I don't use Linq or EF. The connection to the base work and the simple requests work. This causes me problems: in a first time i populate a listview with the result of a simple request, i choose an element and i click on a searchin button. This request is call with an error:
static public ObservableCollection GetGaz(string connectionString,
string selectedOrder)
{
string GetGazQuery =
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
ObservableCollection GazList = new ObservableCollection();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetGazQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Gaz gaz = new Gaz
{
Gaz_type = reader.GetString(0),
Theorical_content = reader.GetString(1),
Made_tolerance = reader.GetDouble(2),
Gaz_lifetime = reader.GetInt32(3),
Gaz_comments = reader.GetString(4),
Poste_number = reader.GetInt32(6)
};
GazList.Add(gaz);
}
}
}
}
}
return GazList;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
}
private string selectedOrder;
public Gestion_Stock()
{
this.InitializeComponent();
SelectOrders.ItemsSource = OrdersDataHelper.GetOrders(connectionString: (Windows.UI.Xaml.Application.Current as App).ConnectionString);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
Affichage_Stock_Gaz.ItemsSource = GazDataHelper.GetGaz((Windows.UI.Xaml.Application.Current as App).ConnectionString, selectedOrder);
}
private void SelectOrders_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
ListView selectOrders = sender as ListView;
Orders orders = SelectOrders.SelectedItem as Orders;
selectedOrder = orders.Order_Number;
}
The output:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception: Incorrect syntax near the keyword 'join'
This simple request is working, i don't use a variable and "where" command.
This work:
static public ObservableCollection GetOrders(string connectionString)
{
const string GetOrdersQuery = "" +
"select " +
"tbl_607_order.start_date," +
"tbl_607_order.end_date," +
"tbl_607_provider.provider_name," +
"tbl_607_order.order_number," +
"tbl_607_order.shipping_request_active," +
"tbl_607_order.item_reception_active " +
"from " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider "
;
Someone would have any idea?
Thanks a lot!
Add the missing space by changing
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
to
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order " + // note the missing space added here
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";

XSS and SQL Injection threats found by AppScan Source

So I have been given administration on a website that is basically a company conference room reservation system, it is connected to an access database for room details and vacancies. Problem is, AppScan source is showing a risk of XSS and SQL Injection. This is the complete function in where it is indicating the occurrence of these errors.
protected void btnReserve_Click(object sender, System.EventArgs e)
{
string start_slot, end_slot, event_desc, room_id, emp_nid;
string[] date;
start_slot = ddlStart.SelectedValue;
end_slot = ddlEnd.SelectedValue;
event_desc = txtEventDesc.Text;
room_id = Server.HtmlEncode(Request.QueryString["room_id"]);
emp_nid = Regex.Replace(Request.ServerVariables["LOGON_USER"], #"^.*\\(.*)$", "$1").ToUpper();
date = Request.QueryString["date"].Split('/');
DateTime dt = new DateTime(Convert.ToInt32(date[2]),Convert.ToInt32(date[0]),Convert.ToInt32(date[1]));
string sCmdCheckConflict = #"
SELECT count(*)
FROM t_msc_event
WHERE (event_date = #" +DateTime.Parse(Request.QueryString["date"]).ToString() + #"# )
AND (room_id = " + room_id + #") AND
(
(" + start_slot + #" BETWEEN start_slot AND end_slot) OR
(" + end_slot + #" BETWEEN start_slot AND end_slot) OR
(start_slot BETWEEN " + start_slot + #" AND " + end_slot + #") OR
(end_slot BETWEEN " + start_slot + #" AND " + end_slot + "))";
OleDbCommand cmdConflictCounter = new OleDbCommand(sCmdCheckConflict, cn);
int n;
int event_id;
try
{
cn.Open();
n = (int) cmdConflictCounter.ExecuteScalar();
string Msg;
if (n>0)
{
Msg = "<script language=javascript>alert('Chosen time is not possible due to a conflict.');</script>";
}
else
{
#region MS Access related region
OleDbCommand cmdgetMaxId = new OleDbCommand("select max(event_id) from t_msc_event", cn);
string sCmdInsert;
OleDbCommand cmdInsertEvent = null;
event_id = 0; bool success = false; int trials = 0;
do
{
try
{
event_id = (int) cmdgetMaxId.ExecuteScalar() + 1;
}
catch
{
event_id = 0;
}
sCmdInsert = #"
insert into t_msc_event (event_id,
emp_nid, event_desc, event_date,
start_slot, end_slot, room_id
) values (" + event_id + #",
'" + Server.HtmlEncode(emp_nid) + "', '" + Server.HtmlEncode(event_desc.Replace("'", "''")) + "', #" + dt.ToShortDateString() + "#, " +
start_slot + ", " + end_slot + ", " + room_id + ")";
cmdInsertEvent = new OleDbCommand(sCmdInsert, cn);
cmdInsertEvent.ExecuteNonQuery();
success = true;
} while ((!success) && (trials <=5));
OleDbDataAdapter daGetSlots = new OleDbDataAdapter("select slot_id, left(slot_desc,5) as slot_start, right(slot_desc,5) as slot_end from t_msc_slot order by slot_id", cn);
DataTable dtSlotInfo = new DataTable();
daGetSlots.Fill(dtSlotInfo);
OleDbCommand cmdGetRoolTitle = new OleDbCommand("select room_title from t_msc_room where room_id=" + Server.HtmlEncode(room_id), cn);
string room_title = (string) cmdGetRoolTitle.ExecuteScalar();
string msg = "Dear " + emp_nid +
",<br><br>This is to confirm your reservation of " +
room_title +
" on " + dt.ToShortDateString() + " from " +
dtSlotInfo.Rows[Convert.ToInt32(start_slot)]["slot_start"].ToString() + " to " +
dtSlotInfo.Rows[Convert.ToInt32(end_slot)]["slot_end"].ToString() + "." +
"<br><br>In case you want to cancel, go to " +
"<a href='" + Regex.Replace(Request.Url.ToString(), #"^(.*)/.*\.aspx\?*.*$", "$1/MyReservations.aspx") + "'>" +
"MS Conference Rooms Reservation -> MyReservatios</a>";
#endregion
string subject = "MS Conference Room Reservation Confirmation [id=" + event_id + "]";
try
{
SendEmail(emp_nid, subject, msg);
Msg = "<script language=javascript>alert('Room successfully reserved. You should receive a confirmation email shortly.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
catch
{
Msg = "<script language=javascript>alert('Room successfully reserved.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
}
Response.Write(Msg);
}
catch (Exception x)
{
Response.Write(x.ToString());
string Msg;
Msg = "<script language=javascript>alert('Error: " + x.ToString() + "');</script>";
Response.Write(Msg);
}
finally
{
cn.Close();
}
}
Sorry for having to show you the whole function as I have really no idea what I need to do here, this isn't my app.
what I did do is 1) Enable Request Validation in ASP.NET 2) encode user input by using Server.HtmlEncode(); but it is still reporting the same thing. Note that both start_slot and end_slot are DDLs so I thought I wouldn't need to encode/check them before sending. Would you please help me in modifying this code to neglect harmful user input? Thank you loads.
The correct way to use parameterized SQL query is
string commandText = "UPDATE ProductDetails
SET ProductQuantity = #quantity WHERE ProductId = #productId";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#productId", "P123");
command.Parameters.AddWithValue("#quantity", 10);
You can safely replace the "P123" with user provided input now.

Possible solution for locking the table in sqlserver using asp.net

I have been working on a software which uses database which is shared with multiple PCs. The project is all about to store missing baggage information. We have given a facility to copy the newly inserted record into the master DB.
Now what here happens is when multiple users are trying to update the db at the same time single item get stored for multiple time in the global DB.
So I have tried to use TableLock using serializable but I got nothing here.
Edit
query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN TRANSACTION;";
insertdata(query); //using cmd.ExecuteNonQuery();
query = "select * from Goods WITH (TABLOCKX)" ;
DataSet dsGoods = getdata(query, "config");//Function to get the data
updateitem();
query = "COMMIT TRANSACTION";
insertdata(query);//using cmd.ExecuteNonQuery();
And the updateitem() is as follow
public static void updateitem()
{
string query = "select * from config where param='lastsync'";
DataSet ds = dataaccess.getdata(query, "config");
query = "select isonlive,associateid,itemid,founddate,regdate,status,foundbyname,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,showonline,officeid,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item ";
String updatedDate =ds.Tables[0].Rows[0]["value"].ToString();
if (updatedDate != "")
{
query = "select isonlive,associateid,itemid,founddate,regdate,foundbyname,status,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,officeid,showonline,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item where updateat >= #updateat";
}
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(query);
if (updatedDate != "")
{
cmd.Parameters.AddWithValue("#updateat",DateTime.ParseExact(updatedDate,"dd-MM-yyyy HH:mm:ss",null,System.Globalization.DateTimeStyles.None));
}
DataRow dr;
ds = dataaccess.getdata(cmd, "item");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
int status = 0;
dr = ds.Tables[0].Rows[i];
if (dr["status"].ToString() == "Transferred")
{
status = 2;
}
else if (dr["status"].ToString() != "Received")
{
status = 1;
}
DateTime regdate = Convert.ToDateTime(dr["regdate"]);
DateTime founddate = Convert.ToDateTime(dr["founddate"]);
//returndatetime = String.Format("MMM dd yyyy H:mm:ss", returndate);
if (dr["showonline"].ToString() == "False")
{
status = 1;
}
if (dr["isdeleted"].ToString() == "true")
{
insertdata("delete from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'");
continue;
}
if (dr["isonlive"].ToString() == "true")
{
query = "update goods set Status='" + status + "',officeid='" + dr["officeID"] + "', notes='" + dr["notes"].ToString().Replace("'", "''") + "',ReturnedTo='" + dr["returnedtoname"].ToString().Replace("'", "''") + "',founddate=#founddate,ReturnedDate=#returndate,ReturnedBy='" + dr["returnedby"].ToString().Replace("'", "''") +
"',Model='" + dr["model"].ToString().Replace("'", "''") + "',ColorID='" + dr["color"].ToString().Replace("'", "''") + "',FoundWhere='" + dr["foundwhere"].ToString().Replace("'", "''") + "',MainCat='" + dr["categoryid"] + "',SubCat='" + dr["subcatid"] + "',ItemID='" + dr["item"] + "' where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'";
}
else
{
query = "select * from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "' and MainCat='" + dr["categoryid"] + "' and SubCat='" + dr["subcatid"] + "' and ItemID='" + dr["item"] + "'";
DataSet dsItems = getdata(query, "config");
if(dsItems.Tables[0].Rows.Count==0)
{
query = "insert into goods (AssociateID,ID,DateReg,Status,MainCat,SubCat,ItemID,Model,ColorID,FoundWhere,RegBy,FoundBy,ReturnedTo,ReturnedDate,ReturnedBy,Notes,IP,founddate,officeid) values('" + dr["associateid"] + "','" + dr["itemid"] + "',#regdate,'" + status + "'," +
"'" + dr["categoryid"] + "','" + dr["subcatid"] + "','" + dr["item"] + "','" + dr["model"].ToString().Replace("'", "''") + "','" + dr["color"].ToString().Replace("'", "''") + "'," +
"'" + dr["foundwhere"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["returnedtoname"].ToString().Replace("'", "''") + "',#returndate," +
"'" + dr["returnedby"].ToString().Replace("'", "''") + "','" + dr["notes"].ToString().Replace("'", "''") + "','',#founddate,'" + dr["officeID"].ToString() + "')";
}
}
SqlCommand sce = new SqlCommand(query);
if (dr["returneddate"].ToString() != "")
{
sce.Parameters.AddWithValue("#returndate", Convert.ToDateTime(dr["returneddate"]));
}
else
{
sce.Parameters.Add("#returndate", SqlDbType.DateTime).Value = DBNull.Value;
}
sce.Parameters.AddWithValue("#regdate", regdate);
sce.Parameters.AddWithValue("#founddate", founddate);
insertdata(sce);
query = "update item set isonlive = 'true',updateat=#updateDate where itemid = '" + dr["itemid"] + "'";
sce = new SqlCommand(query);
sce.Parameters.AddWithValue("#updateDate", DateTime.Now);
dataaccess.insertdata(sce);
}
catch (Exception ex)
{
App.writelog(ex.Message + "\n" + ex.StackTrace);
}
}
}
P.S.: I want it to be done though ASP.Net.

Button click fires text changed event

I have a textbox with autopostback property true and a button for saving.
On text changed, I get data from a database, and display in other textboxes. When I edit the textboxes and then save, the textchanged event fires, and the data does not update. Instead it saves the previous data only. I want to save the edited data.
Can anyone help me do this?
Here is the button click event:
protected void btnSave_Click(object sender, EventArgs e)
{
//TextBox1.Text = exists;
if(exists=="yes")
{
OdbcConnection DbConnection2 = new OdbcConnection(con1);
OdbcCommand DbCommand2 = DbConnection2.CreateCommand();
try
{
DbConnection2.Open();
DbCommand2.CommandText = "update tbl_trip_login set username='" + txtUser.Text.ToUpper() + "',password='" + txtPwd.Text + "',name='" + txtname.Text + "',department='" + txtDept.Text + "',designation='" + txtDesg.Text + "',DOJ='" + txtDOJ.Text + "',DOB='" + txtDOJ.Text + "',phone='" + txtPh.Text + "',Email='" + txtEmail.Text + "',Gender='" + rdbGender.SelectedItem.Text + "',Active='" + rdbActive.SelectedItem.Text + "' where upper(username)=upper('" + txtUser.Text + "')";
TextBox1.Text = DbCommand2.CommandText.ToString();
int t2 = DbCommand2.ExecuteNonQuery();
if (t2 == 1)
{
lblError.Visible = true;
lblError.Text = "Successfully Saved";
}
else
{
lblError.Text = "Not Saved.. Try again later";
lblError.Visible = true;
}
DbConnection2.Close();
}
catch (Exception e1)
{
lblError.Text = e1.Message;
lblError.Visible = true;
DbConnection2.Close();
}
}
else //if user doesn't exists,create new user
{
DateTime dd = DateTime.Now; //current date and time
string custom = dd.ToString("dd-MMM-yyyy,hh:mm,tt"); // to convert in the form : 14-APR-2013 01:35 PM
string ss = "to_date('" + custom + "','dd-mon-yyyy HH:MI AM')"; // oracle does not take only time by default, so use to_date(), and pass this string variable directly in the query
OdbcConnection DbConnection1 = new OdbcConnection(con1);
OdbcCommand DbCommand1 = DbConnection1.CreateCommand();
try
{
DbConnection1.Open();
DbCommand1.CommandText = "insert into tbl_trip_login(username,password,name,department,designation,DOJ,DOB,phone,Email,Gender,Active,Entered_by,Entered_time)values('" + txtUser.Text + "','" + txtPwd.Text + "','" + txtname.Text + "','" + txtDept.Text + "','" + txtDesg.Text + "','" + txtDOJ.Text + "','" + txtDOB.Text + "','" + txtPh.Text + "','" + txtEmail.Text + "','" + rdbGender.SelectedItem.Text + "','" + rdbActive.SelectedItem.Text + "','" + Session["UserAuthentication"].ToString() + "','" + ss + "')";
TextBox1.Text = DbCommand1.CommandText.ToString();
int t1 = DbCommand1.ExecuteNonQuery();
if (t1 == 1)
{
lblError.Visible = true;
lblError.Text = "Successfully Saved";
}
else
{
lblError.Text = "Not Saved.. Try again later";
lblError.Visible = true;
}
DbConnection1.Close();
}
catch (Exception e1)
{
lblError.Text = e1.Message;
lblError.Visible = true;
DbConnection1.Close();
}
txtUser.Focus();
txtUser.Text = "";
txtPwd.Text = "green";
}
}
And the Text Changed event:
protected void txtUser_TextChanged(object sender, EventArgs e)
{
var targetID = Request.Form["__EVENTTARGET"];
if (targetID != null && targetID != string.Empty)
{
btnSave.Enabled = true;
exists = "no";
try
{
OdbcConnection myOdbcConnection = new OdbcConnection(con1);
OdbcCommand myOdbcCommand = myOdbcConnection.CreateCommand();
string sSQL = "select username,password,name,department,designation,doj,dob,phone,email,gender,active from tbl_trip_login where upper(username)=upper('" + txtUser.Text + "')";
myOdbcCommand.CommandText = sSQL;
myOdbcConnection.Open();
OdbcDataReader myOdbcDataReader = myOdbcCommand.ExecuteReader();
if (myOdbcDataReader.HasRows)
{
exists = "yes";
txtPwd.Text = myOdbcDataReader[1].ToString();
txtname.Text = myOdbcDataReader[2].ToString();
txtDept.Text = myOdbcDataReader[3].ToString();
txtDesg.Text = myOdbcDataReader[4].ToString();
txtDOJ.Text = myOdbcDataReader[5].ToString();
txtDOB.Text = myOdbcDataReader[6].ToString();
txtPh.Text = myOdbcDataReader[7].ToString();
txtEmail.Text = myOdbcDataReader[8].ToString();
rdbGender.Text = myOdbcDataReader[9].ToString();
rdbActive.Text = myOdbcDataReader[10].ToString();
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
}

Categories