I'm facing a problem where every time I refresh my page, the loan paid will increase by 500. I understand that my logic is wrong, after 1 month from the loan application date, the 'loanPaid' will increase by 500 but what I want to happen is every next month it will increase by $500. If anyone who can help me with the logic. I would appreciate it. I was thinking of using some loop but not sure which one and how. I'm a freshman student only so please pardon my coding style. Thank you
public class LoanDAL
{
string connString = ConfigurationManager.ConnectionStrings["Oakhorizons"].ToString();
public LoanDAL()
{
//
// TODO: Add constructor logic here
//
}
public DataTable getAllLoanInfoDT()
{
using (SqlConnection conn = new SqlConnection(connString))
{
DataTable dt = new DataTable();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn;
// cmd.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "SELECT DISTINCT purchaseDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
cmd2.Parameters.AddWithValue("#custID", "OH00002");
cmd2.Parameters.AddWithValue("#loanType", "Personal Loan");
conn.Open();
string custID = "OH00002";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd2;
da.Fill(dt);
int iMonthNo = int.Parse(System.DateTime.Now.Month.ToString());
DateTime dtDate = new DateTime(2000, iMonthNo, 1);
double dMonthNow = Double.Parse(dtDate.ToString("MM"));
LoanTableAdapters.LoanPortfolioTableAdapter loanAdapter = new LoanPortfolioTableAdapter();
string LoanDate = loanAdapter.RetrieveData(custID.ToString()).ToString();
string month = dt.ToString();
double dLoanDate = Double.Parse(LoanDate.Substring(3, 2));
if (dMonthNow > dLoanDate)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + 500";
sql += "WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
cmd2.Connection = conn;
cmd2.CommandText = sql;
cmd2.ExecuteNonQuery();
}
conn.Close();
}
}
After edit:
public DataTable getAllLoanInfoDT()
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn;
// cmd.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "SELECT DISTINCT loanUpdateDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
cmd2.Parameters.AddWithValue("#custID", "OH00002");
cmd2.Parameters.AddWithValue("#loanType", "Personal Loan");
conn.Open();
SqlDataReader myReader = cmd2.ExecuteReader();
DateTime loanUpdateDate = Convert.ToDateTime(myReader);
DateTime currDateTime = DateTime.Now;
int loanToBeAdded = (((currDateTime.Year - loanUpdateDate.Year) * 12) + currDateTime.Month - loanUpdateDate.Month) * 500;
if (loanToBeAdded > 0)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", loanUpdateDate = " + DateTime.Now.ToString();
sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
//Execute the above query here
}
conn.Close();
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
return dTable;
}
}
}
You have done a lot of unnecessary things, some important checks missing and some performance inhibiting mistakes also in your code but I will not point them out here since you are a freshman and you will learn gradually.
The solution to your problem should be the following
Firstly create a new column in your "LoanPortfolio" table namely "LastUpdatedLoanPaidDate". The type should be Date for this column. This will store the date when you last added $500 to "loanPaid" column.
Set this column same as "purchaseDate" when you first add a row in your "LoanPortfolio" table. So initially "purchaseDate" and "LastUpdatedLoanPaidDate" will be same.
Fetch only "LastUpdatedLoanPaidDate" instead of "purchaseDate" as
cmd2.CommandText = "SELECT DISTINCT LastUpdatedLoanPaidDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
Assuming that there will be just 1 record fetched from the above query, The following code should add $500 to "loadPaid" column once every month
//Fetch "LastUpdatedLoanPaidDate" here
//This will be "LastUpdatedLoanPaidDate" coming from database i.e. dt[0][0].ToString(). Hard-coded here for simplicity
string strLastUpdatedLoanPaidDate = "07/29/2013";
DateTime lastUpdatedLoanPaidDate = Convert.ToDateTime(strLastUpdatedLoanPaidDate);
DateTime currDateTime = DateTime.Now;
//This will make sure that all the previous purchases are also handled and not just previous month's
//This is important when you are implementing new logic on existing data
int loanToBeAdded = (((currDateTime.Year - lastUpdatedLoanPaidDate.Year) * 12) + currDateTime.Month - lastUpdatedLoanPaidDate.Month) * 500;
//If loadToBeAdded is zero then need not update database
if (loanToBeAdded > 0)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", LastUpdatedLoanPaidDate = " + DateTime.Now.ToString();
sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
//Execute the above query here
}
There might be some things which I am missing depending upon your requirement. Also the update statement might need a tweak as I have not tested it but overall this should do the trick.
Hope this helped.
Regards,
Samar
You should also indicate in your table when you increased the loan for the last time and check this value, too. You could insert a new column lastLoanIncrease in the table LoanPortFolio as char(6) and save the month and year, when you increased it. Then before increasing again check for it.
You don't need a loop.
Your issue is in your conditional if
//DateTime loanDate = new DateTime(2000, 1, 18);
DateTime loanDueDate = Foo.GetLoanDueDate(loanId);
int loanDueMonth = loanDueDate.Month;
int currentMonth = DateTime.Now.Month;
if (currentMonth > loanDueMonth)
{
// update db
loanDate.AddMonths(1);
Foo.UpdateLoanDueDate(loanId, loanDate); // increase loan due date for next month so that the conditional is true next month.
}
Related
I have a table in SQL server:
| date_Tim| Machine|Case_wrong|
|:---------|:--------:|:----------:|
|07/03/21 16:53:PM|Test1|1|
|07/03/21 16:58:PM|Test1|1|
|07/03/21 16:59:PM|Test1|1|
|07/03/21 16:58:PM|Test2|1|
|07/03/21 16:59:PM|Test2|1|
|07/03/21 17:00:PM|Test2|1|
|07/03/21 17:01:PM|Test3|1|
|08/03/21 16:58:PM|Test3|1|
|08/03/21 16:58:PM|Test2|1|
I want to sum column machine All machine from date 07/03/22 and fill to chart
I try code
private void loadchart()
{
var Today = DateTime.Now.ToString("dd/MM/yy");
ChartTop.Series[0].Points.Clear();
ChartTop.ChartAreas["ChartArea1"].AxisX.Interval = 1;
string constring = ConfigurationManager.ConnectionStrings["Connstring"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
try
{
sqlCmd.CommandText = sqlCmd.CommandText = "SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " group by Machine order by SUM(Case_wrong)";
DataSet dtRecord = new DataSet();
sqlDataAdap.Fill(dtRecord);
ChartTop.DataSource = dtRecord;
//set the member of the chart data source used to data bind to the X-values of the series
ChartTop.Series["Series1"].XValueMember = "Machine";
//set the member columns of the chart data source used to data bind to the X-values of the series
ChartTop.Series["Series1"].YValueMembers = "Case_wrong";
// ChartTop.Series[0].ChartType = SeriesChartType.Pie;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
it works but it takes all the data in my table for calculation. is there a way to filter the data by date and sum there?
Please help me! Thanks.
What appears is that date_Tim is a datetime feild , if thats the case then you need a where clause added to your query , I am assuming that the date you mentioned (07/03/22) is DD/MM/YY based on that the query needs to be updated to add the clause as below
"SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " WHERE date_Tim >='2022-03-07 00:00:00.000' group by Machine order by SUM(Case_wrong)"
Please note #madreflection has pointed out critical errors, please fix them more details about SQL injection here
Edit 1:
In case you are just looking for a specific day
"SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " WHERE CAST(date_Tim AS DATE) ='2022-03-07' group by Machine order by SUM(Case_wrong)"
In case you are looking for the current date
"SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " WHERE CAST(date_Tim AS DATE) = GETDATE() group by Machine order by SUM(Case_wrong)"
I want make a auto number based date and number at "Transaction" Form. But i have problem with make a "condition" to compare date "today" and date "yesterday". If date is different, then will make a new "autonumber" from number 1. For example, that date is 2019-08-08 so the ID from "permintaanId" is P2019080803 (two last number is how many transaction make that day). And tomorrow is 2019-08-09 will make ID P2019080901 (two last number will reset because no one transaction make)
private void auto()
{
long hitung;
string urut;
SqlConnection conn = konn.GetConn();
conn.Open();
cmd = new SqlCommand("select permintaanId from permintaan_data where permintaanId in(select max(permintaanId) from permintaan_data) order by permintaanId DESC", conn);
rd = cmd.ExecuteReader();
rd.Read();
if (rd.HasRows) //<- this condition
{
hitung = Convert.ToInt64(rd[0].ToString().Substring(rd["permintaanId"].ToString().Length - 2, 2)) + 1;
string joinstr = "00" + hitung;
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + joinstr.Substring(joinstr.Length - 2, 2);
}
else
{
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + "01";
}
rd.Close();
txt_noPermintaan.Text = urut;
conn.Close();
}
get last item created
cmd = new SqlCommand("select top1 permintaanId from permintaan_data order by DESC", conn);
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
var id = rd["the one with p and 2 numbers at the end"].ToString();
var dateLastCreated = id.ToString().Remove(0,1).Remove(id.Length-2,2);
if (dateLastCreated == DateTime.Now.ToString("yyyyMMdd"))
{
//increment
}
else
{
//create new
}
}
DECLARE #permintaanId INT=0
DECLARE #NewNo VARCHAR(40)=''
select #permintaanId=CAST(ISNULL(MAX(RIGHT(permintaanId,1)),0)+1 AS INT)
FROM permintaan_data
WHERE CAST([tranData] AS DATE) =CAST(GETDATE() AS DATE)
SET #NewNo='P'+CONVERT(VARCHAR(10),GETDATE(),112)+CAST(#permintaanId AS VARCHAR(10))
SELECT #NewNo
i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}
I am making payroll management system in which double pay salary is equal to some proportion of employee's fix pay.That proportion is given by some percentage i.e. 12% of fix pay and this percentage tends to change time by time. And when the percentage is changed then double pay value according to that percentage must also be changed in employee table.
here is my code:
string query;
query = "select count(*) from ConditionalEarnings where [Double Duty]!=0";
SqlCommand value = new SqlCommand(query,DataFind);
value.ExecuteNonQuery();
int no = Convert.ToInt32(value.ExecuteScalar());
textBox7.Text = no.ToString();
for (int o = 0; o< no; o++)
{
string query1;
query1 = "select EmpId from ConditionalEarnings where [Double Duty]!=0";
SqlCommand value1 = new SqlCommand(query1, DataFind);
value1.ExecuteNonQuery();
int id = Convert.ToInt32(value1.ExecuteScalar());
textBox8.Text = id.ToString();
string query2;
query2 = "Select EmpRunningBasic from EmployeeRunningBasic where EmpId=#id";
SqlCommand r = new SqlCommand(query2,DataFind);
r.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
r.ExecuteNonQuery();
int rb = Convert.ToInt32(r.ExecuteScalar());
int doublechange = Convert.ToInt32(textBox1.Text);
int apply = (rb * doublechange)/100;
SqlCommand f = new SqlCommand("Update ConditionalEarnings set [Double Duty]='" + apply + "' where EmpId=#id", DataFind);
f.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
f.ExecuteNonQuery();
}
And my form is as follow:
Its my form
This is my code to perform task.
When I enter percentage and execute program to update all values in that specific column of double pay, only 1st row of table is changed and all other row's cell for double duty remain unchanged. Means my program works in a loop and calculate and replace value of my first row's column again and again without going to the next row. How to apply change on all rows selected on base of same criteria?
its my table showing employee id column and double duty column highlighted
The value of double duty column is not changing for all employee ids but for only first id in table.
First you have to get the Employees (with their Running Basics) that you want to Iterate, then apply your calculation on every one then update your database
have a look at the below code , it may help you (modify the code to match your needs)
int no = 0;
string query = "select count(*) from ConditionalEarnings where [Double Duty]!=0";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
no = Convert.ToInt32(cmd.ExecuteScalar());
}
string selectQuery = "select a.EmpId,b.EmpRunningBasic from ConditionalEarnings a left join EmployeeRunningBasic b on a.EmpId=b.EmpId where a.[Double Duty]!=0";
SqlDataAdapter adapter = new SqlDataAdapter(selectQuery, DataFind);
DataTable dtEmp;
adapter.Fill(dtEmp);
textBox7.Text = no.ToString();
string updateQuery = "";
foreach (DataRow row in dtEmp)
{
string empId = row["EmpId"].ToString();
textBox8.Text = empId;
int rb = Convert.ToInt32(row["EmpRunningBasic"]);
int doublechange = Convert.ToInt32(textBox1.Text);
int apply = (rb * doublechange) / 100;
updateQuery += string.Format("Update ConditionalEarnings set [Double Duty]='{1}' where EmpId='{0}';", empId, apply);
}
if (!string.IsNullOrEmpty(updateQuery))
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(updateQuery, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
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;
}