I want to make a library system in C#. In this system when a book is issued it should automatically reduce the book quantity in database. When book quantity == 0 there should be a message box showing "not available".
This is my code:
private void btnIssue_Click(object sender, EventArgs e)
{
if (cmbResID.Text != "" && cmbMemID.Text != "" && cmbBookID.Text != "" && txtBkTitle.Text != "" && txtCategory.Text != "" && txtAuthor.Text != "" && txtIssueDate.Text != "" && txtActDate.Text != "")
{
SqlCommand Quantity = new SqlCommand("Select * from tblBookDetails where Book_ID = '" + cmbBookID.Text +"'");
DataSet ds = Library.Select(Quantity);
if (ds.Tables[0].Rows.Count > 0)
{
textBox1.Text = ds.Tables[0].Rows[0].ItemArray.GetValue(5).ToString();
int b = Convert.ToInt32(textBox1.Text);
if (b > 0)
{
//a = a - 1;
//int b = Convert.ToInt32(a);
//label15.Text = a.ToString();
SqlCommand update=new SqlCommand("UPDATE tblBookDetails SET Quantity=Quantity-1 WHERE Book_ID='"+ cmbBookID +"'");
Library.ExecuteInsert(update);
SqlCommand save = new SqlCommand("insert into tblBookIssue values(#ResID,#Member_ID,#Book_ID,#Issue_Date,#Act_Ret_Date)");
save.Parameters.AddWithValue("#ResID", cmbResID.Text);
save.Parameters.AddWithValue("#Member_ID", cmbMemID.Text);
save.Parameters.AddWithValue("#Book_ID", cmbBookID.Text);
save.Parameters.AddWithValue("#Issue_Date", txtIssueDate.Text);
save.Parameters.AddWithValue("#Act_Ret_Date", txtActDate.Text);
Library.Insert(save);
MessageBox.Show("Book Issued", "Book Issue", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
else
{
MessageBox.Show("this book is not available");
}
}
}
else
{
MessageBox.Show("FILL COLUMS");
}
}
Executing SQL based off of text boxes is very unsafe and Prone to SQL injection attacks. Also, to follow Object Oriented program and make much cleaner code it would be advisable to make a Book object, I completed some code below which shows an example including the book incrementer. It would be better to make focused stored procs which execute gets for books and updates for book checkouts. You will have to turn your basic select into a stored proc, and write another proc which looks at the quantity and if quantity < 1 return 0 else return 1. Let me know if you need more info, this code should help you get rolling
using System;
using System.Data;
using System.Data.SqlClient;
namespace MockLibrary
{
internal class Book
{
#region Constructors
public Book()
{
}
public Book(string resId, string memberId, string bookId, DateTime issueDate, DateTime actRetDate)
{
this.ResId = resId;
this.MemberId = memberId;
this.BookId = bookId;
this.IssueDate = issueDate;
this.ActRetDate = actRetDate;
}
#endregion
#region Properties
private string _ResID;
private string _MemberID;
private string _BookId;
private DateTime _IssueDate;
private DateTime _ActRetDate;
public string ResId
{
get { return _ResID; }
set { _ResID = value; }
}
public string MemberId
{
get { return _MemberID; }
set { _MemberID = value; }
}
public string BookId
{
get { return _BookId; }
set { _BookId = value; }
}
public DateTime IssueDate
{
get { return _IssueDate; }
set { _IssueDate = value; }
}
public DateTime ActRetDate
{
get { return _ActRetDate; }
set { _ActRetDate = value; }
}
#endregion
public Book GetBookByID(string resId, string memberId)
{
try
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_GetBookById", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Book newBook = new Book(rdr["ResId"].ToString(),rdr["MemberId"].ToString(),rdr["BookId"].ToString(),DateTime.Now,DateTime.Now);
return newBook;
}
}
}
}
catch
{
throw new Exception("something went wrong");
}
return null;
}
public bool CheckoutBook(string resId, string memberId)
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_CheckoutBook", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (rdr["checkoutsuccessful"].ToString() == "1")
{
return true;
}
}
}
}
return false;
}
}
}
when user returns a book:-
MySqlCommand cm1;
cm1 = new MySqlCommand("update addbook set bookquantity=bookquantity+1 where bookname='" + txt_bookname.Text + "'",con);
cm1.ExecuteNonQuery();
Related
The update is working fine, but stock value when is purchased I want to show messagebox, and stop the purchase when the value is zero in the stock update code.
I tried this code, but he only reduces value if the quantity is zero showing minus in the stock value when to stop when the value is equal to zero.
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=#q where id=#Xkey ", con);
//stock=Convert.ToInt32(dr)
cmd.Parameters.AddWithValue("#q", newqty);
cmd.Parameters.AddWithValue("#Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
//showExpenses();
//Reset();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The following first asserts there is sufficient stock, if not, alert caller else update the stock. This assumes no other users are working with the same item.
Note the use of delegates and that the database does not match your database but the same will work for your code with adjustments.
public class DataOperations
{
private const string ConnectionString
= "Data Source=.\\sqlexpress;Initial Catalog=NorthWind2020;Integrated Security=True";
public delegate void OnProcessing(string text);
public static event OnProcessing Processed;
public static void UpdateProductStockCount(int id, int amount)
{
using (var cn = new SqlConnection(ConnectionString))
{
using (var cmd = new SqlCommand() { Connection = cn })
{
cmd.CommandText = "SELECT UnitsInStock FROM dbo.Products WHERE ProductID = #Id";
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = id;
cn.Open();
var currentCount = (short)cmd.ExecuteScalar();
if (currentCount - amount <0)
{
Processed?.Invoke("Insufficient stock");
}
else
{
cmd.CommandText = "UPDATE dbo.Products SET UnitsInStock = #InStock WHERE ProductID = #Id";
cmd.Parameters.Add("#InStock", SqlDbType.Int).Value = currentCount - amount;
cmd.ExecuteNonQuery();
Processed?.Invoke("Processed");
}
}
}
}
}
Form code
public partial class StackoverflowForm : Form
{
public StackoverflowForm()
{
InitializeComponent();
DataOperations.Processed += DataOperationsOnProcessed;
}
private void DataOperationsOnProcessed(string text)
{
if (text == "Insufficient stock")
{
MessageBox.Show($"Sorry {text} ");
}
else
{
MessageBox.Show(text);
}
}
private void updateButton_Click(object sender, EventArgs e)
{
DataOperations.UpdateProductStockCount(21,1);
}
}
As #BagusTesa suggested, a simple if could do the trick:
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
if (newqty >= 0) // proceed
{
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=#q where id=#Xkey ", con);
cmd.Parameters.AddWithValue("#q", newqty);
cmd.Parameters.AddWithValue("#Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
}
else // cancel purchase
{
MessageBox.Show("New quantity is below 0, purchase cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have bit of code in my program that will not let and operator start another batch until they finish the one that they are on but still allows another operator to start the same batch. The sqldatareader is returning the correct data i.e. 17080387-002 but the program keeps going to the "Please finish batch" step. I'm trying to figure out if it possibly has anything to do with how the batch is being returned.
public void BatchLockOut()
{
string eventID = null;
string batchLock = null;
string enteredLot = TextBoxLot.Text;
string connectionString = "";
string commandText = "SELECT BadgeNo, Container_ID, Event_ID, Event_Time " +
"FROM dbo.Custom_EventLog " +
"WHERE Event_Time IN (SELECT MAX(Event_Time) FROM dbo.Custom_EventLog WHERE BadgeNo = #BADGENO)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#BADGENO", SqlDbType.NChar, 10).Value = TextBoxLogin.Text;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
eventID = Convert.ToInt32(reader["Event_ID"]).ToString();
batchLock = reader["Container_ID"] as string;
break;
}
}
connection.Close();
}
if (batchLock == null)
{
ButtonBeginStir.IsEnabled = true;
}
else if (batchLock != enteredLot)
{
if (eventID == "1")
{
MessageBox.Show("Please finish previous stir", "Finish Stir", MessageBoxButton.OK, MessageBoxImage.Information);
ClearForm();
}
else
{
ButtonBeginStir.IsEnabled = true;
}
}
else if (batchLock == enteredLot)
{
if (eventID == "1")
{
ButtonEndStir.IsEnabled = true;
}
else if (eventID == "2")
{
ButtonBeginStir.IsEnabled = true;
}
}
}
Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.
My Class
public string Countryadd(string country, string id)
{
string data = "0";
try
{
string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
SqlDataReader dr = conn.query(qry1);
if (dr.Read())
{
return data = "1";
}
else
{
string qry = "insert into Country values('" + id + "','" + country + "')";
conn.nonquery(qry);
return data = "3";
}
}
catch (Exception ex)
{
string x = ex.Message();
}
return data;
}
this string value how can we set in a label
My button_click function is
protected void Button1_Click(object sender, EventArgs e)
{
string str = mas.Countryadd(txtcountry.Text, txtid.Text);
if (str == "1")
{
Response.Write("<script>alert('Country Already Exist!!!!')</script>");
}
else if (str == "3")
{
Response.Write("<script>alert('Country Added Succesfully')</script>");
}
else
{
Label1.Text = str;
}
}
It's not the prettiest of code. Returning a string as a kind of status code is generally bad practice, because you don't know the range of possible values which can be returned, and what they mean. At the very least consider integer or even enum (which is named).
That being said, I would handle the check and the insert in separate methods, and catch the exception in the click event handler - let a single method have a single responsibility:
private void AddCountry(string country, string id)
{
using (SqlConnection conn = new SqlConnection())
{
string sql = string.Format("INSERT INTO Country (Id, Country) VALUES ('{0}', '{1}')", id, country);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}
}
private bool Exists(string country, string id)
{
using (SqlConnection conn = new SqlConnection())
{
string sql = "SELECT Count(*) FROM Country WHERE Country='" + country + "'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
int count = (int)cmd.ExecuteScalar();
return count >= 1;
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
if (Exists(txtcountry.Text, txtid.Text))
{
Response.Write("<script>alert('Country Already Exist!!!!')</script>");
}
else
{
AddCountry(txtcountry.Text, txtid.Text);
Response.Write("<script>alert('Country Added Succesfully')</script>");
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Catch(Exception e)
{
Label.Text= e.Message;
}
Well I am a newbie, and am trying to compile a .NET application but I am encountering many errors with the recompilation, this error in particular:
Only assignment, call, increment, decrement, and new objects
expressions can be used as a statement
On line 116 where this is located { SqlDataReader CS;1;0000; } what do you suggest?
namespace ProBall
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
public class DataManager
{
public static List<string> barcodes = new List<string>();
private string connStr;
private string queryStr;
public static bool queueMessage;
public static bool serverStatus = false;
public DataManager()
{
}
public DataManager(string connStr, string queryStr)
{
this.connStr = connStr;
this.queryStr = queryStr;
}
public static IPAddress FindIPAddress(bool localPreference)
{
return FindIPAddress(Dns.GetHostEntry(Dns.GetHostName()), localPreference);
}
public static IPAddress FindIPAddress(IPHostEntry host, bool localPreference)
{
if (host == null)
{
throw new ArgumentNullException("host");
}
if (host.AddressList.Length != 1)
{
foreach (IPAddress address in host.AddressList)
{
bool local = IsLocal(address);
if (local && localPreference)
{
return address;
}
if (!(local || localPreference))
{
return address;
}
}
}
return host.AddressList[0];
}
public string FormatDates(string date)
{
string tmpDate = date;
try
{
string[] nDate = null;
string day = string.Empty;
string month = string.Empty;
string year = string.Empty;
if (tmpDate.Contains("/"))
{
nDate = date.Split(new char[] { '/' });
day = nDate[0];
month = nDate[1];
year = nDate[2].Split(new char[] { ' ' })[0];
return (month + "/" + day + "/" + year);
}
if (tmpDate.Contains("-"))
{
tmpDate = date.Split(new char[] { ' ' })[0];
}
}
catch (Exception er)
{
this.LogError(er.Message, "GENERIC");
}
return tmpDate;
}
public string GetUserName(string tableName = "employees")
{
return this.ReadValue(string.Concat(new object[] { "select id from ", tableName, " where CurrentlyLoggedIn = 1 and LastLoginStation = '", ReturnHostName(), "' and LastLoginStationIP = '", FindIPAddress(true), "'" }), ConfigurationSettings.AppSettings["kcam"]);
}
public static bool IsLocal(IPAddress address)
{
if (address == null)
{
throw new ArgumentNullException("address");
}
byte[] addr = address.GetAddressBytes();
return (((addr[0] == 10) || ((addr[0] == 0xc0) && (addr[1] == 0xa8))) || (((addr[0] == 0xac) && (addr[1] >= 0x10)) && (addr[1] <= 0x1f)));
}
public void LogError(string message, string logType = "GENERIC")
{
StreamWriter ftmp = new StreamWriter(#"c:\coopnet\server\debug.txt", true);
ftmp.WriteLine(message);
ftmp.Close();
}
public bool LogOffUser(string tableName = "employees")
{
return this.SaveEntityData(string.Concat(new object[] { "update ", tableName, " set CurrentlyLoggedIn = 0 where LastLoginStation = '", ReturnHostName(), "' and LastLoginStationIP = '", FindIPAddress(true), "'" }), ConfigurationSettings.AppSettings["kcam"]);
}
public SqlDataReader ReadData()
{
SqlDataReader CS;1;0000;
using (SqlConnection conn = new SqlConnection(this.connStr))
{
using (SqlCommand cmd = new SqlCommand(this.queryStr, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
CS;1;0000 = reader;
}
}
}
; return CS; 1; 0000;
}
public bool ReadData(string query)
{
bool status = false;
this.queryStr = query;
using (SqlConnection conn = new SqlConnection(this.connStr))
{
using (SqlCommand cmd = new SqlCommand(this.queryStr, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
status = true;
}
}
return status;
}
}
}
public bool ReadData(string query, string connection)
{
bool status = false;
using (SqlConnection conn = new SqlConnection(connection))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
status = true;
}
}
return status;
}
}
}
public string ReadValue(string query, string connectionStr)
{
string value = string.Empty;
this.queryStr = query;
try
{
using (SqlConnection conn = new SqlConnection(connectionStr))
{
using (SqlCommand cmd = new SqlCommand(this.queryStr, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
return reader[0].ToString();
}
}
}
return value;
}
}
catch (Exception)
{
return value;
}
return value;
}
public static string ReturnHostName()
{
return Dns.GetHostName();
}
public bool SaveData()
{
try
{
bool status = false;
using (SqlConnection conn = new SqlConnection(this.connStr))
{
using (SqlCommand cmd = new SqlCommand(this.queryStr, conn))
{
conn.Open();
cmd.ExecuteReader();
status = true;
}
}
return status;
}
catch (Exception se)
{
this.LogError(se.Message, "GENERIC");
return false;
}
}
public bool SaveEntityData(string query, string connectionString)
{
try
{
Func<string, bool> performQuery = delegate (string querySql) {
this.connStr = connectionString;
this.queryStr = querySql;
return this.SaveData();
};
return performQuery(query);
}
catch (Exception e)
{
this.LogError("Error: " + e.Message, "GENERIC");
return false;
}
}
}
}
It looks like you are trying to use the value CS;1;0000; as a variable name, but this is invalid per the Language Spec ยง2.4.2 Identifiers. You cannot use semi-colons in variable names, as these have a special meaning as the end of a statement. If you re-name that variable to CS10000 or CS_1_0000 that should solve your problem.
Have a look at your public SqlDataReader ReadData() method. It has issues with semicolons.
SqlDataReader CS;1;0000; is not legal syntax. You can't name a variable CS;1;10000; Call it CS1000 and repeat through the method.
As you may have guessed the lines:
SqlDataReader CS; 1; 0000;
CS;1;0000 = reader;
; return CS; 1; 0000;
are not valid. You will need to fix this in order to compile your code.
Try replaceing the ; in the above code with underscores or something:
SqlDataReader CS_1_0000;
CS_1_0000 = reader;
return CS_1_0000;
In .NET a semicolon means the end of a line. This also means that the following code would be valid:
SqlDataReader CS; SqlDataReader cs2;
This single line would create two variables. CS and cs2
You should use variable name instead of "CS;1;0000;" (for example tempReader)