File manager - Edit - G:/PleskVhosts/indiaminerals.in/vgm.INFOFIXDEVELOPERS.COM/admin/Issue.aspx.cs
Back
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using WebApp.LIBS; using System.IO; namespace VGM.admin { public partial class Issue : BasePageClass { string cs = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; SqlConnection con; SqlCommand cmd; SqlDataAdapter da; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //// Modify your SQL query to join the "stock" table with "medicine_info" and add a condition to filter out medicines with stock <= 0 //da = new SqlDataAdapter("SELECT DISTINCT m.Medicine_name FROM stock s INNER JOIN medicine m ON s.Medicine_id = m.ID WHERE s.Purchase_stock > 0", cs); //DataTable dt = new DataTable(); //da.Fill(dt); //// Bind the dropdown with the filtered medicine names //medicineDropdown.DataSource = dt; //medicineDropdown.DataTextField = "Medicine_name"; //medicineDropdown.DataBind(); try { using (SqlConnection connection = new SqlConnection(cs)) { string query = "SELECT DISTINCT m.Medicine_name FROM stock s INNER JOIN medicine m ON s.Medicine_id = m.ID WHERE s.Purchase_stock > 0"; using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); // Add the default option "Select Medicine" ddlMedicine.Items.Add(new ListItem("Select Medicine", "")); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string medicineName = reader["Medicine_name"].ToString(); ListItem item = new ListItem(medicineName, medicineName); ddlMedicine.Items.Add(item); } } } } } catch (Exception ex) { // Log the exception details Console.WriteLine("Exception during Page_Load: " + ex.ToString()); // Display an error message to the user if needed Response.Write("<script>alert('An error occurred during page load: " + ex.Message + "')</script>"); } if (ViewState["MedicineData"] == null) { DataTable dt1 = new DataTable(); dt1.Columns.Add("Medicine_id", typeof(int)); dt1.Columns.Add("Medicine_name", typeof(string)); dt1.Columns.Add("Quantity", typeof(int)); ViewState["MedicineData"] = dt1; } // Bind the GridView with the data stored in ViewState DataTable dt2 = ViewState["MedicineData"] as DataTable; Gridview1.DataSource = dt2; Gridview1.DataBind(); int generatedID = GenerateUniqueID(); Label1.Text = generatedID.ToString(); } } protected void removeButton_Click(object sender, EventArgs e) { } protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteRow") { int rowIndex = Convert.ToInt32(e.CommandArgument); DataTable dt = ViewState["MedicineData"] as DataTable; if (dt != null) { if (dt.Rows.Count > rowIndex) { // Remove the row from the DataTable dt.Rows.RemoveAt(rowIndex); ViewState["MedicineData"] = dt; // Rebind the GridView to reflect the updated data Gridview1.DataSource = dt; Gridview1.DataBind(); } } } } protected void submitBtn2_Click(object sender, EventArgs e) { try { DataTable dt1 = ViewState["MedicineData"] as DataTable; // Your database connection string string connectionString = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Insert all the rows from the DataTable into the database foreach (DataRow row in dt1.Rows) { // Get the data you need from each row int medicineId = Convert.ToInt32(row["Medicine_id"]); int issuedQuantity = Convert.ToInt32(row["Quantity"]); // You should also get the other parameters required for the INSERT statement string insertQuery = "INSERT INTO issue(Issue_id,Issue_date, Issue_time, Issue_from, Issue_to, Medicine_id, Quantity) " + "VALUES (@Issue_id,@Issue_date, @Issue_time, @Issue_from, @Issue_to, @Medicine_id, @Quantity);"; using (SqlCommand insertCommand = new SqlCommand(insertQuery, connection)) { insertCommand.Parameters.Add(new SqlParameter("@Issue_id", Label1.Text));// Set the parameters // Assuming 'date' and 'time' are TextBox controls insertCommand.Parameters.Add(new SqlParameter("@Issue_date", date.Text.Trim())); insertCommand.Parameters.Add(new SqlParameter("@Issue_time", time.Text.Trim())); insertCommand.Parameters.Add(new SqlParameter("@Issue_from", issueFrom.Text)); insertCommand.Parameters.Add(new SqlParameter("@Issue_to", issuedTo.Text)); insertCommand.Parameters.Add(new SqlParameter("@Medicine_id", medicineId)); insertCommand.Parameters.Add(new SqlParameter("@Quantity", issuedQuantity)); // Execute the SQL command to insert data insertCommand.ExecuteNonQuery(); } // Update the stock table to reduce the quantity string updateStockQuery = "UPDATE stock SET Purchase_stock = Purchase_stock - @Purchase_stock WHERE Medicine_id = @Medicine_id"; using (SqlCommand updateStockCommand = new SqlCommand(updateStockQuery, connection)) { // Set the parameters updateStockCommand.Parameters.Add(new SqlParameter("@Medicine_id", medicineId)); updateStockCommand.Parameters.Add(new SqlParameter("@Purchase_stock", issuedQuantity)); updateStockCommand.ExecuteNonQuery(); } } } // Display a message after data insertion Response.Write("<script>if(confirm('Data inserted successfully.')){ window.location = 'Issue_list.aspx'; }</script>"); ViewState["MedicineData"] = null; Gridview1.DataSource = null; Gridview1.DataBind(); SaveToCSV(); } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } private void SaveToCSV() { try { string dateTime = DateTime.Now.ToString("yyyy-MM-dd"); string time = DateTime.Now.ToString("HH:mm:ss"); string tittle = "Medicine Issue"; // Get additional details (you may customize this part) string details = $"Medicine Issue From {issueFrom.Text} issue to {issuedTo.Text}"; // Combine date, time, and details in CSV format with comma delimiter string contentToSave = $"\"{dateTime}\",\"{time}\",\"{tittle}\",\"{details}\""; // Specify the path to the CSV file (including the file name) string filePath = Server.MapPath("~/data/LogData.csv"); // Check if the directory exists, if not, create it string directoryPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } // Check if the file exists, if not, create and add headers if (!File.Exists(filePath)) { File.WriteAllText(filePath, "Date,Time,Tittle,Details" + Environment.NewLine); } // Save the content to the file File.AppendAllText(filePath, contentToSave + Environment.NewLine); } catch (Exception ex) { Response.Write("<script>alert('An error occurred while saving to CSV: " + ex.Message + "')</script>"); } } private int GenerateUniqueID() { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["gav"].ConnectionString)) { connection.Open(); // Retrieve the highest existing Issue_id in the issue table string getMaxIssueIdQuery = "SELECT MAX(Issue_id) FROM issue"; using (SqlCommand getMaxIssueIdCommand = new SqlCommand(getMaxIssueIdQuery, connection)) { object maxIssueId = getMaxIssueIdCommand.ExecuteScalar(); if (maxIssueId != DBNull.Value) { return (int)maxIssueId + 1; } else { return 1; } } } } protected void addButton_Click(object sender, EventArgs e) { try { if (ViewState["MedicineData"] == null) { // Create a DataTable to store treatment data DataTable dt1 = new DataTable(); dt1.Columns.Add("Medicine_id", typeof(int)); // Change to "Medicine_id" dt1.Columns.Add("Medicine_name", typeof(string)); dt1.Columns.Add("Quantity", typeof(int)); // Add the "Quantity" column ViewState["MedicineData"] = dt1; } DataTable dt = (DataTable)ViewState["MedicineData"]; string selectedMedicineName = ddlMedicine.Value; // Get the selected medicine name // Your database connection string string connectionString = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Retrieve the Medicine_id and Purchase_stock based on the selected medicine name string selectMedicineInfoQuery = "SELECT m.ID, s.Purchase_stock " + "FROM medicine m " + "INNER JOIN stock s ON m.ID = s.Medicine_id " + "WHERE m.Medicine_name = @MedicineName"; using (SqlCommand selectMedicineInfoCommand = new SqlCommand(selectMedicineInfoQuery, connection)) { selectMedicineInfoCommand.Parameters.AddWithValue("@MedicineName", selectedMedicineName); SqlDataReader reader = selectMedicineInfoCommand.ExecuteReader(); if (reader.Read()) { int selectedMedicineId = (int)reader["ID"]; int purchaseStock = (int)reader["Purchase_stock"]; // Get the quantity entered by the user int enteredQuantity; if (int.TryParse(quantity.Text, out enteredQuantity)) { // Check if the entered quantity is valid if (enteredQuantity > 0) { // Calculate the total quantity in the cart for the selected medicine int totalQuantityInCart = 0; DataRow existingRow = dt.AsEnumerable() .FirstOrDefault(r => r.Field<int>("Medicine_id") == selectedMedicineId); if (existingRow != null) { totalQuantityInCart = existingRow.Field<int>("Quantity"); } if (totalQuantityInCart + enteredQuantity <= purchaseStock) { if (existingRow != null) { // Update the quantity if the row exists int currentQuantity = existingRow.Field<int>("Quantity"); int updatedQuantity = currentQuantity + enteredQuantity; existingRow.SetField("Quantity", updatedQuantity); } else { // Add a new row to the cart if the medicine is not present DataRow newRow = dt.NewRow(); newRow["Medicine_id"] = selectedMedicineId; newRow["Medicine_name"] = selectedMedicineName; newRow["Quantity"] = enteredQuantity; dt.Rows.Add(newRow); } // Bind the DataTable to the GridView Gridview1.DataSource = dt; Gridview1.DataBind(); quantity.Text = ""; ddlMedicine.Focus(); // Reset the error message lblError.Text = ""; lblError.Visible = false; } else { // Display an error message if adding more would exceed purchase_stock lblError.Text = "Available quantity for " + selectedMedicineName + " : " + purchaseStock; lblError.Visible = true; } } else { // Display an error message if the entered quantity is not valid lblError.Text = "Invalid quantity entered"; lblError.Visible = true; } } else { // Handle invalid quantity input lblError.Text = "Invalid quantity entered"; lblError.Visible = true; } } else { // Handle the case where the selected medicine name is not found lblError.Text = "Invalid Medicine selection"; lblError.Visible = true; } } } } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } } }
| ver. 1.4 |
Github
|
.
| PHP 7.3.33 | Generation time: 0.08 |
proxy
|
phpinfo
|
Settings