File manager - Edit - G:/PleskVhosts/indiaminerals.in/vgm.INFOFIXDEVELOPERS.COM/admin/Observation.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; using DevExpress.Utils.IoC; using DevExpress.Utils.OAuth.Provider; namespace VGM.admin { public partial class Observation : BasePageClass { string cs = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; SqlConnection con; SqlCommand cmd; SqlDataAdapter da; protected void Page_Load(object sender, EventArgs e) { string tagNo = Request.QueryString["tag_no"]; string animalCategory = Request.QueryString["animal_category"]; if (!string.IsNullOrEmpty(tagNo) && !string.IsNullOrEmpty(animalCategory)) { FillRegistrationDropdown(tagNo, animalCategory); LoadRegistrationData(); } else { LoadRegistrationData(); } try { if(!IsPostBack) { using (SqlConnection connection = new SqlConnection(cs)) { using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT ID, Medicine_name FROM medicine", connection)) { connection.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { ddlMedicine.DataSource = reader; ddlMedicine.DataTextField = "Medicine_name"; ddlMedicine.DataValueField = "ID"; ddlMedicine.DataBind(); ddlMedicine.SelectedIndex = 0; } connection.Close(); } } } } catch (Exception ex) { Console.WriteLine("Exception during Page_Load: " + ex.ToString()); Response.Write("<script>alert('An error occurred during page load: " + ex.Message + "')</script>"); } if (ViewState["TreatmentData"] == null) { DataTable dt1 = new DataTable(); dt1.Columns.Add("Date", typeof(DateTime)); dt1.Columns.Add("Medicine_name", typeof(string)); dt1.Columns.Add("Dose", typeof(string)); dt1.Columns.Add("OD_TID_BID", typeof(string)); ViewState["TreatmentData"] = dt1; } DataTable dt2 = ViewState["TreatmentData"] as DataTable; Gridview1.DataSource = dt2; Gridview1.DataBind(); int generatedID = GenerateUniqueID(); id.Text = generatedID.ToString(); } private int GenerateUniqueID() { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["gav"].ConnectionString)) { connection.Open(); string getMaxIssueIdQuery = "SELECT MAX([S_no]) FROM observation"; using (SqlCommand getMaxIssueIdCommand = new SqlCommand(getMaxIssueIdQuery, connection)) { object maxIssueId = getMaxIssueIdCommand.ExecuteScalar(); if (maxIssueId != DBNull.Value) { return (int)maxIssueId + 1; } else { return 1; } } } } private void FillRegistrationDropdown(string tagNo, string animalCategory) { try { registration.Items.Clear(); registration.Items.Add($"{tagNo} - {animalCategory}"); registration.SelectedIndex = 0; } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } private void LoadRegistrationData() { try { da = new SqlDataAdapter("select * from registration", cs); DataSet dt = new DataSet(); da.Fill(dt); for (int i = 0; i < dt.Tables[0].Rows.Count; i++) { registration.Items.Add(dt.Tables[0].Rows[i][1] + " - " + dt.Tables[0].Rows[i][2]); } } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } protected void Button2_Click(object sender, EventArgs e) { } protected void submitBtn2_Click1(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(registration.Text)) { ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Please enter a Tag no.');", true); return; } DataTable dt1 = ViewState["TreatmentData"] as DataTable ?? new DataTable(); string connectionString = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); foreach (DataRow row in dt1.Rows) { string medicineName = row["Medicine_name"].ToString(); int medicineId = 0; string selectedItem = registration.SelectedItem.Text; string[] parts = selectedItem.Split('-'); if (parts.Length >= 2) { string tagNoPart = parts[0].Trim(); int tagno; if (int.TryParse(tagNoPart, out tagno)) { string animalCategory = parts[1].Trim(); string registered_id_query = "SELECT id FROM registration WHERE tag_no = @TagNo AND animal_category = @AnimalCategory"; using (SqlCommand registeredIdCommand = new SqlCommand(registered_id_query, connection)) { registeredIdCommand.Parameters.AddWithValue("@TagNo", tagno); registeredIdCommand.Parameters.AddWithValue("@AnimalCategory", animalCategory); object registeredIdResult = registeredIdCommand.ExecuteScalar(); if (registeredIdResult != null) { int registeredId = Convert.ToInt32(registeredIdResult); string getMedicineIdQuery = "SELECT ID FROM medicine WHERE medicine_name = @MedicineName"; using (SqlCommand getMedicineIdCommand = new SqlCommand(getMedicineIdQuery, connection)) { getMedicineIdCommand.Parameters.AddWithValue("@MedicineName", medicineName); object result = getMedicineIdCommand.ExecuteScalar(); if (result != null) { medicineId = Convert.ToInt32(result); string insertQuery = "INSERT INTO observation ([S_no], Tag_no, Date, Medicine_id, Dose, OD_TID_BID, registered_id) VALUES (@ID, @TagNo, @Date, @MedicineId, @Dose, @OD_TID_BID, @RegisteredId)"; using (SqlCommand command = new SqlCommand(insertQuery, connection)) { command.Parameters.AddWithValue("@ID", id.Text); command.Parameters.AddWithValue("@TagNo", tagno); command.Parameters.AddWithValue("@Date", row["Date"]); command.Parameters.AddWithValue("@MedicineId", medicineId); // Use the retrieved ID command.Parameters.AddWithValue("@Dose", row["Dose"]); command.Parameters.AddWithValue("@OD_TID_BID", row["OD_TID_BID"]); command.Parameters.AddWithValue("@RegisteredId", registeredId); command.ExecuteNonQuery(); } } } } } } } } } Response.Write("<script>if(confirm('Data inserted successfully.')){ window.location = 'Observation_list.aspx'; }</script>"); 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 = "Observation Master"; // Get additional details (you may customize this part) string details = $"Tag no. {registration.Text} Observation detail"; // 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>"); } } protected void submitBtn_Click(object sender, EventArgs e) { try { string connectionString = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; string selectedItem = registration.SelectedItem.Text; string[] parts = selectedItem.Split('-'); if (parts.Length >= 2) { int tagNo; if (int.TryParse(parts[0]?.Trim(), out tagNo)) // Use of TryParse for safe conversion to integer { string animalCategory = parts[1].Trim(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string registered_id_query = "SELECT id FROM registration WHERE tag_no = @TagNo AND animal_category = @AnimalCategory"; using (SqlCommand registeredIdCommand = new SqlCommand(registered_id_query, connection)) { registeredIdCommand.Parameters.AddWithValue("@TagNo", tagNo); registeredIdCommand.Parameters.AddWithValue("@AnimalCategory", animalCategory); object registeredIdResult = registeredIdCommand.ExecuteScalar(); if (registeredIdResult != null) { int registeredId = Convert.ToInt32(registeredIdResult); if (tagNo <= 0) { // The "Tag no" textbox is empty, show a validation error label2.Text = ""; label3.Text = ""; label4.Text = ""; label6.Text = ""; label8.Text = ""; label10.Text = ""; label12.Text = ""; label14.Text = ""; label16.Text = ""; label18.Text = ""; label20.Text = ""; label22.Text = ""; Response.Write("<script>alert('Please insert a Tag no.')</script>"); } else { // The "Tag no" textbox is not empty, perform the database lookup string statusAdmitted = "Admitted"; string statusOwn = "Own"; da = new SqlDataAdapter("select * from registration where id = '" + registeredId + "' and (status = '" + statusAdmitted + "' OR status = '" + statusOwn + "')", cs); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { label2.Text = dt.Rows[0]["owner_name"].ToString(); label3.Text = dt.Rows[0]["owner_mobile_no"].ToString(); label4.Text = dt.Rows[0]["owner_address"].ToString(); label6.Text = dt.Rows[0]["animal_category"].ToString(); label8.Text = dt.Rows[0]["dob"].ToString(); label10.Text = dt.Rows[0]["age"].ToString(); label12.Text = dt.Rows[0]["color"].ToString(); label14.Text = dt.Rows[0]["gender"].ToString(); label16.Text = dt.Rows[0]["weight"].ToString(); label18.Text = dt.Rows[0]["species"].ToString(); label20.Text = dt.Rows[0]["disease_diagnosis"].ToString(); label22.Text = dt.Rows[0]["prognosis"].ToString(); } else { Response.Write("<script>alert('Please insert Correct Tag no.')</script>"); } } } } } } } } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteRow") { int rowIndex = Convert.ToInt32(e.CommandArgument); DataTable dt = ViewState["TreatmentData"] as DataTable; if (dt != null) { if (dt.Rows.Count > rowIndex) { // Remove the row from the DataTable dt.Rows.RemoveAt(rowIndex); ViewState["TreatmentData"] = dt; // Rebind the GridView to reflect the updated data Gridview1.DataSource = dt; Gridview1.DataBind(); } } } } protected void Button1_Click1(object sender, EventArgs e) { try { DataTable dt = new DataTable(); if (ViewState["TreatmentData"] == null) { dt.Columns.Add("Date", typeof(DateTime)); dt.Columns.Add("Medicine_name", typeof(string)); dt.Columns.Add("Dose", typeof(string)); dt.Columns.Add("OD_TID_BID", typeof(string)); ViewState["TreatmentData"] = dt; } else { dt = (DataTable)ViewState["TreatmentData"]; } string st; if (od.Checked) { st = "OD"; } else if (bid.Checked) { st = "BID"; } else { st = "TID"; } // Check if Treatment and Dose are selected/entered if (!string.IsNullOrEmpty(ddlMedicine.SelectedValue) && !string.IsNullOrEmpty(dose.Text)) { DataRow newRow = dt.NewRow(); newRow["Date"] = Convert.ToDateTime(date.Text).ToString("dd-MMM-yyyy"); newRow["Medicine_name"] = ddlMedicine.SelectedItem; newRow["Dose"] = dose.Text; newRow["OD_TID_BID"] = st; dt.Rows.Add(newRow); // Bind the DataTable to the GridView Gridview1.DataSource = dt; Gridview1.DataBind(); // Clear the form inputs date.Text = ""; od.Checked = false; tid.Checked = false; bid.Checked = false; dose.Text = ""; date.Focus(); } else { // Display an error message if Treatment or Dose is not selected/entered //labelValidation.Text = "Please select Treatment and enter Dose."; } } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } protected void view_Click(object sender, EventArgs e) { try { string connectionString = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; string date1 = textBox1.Text; string selectedItem = registration.SelectedItem.Text; string[] parts = selectedItem.Split('-'); if (parts.Length >= 2) { int tagno = int.Parse(parts[0].Trim()); string animalCategory = parts[1].Trim(); string registered_id = "select id from registration where tag_no = '" + tagno + "' and animal_category = '" + animalCategory + "'"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string query = "SELECT o.Date, m.Medicine_name, o.Dose, o.OD_TID_BID " + "FROM observation o " + "INNER JOIN medicine m ON o.Medicine_id = m.ID " + "WHERE o.Date = @Date AND o.Tag_no = @TagNo AND o.registered_id = @registered_id"; SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@Date", date1); command.Parameters.AddWithValue("@TagNo", tagno); command.Parameters.AddWithValue("@registered_id", registered_id); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); Gridview2.DataSource = dataTable; Gridview2.DataBind(); } } } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } protected void Repeatdose_Click(object sender, EventArgs e) { try { DataTable dtTreatment = ViewState["TreatmentData"] as DataTable; if (dtTreatment == null) { dtTreatment = new DataTable(); dtTreatment.Columns.Add("Date", typeof(DateTime)); dtTreatment.Columns.Add("Medicine_name", typeof(string)); dtTreatment.Columns.Add("Dose", typeof(string)); dtTreatment.Columns.Add("OD_TID_BID", typeof(string)); } // Get the DataTable from Gridview2 DataTable dtGridview2 = new DataTable(); // Create columns in dtGridview2 based on Gridview2 foreach (DataControlField column in Gridview2.Columns) { dtGridview2.Columns.Add(column.HeaderText); } // Iterate through the rows of Gridview2 and add them to dtGridview2 foreach (GridViewRow row in Gridview2.Rows) { DataRow newRow = dtGridview2.NewRow(); var doseDate = ((Literal)row.FindControl("doseDate")).Text; var doseMedicine_name = ((Literal)row.FindControl("doseMedicine_name")).Text; var doseDose = ((Literal)row.FindControl("doseDose")).Text; var doseOD_TID_BID = ((Literal)row.FindControl("doseOD_TID_BID")).Text; newRow["Date"] = doseDate; newRow["Treatment"] = doseMedicine_name; newRow["Dose"] = doseDose; newRow["OD_TID_BID"] = doseOD_TID_BID; dtGridview2.Rows.Add(newRow); } // Merge the data from dtGridview2 into dtTreatment foreach (DataRow row in dtGridview2.Rows) { DataRow newRow = dtTreatment.NewRow(); newRow.ItemArray = row.ItemArray; // Copy the row data // Modify the "Date" column to have the current date newRow["Date"] = DateTime.Today; dtTreatment.Rows.Add(newRow); } // Store the updated DataTable in ViewState ViewState["TreatmentData"] = dtTreatment; // Bind the DataTable to Gridview1 Gridview1.DataSource = dtTreatment; Gridview1.DataBind(); } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } protected void ddlMedicine_SelectedIndexChanged(object sender, EventArgs e) { string cs = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; try { using (SqlConnection connection = new SqlConnection(cs)) { string selectMedicineInfoQuery = @" SELECT m.ID, m.Medicine_name, COALESCE(SUM(p.Quantity), 0) AS Purchase_stock, COALESCE(SUM(i.Quantity), 0) AS Issue_stock FROM medicine m LEFT JOIN purchase p ON m.ID = p.Medicine_id LEFT JOIN issue i ON m.ID = i.Medicine_id WHERE m.ID = @MedicineName GROUP BY m.ID, m.Medicine_name"; using (SqlCommand selectMedicineInfoCommand = new SqlCommand(selectMedicineInfoQuery, connection)) { selectMedicineInfoCommand.Parameters.AddWithValue("@MedicineName", ddlMedicine.SelectedValue); connection.Open(); using (SqlDataReader reader = selectMedicineInfoCommand.ExecuteReader()) { if (reader.Read()) { int purchaseStock = reader["Purchase_stock"] != DBNull.Value ? Convert.ToInt32(reader["Purchase_stock"]) : 0; int issueStock = reader["Issue_stock"] != DBNull.Value ? Convert.ToInt32(reader["Issue_stock"]) : 0; lblError.Text = $"Purchase Qty: {purchaseStock}, Issue Qty: {issueStock}"; lblError.Visible = true; } else { lblError.Text = "No records found."; lblError.Visible = true; } } } } } catch (Exception ex) { lblError.Text = "Error: " + ex.Message; lblError.Visible = true; } } } }
| ver. 1.4 |
Github
|
.
| PHP 7.3.33 | Generation time: 0.04 |
proxy
|
phpinfo
|
Settings