Using UPDATE in my loop? - c#

string inserttest = "UPDATE Warranty([LenovoBaseWarrantyStartDate], [LenovoBaseWarrantyEndDate], [LenovoBaseWarrantyStatus])"
+ "VALUES (#LenovoBaseWarrantyStartDate, #LenovoBaseWarrantyEndDate, #LenovoBaseWarrantyStatus)";
OleDbCommand cmd = new OleDbCommand(inserttest, conn1);
OleDbCommand accessCommand = conn1.CreateCommand();
accessCommand.CommandText = ("SELECT SerialNumber from Warranty");
OleDbDataReader accessReader = accessCommand.ExecuteReader();
int count = accessReader.FieldCount;
List<StoreClass> storeList = new List<StoreClass>();
while (accessReader.Read())
{
for (int i = 0; i < count; i++)
{
string result = accessReader.GetValue(i).ToString();
webBrowser1.Document.GetElementById("serialCode").Focus();
webBrowser1.Document.GetElementById("serialCode").InnerText = result;
webBrowser1.Document.GetElementById("warrantySubmit").InvokeMember("Click");
Thread.Sleep(500);
MessageBox.Show("Serial Number:" + " " + result);
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
if (el.GetAttribute("className") == "fluid-row Borderfluid")
{
string record = el.InnerText;
var result1 = parseString(record);
string StartDate = string.Join("", result1.ConvertAll(r => string.Format("{0}", r)).ToArray());
DateTime strStartDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
string EndDate = string.Join("", result1.ConvertAll(r => string.Format("{1}", r)).ToArray());
DateTime strEndDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
string Status = string.Join("", result1.ConvertAll(r => string.Format("{2}", r)).ToArray());
bool strStatus = "Active" == "1" && "Expired" == "0";
storeList.Add(new StoreClass(strStartDate, strEndDate, strStatus));
cmd.Parameters.Add("#LenovoBaseWarrantyStartDate", OleDbType.Date).Value = storeList[0].startDate;
cmd.Parameters.Add("#LenovoBaseWarrantyEndDate", OleDbType.Date).Value = storeList[0].endDate;
cmd.Parameters.Add("#LenovoBaseWarrantyStatus", OleDbType.Boolean).Value = storeList[0].status;
cmd.Parameters.Add("#LenovoWarrantyUpgradeStartDate", OleDbType.Date).Value = storeList[1].startDate;
cmd.Parameters.Add("#LenovoWarrantyUpgradeEndDate", OleDbType.Date).Value = storeList[1].endDate;
cmd.Parameters.Add("#LenovoWarrantyUpgradeStatus", OleDbType.Boolean).Value = storeList[1].status;
cmd.Parameters.Add("#LenovoPrioritySupportStartDate", OleDbType.Date).Value = storeList[2].startDate;
cmd.Parameters.Add("#LenovoPrioritySupportEndDate", OleDbType.Date).Value = storeList[2].endDate;
cmd.Parameters.Add("#LenovoPrioritySupportStatus", OleDbType.Boolean).Value = storeList[2].status;
//...
}
//...
}
//...
}
Sorry for the wall of code but its to give you an idea of what I am trying to figure out. I have this loop to retrieve data and store it into a database table. I am trying to edit my inserttest statement at the top so I can update the columns in the specific Serial Number it is currently looping through.
Is there a way to do this? I can't do Update Warranty ... Where SerialNumber = result cause it only exists in the loop (unless I can and I just dont know how).

You pass it in as another parameter, and add the where clause
WHERE SerialNumber = #result

Related

how to auto generate id from date in asp.net c#

i want to auto generate Id from date entered by user.
Example: date is 12/05/2017 than id must 170001 or 5/10/2014 than id must 140001
private void autogeneratedocno()
{
con.Open();
string check="select count(Doc_no) from
complaint";
SqlCommand cmd2 = new SqlCommand(check,con);
int a =Convert.ToInt32(cmd2.ExecuteScalar());
string date = txtdate.Text.ToString();
string year = date.Substring(8, 2);
//string[] arrDate = date.Split('/');
//string day = arrDate[0].ToString();
//string month = arrDate[1].ToString();
//string year = arrDate[2].ToString();
//string y = year.Substring(2, 2);
if (a == 0)
{
txtdocno.Text = string.Concat( year.ToString()
+ "00000");
}
else
{
string count = "select ISNULL(MAX(Doc_no),0)+1
from complaint";
SqlCommand cmd = new SqlCommand(count, con);
int doc_no =
Convert.ToInt32(cmd.ExecuteScalar());
txtdocno.Text = doc_no.ToString();
}
con.Close();
}
by using above code. i am able to generate id for year 2017 but when i change the year the first two digits are not changing.
please suggest me changes to autogenerate ID
lbldate.Text = Convert.ToDateTime(DateTime.Now.AddYears(-3)).ToString("dd/MM/yyyy");
string Year = lbldate.Text.Substring(8, 2);
lblYear.Text = Year;
This may help you solve the problem you are having, but you may find you will have other issues down the line.
I opted to converting the string input to a DateTime as you cannot guarantee what a user will input. What if they enter the date like 2017-01-01.
For instance this will fail for 2009 as the int.parse will remove the leading zeros.
string date = "01/01/2017"; //example date
DateTime d = DateTime.Parse(date); //convert string into datetime
var i = int.Parse(d.ToString("yy00000")); //format and convert to int
int docno = i + count
You should maybe look at generating a number from the database or possibly using a GUID
private void autogeneratedocno()
{
string str1 = txtdate.Text;
string[] s1 = str1.Split('/');
str1 = s1[1].ToString() + "/" + s1[0].ToString() +
"/" + s1[2].ToString();
string yy = s1[2].ToString();
string mm = s1[1].ToString();
string dd = s1[0].ToString();
int y = Convert.ToInt32(yy);
int m = Convert.ToInt32(mm);
string z = yy.Substring(2,2);
string sqlno =" selectisnull(max(substring
(doc_no,3,5)),0)+1 from complaint where
substring(doc_no,1,2) = '"+z+"'";
con.Open();
SqlCommand cmd = new SqlCommand(sqlno, con);
string getno =
Convert.ToString(cmd.ExecuteScalar());
con.Close();
string Inquiry_code = yy.Substring(2, 2) +
getno.ToString().PadLeft(5, '0');
txtdocno.Text = Inquiry_code;
}
finally got the answer.
Please Suggest if you have other Ideas to do this.

DataReader is not fetching the values from MySqlDatabase

I have a datagridview that holds the bio_id and email. I am iterating through the datagridview to get the time records of the employee based on the bio_id and dates. If I create a MySql syntax in the MySql itself, it gets the right value but when I use the MySqlDataReader, it gives me a null value. Below are the codes:
public MySqlDataReader SendTimeLogs(string fromDate, string toDate, int bioId)
{
using (var cn = new DatabaseConnection().ConnectToMySql())
{
const string query = #"SELECT MIN(scan_time) as 'Time In', MAX(scan_time) as 'Time Out',
TIMEDIFF(MAX(scan_time),MIN(scan_time)) as difference
FROM `filtered_dates`
WHERE bio_id = #bioId AND date BETWEEN #fromDate AND #toDate GROUP BY date ORDER BY date asc";
var cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.Parameters.AddWithValue("#fromDate", fromDate);
cmd.Parameters.AddWithValue("#toDate", toDate);
cmd.Parameters.AddWithValue("#bioId", bioId);
return cmd.ExecuteReader();
}
}
private void SendEmail()
{
var rdr = new EmployeeDataAccess().GetBioIdEmail();
while (rdr.HasRows && rdr.Read())
{
dgvBioIdList.Rows.Add(rdr["bio_id"].ToString(), rdr["email_add"].ToString());
}
for (var i = 0; i < dgvBioIdList.Rows.Count; i++)
{
var message = "Time Logs for Bio ID: " +dgvBioIdList.Rows[i].Cells[0].Value;
var x = new FilteredDatesDataAccess();
var timeLogs = x.SendTimeLogs(dtpStart.Text, dtpStop.Text,
Convert.ToInt32(dgvBioIdList.Rows[i].Cells[0].Value));
var rec = dgvBioIdList.Rows[0].Cells[1].Value.ToString();
Console.WriteLine(message);
Console.WriteLine(rec);
while (timeLogs.HasRows && timeLogs.Read())
{
Console.WriteLine(timeLogs["Time In"] + #" - " + timeLogs["Time Out"]);
}
}
}
I get the Console.WriteLine(message); and Console.WriteLine(rec); just fine but my while loop is not being written in the console. Can you help? Thank you.

Continuation about Getting date between two dates

My datagridview displays date with the year 2015, even if I set my two datetimepickers from two different dates but with the same year (2016).
Heres my code..
public static List<Retailer> GetDataAllRetailer(DateTime past, DateTime present)
{
List<Retailer> data = new List<Retailer>();
MySqlConnection con = DBConnection.ConnectDatabase();
try
{ // AND
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE (date BETWEEN '" + past.ToString("MM-dd-yyyy") + "' AND '" + present.ToString("MM-dd-yyyy") + "') ", con);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Retailer rawData = new Retailer();
rawData.Date = reader.GetString(1);
rawData.Walletid = reader.GetString(0);
rawData.Fname = reader.GetString(2);
rawData.Lname = reader.GetString(3);
rawData.Birthdate = reader.GetString(4);
rawData.Address = reader.GetString(5);
rawData.Province = reader.GetString(6);
rawData.City = reader.GetString(7);
rawData.Balance = reader.GetDouble(8);
rawData.Frozen = reader.GetDouble(9);
rawData.Sponsor_id = reader.GetString(10);
rawData.Share = reader.GetDecimal(11);
rawData.Email = reader.GetString(12);
rawData.Password = reader.GetString(13);
rawData.Type = reader.GetInt32(14);
data.Add(rawData);
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
return data;
}
}
If the table column is varchar, then I suggest you to convert it to date to do the search appropriately as follows:
SELECT * FROM Table WHERE
CONVERT(DATE, FromDate) >= CONVERT(DATE, '2016-09-03')
AND CONVERT(DATE, ToDate) <= CONVERT(DATE, '2016-09-13')

ORA-01036: illegal variable name/number while updating gridview

I want to update a cell of the row in gridview. But I am getting error as
ORA-01036: illegal variable name/number
at cmd.ExecuteNonQuery()
Here is my code below:-
protected void SaveChanges(object sender, EventArgs e)
{
myConn.Open();
string excelData = Grid1ExcelData.Value;
string excelDeletedIds = Grid1ExcelDeletedIds.Value;
string[] rowSeparator = new string[] { "|*row*|" };
string[] cellSeparator = new string[] { "|*cell*|" };
string[] dataRows = excelData.Split(rowSeparator, StringSplitOptions.None);
for (int i = 0; i < dataRows.Length; i++)
{
string[] dataCells = dataRows[i].Split(cellSeparator, StringSplitOptions.None);
string mkey = dataCells[0];
string shipName = dataCells[1];
string shipCity = dataCells[2];
string shipAddress = dataCells[3];
string shipCountry = dataCells[4];
string orderDate = dataCells[5];
bool sent = dataCells[6] == "yes";
string insertUpdateQuery = "";
if (!string.IsNullOrEmpty(mkey))
{
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = #ShipName, ShipCity = #ShipCity, ShipAddress = #ShipAddress, ShipCountry = #ShipCountry, OrderDate = #OrderDate, Sent = #Sent WHERE MKEY = #MKEY";
}
else
{
insertUpdateQuery = "INSERT INTO B_Order_new (ShipName, ShipCity, ShipAddress, ShipCountry, OrderDate, Sent) " +
"VALUES(#ShipName, #ShipCity, #ShipAddress, #ShipCountry, #OrderDate, #Sent)";
}
OracleCommand cmd = new OracleCommand(insertUpdateQuery, myConn);
var orderedOn = DateTime.ParseExact(orderDate, "dd/MM/yyyy", null);
cmd.Parameters.Add("#ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("#ShipCity", OracleType.VarChar).Value = shipCity;
cmd.Parameters.Add("#ShipAddress", OracleType.VarChar).Value = shipAddress;
cmd.Parameters.Add("#ShipCountry", OracleType.VarChar).Value = shipCountry;
cmd.Parameters.Add("#OrderDate", OracleType.DateTime).Value = orderedOn;
cmd.Parameters.Add("#Sent", OracleType.Char).Value = true;
if (!string.IsNullOrEmpty(mkey))
{
cmd.Parameters.Add("#MKEY", OracleType.Number).Value = mkey;
}
cmd.ExecuteNonQuery();
if (insertUpdateQuery != "")
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "CloseScript", "alert('Data Updated succesfully');", true);
}
}
if (!string.IsNullOrEmpty(excelDeletedIds))
{
OracleCommand deleteComm = new OracleCommand("DELETE FROM Orders WHERE OrderID IN (" + excelDeletedIds + ")", myConn);
deleteComm.ExecuteNonQuery();
}
myConn.Close();
Grid1.DataBind();
}
The problem is that you are using the wrong bind variable syntax (looks like you're using SQL Server parameter binding syntax). Oracle's ADO.NET provider expects you to use a : prefix rather than a #.
So try something like this instead:
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = :ShipName, ShipCity = :ShipCity, ...
And then when setting the values, you don't need to prefix it:
cmd.Parameters.Add("ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("ShipCity", OracleType.VarChar).Value = shipCity;
...
EDIT
Also, if you are binding the parameters by name, make sure you set the OracleCommand.BindByName property to true. Otherwise, the binding will be done positionally.

Reset Autonumber in C# based on year and date using oracle database

i have auto generate number create automatically in C#. this sample like this PPP-150500001 , PPP-150500002 => PPP- is a string never change, 15 is a year, 05 is a date, and 00001 is auto generate number.
How Can i reset auto number after get a new year like PPP-160100001 .
this is my method:
public void NomerUrut()
{
long hitung;
string urut;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOPERMOHONAN FROM PERMOHONAN WHERE NOPERMOHONAN IN (SELECT MAX(NOPERMOHONAN)
FROM PERMOHONAN) ORDER BY NOPERMOHONAN DESC";
cmd.Connection = koneksi_manual.con;
koneksi_manual.con.Open(); //open connection
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
hitung = Convert.ToInt64(dr[0].ToString().Substring(dr["NOPERMOHONAN"].ToString().Length - 5, 5)) + 1;
string joinstr = "00000" + hitung;
DateTime dt = DateTime.Now; // take years and date in autonumber
urut = "PPP-" + dt.ToString("yy") + dt.ToString("MM") + joinstr.Substring(joinstr.Length - 5, 5);
//it will show PPP-150500002, PPP-150500003, etc
//how can i reset this autonumber after get new years like PPP-160100001
}
else
{
urut = "PPP-150500001"; // first form load will display this default autonumber
}
dr.Close();
txtNoPermohonan.Text = urut; //display auto generate number in a textbox
koneksi_manual.con.Close(); //close connection
}
Solved.
i have update for this question and i can finish it using another query to solve my problem. i can reset it every years..
this my update code:
public static string GenerateKodeUrut()
{
string nomor = "";
string date = DateTime.Now.ToString("yyyy/MM/dd").Substring(2, 2);
DateTime dt = DateTime.Now;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = (#"SELECT NOPERMOHONAN from PERMOHONAN
where substr(NOPERMOHONAN, 5,2) ='" + date + "' ORDER BY cast(substr(NOPERMOHONAN, 9,5) as number) DESC");
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
string nmrTerakhir = (dr["NOPERMOHONAN"]).ToString().Remove(0, 8);
nomor = "PPP-" + date + dt.ToString("MM") + (Convert.ToInt32(nmrTerakhir) + 1).ToString("0000#");
}
else
{
nomor = "PPP-" + date + dt.ToString("MM") + "00001";
}
return nomor;
}
you can make a flage in your db to check it && your date.
i hope that code give you my idea
bool flage = false;
int checkdate = Convert.ToInt16(dt.ToString("MM"));
if (checkdate == 12) {
flage = true;
}
if (flage == true && checkdate == 1) {
//Write Your Code Here
flage = false;
}

Categories

Resources