Crud operation in asp.net mvc - asp.net-mvc

I have an assignment in ASP.NET MVC and I try to write a crud operation without Entity Framework, but the code is not working correctly.
This is my code:
List<bookModel> books = new List<bookModel>();
SqlConnection con = new SqlConnection("Data Source=DESKTOP-VKO8311;Initial Catalog=BookStore;Integrated Security=True");
string query = "SELECT * FROM books";
SqlCommand command = new SqlCommand(query, con);
try
{
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
books.Add(new bookModel
{
Title = reader["Title of book"].ToString(),
Author = reader["Author"].ToString(),
Price = reader["Price"].ToString()
});
con.Close();
}
}
catch (Exception ex)
{
con.Close();
}
return View(books);
[HttpGet]
public ActionResult NewBook()
{
ViewBag.Title = "Add New Book";
return View();
}
[HttpPost]
public ActionResult NewBook(bookModel model)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-VKO8311;Initial Catalog=BookStore;Integrated Security=True");
string query = "insert into books values(#Ti, #au, #pr)";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.Add("#Ti", System.Data.SqlDbType.VarChar);
command.Parameters["#Ti"].Value = model.Title;
command.Parameters.Add("#au", System.Data.SqlDbType.VarChar);
command.Parameters["#au"].Value = model.author;
command.Parameters.Add("#pr", System.Data.SqlDbType.VarChar);
command.Parameters["#pr"].Value = model.Price;
try
{
con.Open();
command.ExecuteNonQuery();
MessageBox.Show("insert was successful");
return RedirectToAction("books");
}
catch (Exception ex)
{
con.Close();
}
return View();
}
The books.cshtml does not show the result from the database and also the newbook.cshtml does not redirect the create result in the database also.
Any help please?

Your code needs refactoring, but the biggest issue is where you are closing your connection. You don't do it while you're iterating the data reader. Also, take the connection close out of your exception handler. You're better off enclosing it in a using block.
while (reader.Read())
{
books.Add(new bookModel
{
Title = reader["Title of book"].ToString(),
Author = reader["Author"].ToString(),
Price = reader["Price"].ToString()
});
}

Related

Hi I'm trying to import the captured excel file into table on a button click

enter image description here
Hi I want to export the sheets of excel into a table. I already manage to catch the excel into database. When I click the import button I want to redirect it into a new view and see there the excel values. Any idea how I can do that? I'm using MVC
here is my controller:
public ActionResult Index()
{
Products products = GetProducts();
ViewBag.Message = "";
return View(products);
}
}
[HttpPost]
public ActionResult Index(Products obj)
{
string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss");
string finalPath = "\\UploadedFile\\" + strDateTime + obj.UploadFile.FileName;
obj.UploadFile.SaveAs(Server.MapPath("~") + finalPath);
obj.FilePath = strDateTime + obj.UploadFile.FileName;
ViewBag.Message = SaveToDB(obj);
Products products = GetProducts();
return View(products);
}
public string SaveToDB(Products obj)
{
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "sp_AddFiles";
cmd.Parameters.AddWithValue("#FileN", obj.FileN);
cmd.Parameters.AddWithValue("#FilePath", obj.FilePath);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Dispose();
con.Close();
return "Saved Successfully";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
// GET: Products
public Products GetProducts()
{
Products products = new Products();
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("Select * from tblFiles", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
adapter.Dispose();
cmd.Dispose();
con.Close();
products.lstProducts = new List<Products>();
foreach (DataRow dr in dt.Rows)
{
products.lstProducts.Add(new Products
{
FileN = dr["FileN"].ToString(),
FilePath = dr["FilePath"].ToString()
});
}
}
catch (Exception ex)
{
adapter.Dispose();
cmd.Dispose();
con.Close();
}
if (products == null || products.lstProducts == null || products.lstProducts.Count == 0)
{
products = new Products();
products.lstProducts = new List<Products>();
}
return products;
}
Hi I want to export the sheets of excel into a table. I already manage to catch the excel into database. When I click the import button I want to redirect it into a new view and see there the excel values. Any idea how I can do that? I'm using MVC

How to Populate DropDownList from the Database in MVC

I am new to ASP NET MVC
I need Populate a drop down list from values obtained from a database table using MySql database and view model, after checking if the current user is application enabled, using ASP NET MVC.
This is the tutorial
My code below return
Error: returns void, a return keyword must not be followed by an object expression
On this line
return items;
Any help really appreciated.
Controller
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
List<SelectListItem> items = new List<SelectListItem>();
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "' ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
connection.Close();
}
}
return items;
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
Update
I have tried with this code.
I have error
Error CS0103 The name 'cCountry' does not exist in the current context
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
TempData["Dates"] = PopulateDates();
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
private static List<SelectListItem> PopulateDates()
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "'; ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
You are not passing cCountry value to populateDates.That's why you are getting this error. You can do something like below to get drop down populated. However it is not good idea to write Business Logic directly in controller. You should move it to model or Business layer.
private static List<SelectListItem> PopulateDates(string country)
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM dotable_countries WHERE cCountry = #country";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("#country",country);
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
and while calling this method in Action pass country value to it like below
TempData["Dates"] = PopulateDates(cCountry);

How to check if a checkbox was checked in mvc controller

I'm pulling a list of items from table database and checkbox to check and approve each item; however even when I check the item it throws this error message : Please select at least one requested item. What I'm trying to achieve is that the user checks any amount of items in the list and then the status requisition number is updated to 0.
public ActionResult RequisitionList(List<Requisition> postingObj)
{
IssueDAO dbObj = new DAO(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
List<string> reqNumbers = new List<string>();
bool check=false;
foreach (var item in postingObj)
{
if (item.postTrnx)
{
reqNumbers.Add(item.reqNumber);
}
}
if (check == true)
{
dbObj.SetRequisitionStatus0(reqNumbers);
ViewBag.Message = "Approval Successful!";
}
else {
ViewBag.Message = "Please select at least one requested item";
return View(dbObj.GetAllRequest());
}
return View(dbObj.GetAllRequest());
}
public void SetRequisitionStatus0(List<string> reqNumbers)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = "requisition_sp_setstatus0";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#reqNumber", SqlDbType.VarChar);
command.Parameters.Add("#approve_date", SqlDbType.DateTime).Value = DateTime.Now;
using (command.Connection = connection)
{
try
{
connection.Open();
foreach (var item in reqNumbers)
{
command.Parameters["#reqNumber"].Value = item;
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
return;
}
public List<Requisition> GetAllRequest()
{
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("getallrequests", connection))
{
command.CommandType = CommandType.StoredProcedure;
List<Requisition> request = new List<Requisition>();
SqlDataReader rdrObj;
connection.Open();
rdrObj = command.ExecuteReader();
while (rdrObj.Read())
{
Requisition requisition = new Requisition();
requisition.reqNumber = rdrObj.GetString(0);
requisition.reqDate = rdrObj.GetDateTime(1);
requisition.items = getRequestItemByRquisition(rdrObj.GetString(0));
request.Add(requisition);
}
rdrObj.Close();
return request;
}
}
}

I am getting an error at get property with error 'BusinessLayer.EmployeeBusinessLayer.Employees.get': not all code paths return a value

I am getting an error at get property that not all code paths return a value.
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get // Here i am getting an error that not all code paths return a value
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.Emp_Name = Convert.ToString(rdr["Emp_Name"]);
employee.Designation = Convert.ToString(rdr["Designation"]);
employee.City = Convert.ToString(rdr["City"]);
employee.State = Convert.ToString(rdr["State"]);
employee.Country = Convert.ToString(rdr["Country"]);
employees.Add(employee);
}
}
}
}
}
}
The error message can be taken literally:
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get // Here i am getting an error that not all code paths return a value
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.Emp_Name = Convert.ToString(rdr["Emp_Name"]);
employee.Designation = Convert.ToString(rdr["Designation"]);
employee.City = Convert.ToString(rdr["City"]);
employee.State = Convert.ToString(rdr["State"]);
employee.Country = Convert.ToString(rdr["Country"]);
employees.Add(employee);
}
}
return employees;
}
}
}
}
Need to return your employees. Also you should Close() and dispose your reader.
using(IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
...
employees.Add(employee);
}
rdr.Close();
}
return employees;

User Input Check Before Insert to Database

I have a form in my MVC 5 Webb App, a very simple form for "contact us":
-Name
-Email
-Subject
-Message (body)
I have to check the strings that the user input.
How can I check it in .NET ?
Update:
As Darin suggested, a Parameterizing Queries will take care of that, but I have a problem with implementation it with my architecture design of my web application:
I have a Ado Helper Class:
public class AdoHelper
{
static string connectionString = ConfigurationManager.ConnectionStrings["SQL_DB"].ConnectionString;
public static DataTable ExecuteDataTable(string query)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand command = new SqlCommand(query, con);
SqlDataAdapter tableAdapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
tableAdapter.Fill(dt);
return dt;
}
}
public static void ExecuteNonQuery(string query)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand command = new SqlCommand(query, con);
command.ExecuteNonQuery();
}
}
public static object ExecuteScalar(string query)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand command = new SqlCommand(query, con);
return command.ExecuteScalar();
}
}
}
And I have Data Queries Class: ( I display here only the relevant function to this question)
public class DataQueries
{
public static void InsertContactForm(ContactForm form)
{
try
{
string query = "INSERT INTO ContactForm (Name, Email, Subject, Message, Reply) VALUES ( '" + form.Name + "','" + form.Email + "','" + form.Subject + "','" + form.Message + "','" + form.Reply + "')";
AdoHelper.ExecuteNonQuery(query);
}
catch (Exception ex)
{
throw ex;
}
}
}
When I want to insert data to my DB I call to a Data Queries function that communicate with the Ado Helper Class.
So the query pass to Ado Helper function as string well formed and ready to go, this creates a problem because I cant use parameters in the Ado Helper class (where I have SQL command instance).
Are there any workaround to this problem ?
Thanks.
Looks like your AdoHelper class is currently vulnerable to SQL injection. In order to avoid that you need to use parametrized queries. So I would start by refactoring this AdoHelper class so that it suits better those needs:
public class AdoHelper
{
private static string connectionString = ConfigurationManager.ConnectionStrings["SQL_DB"].ConnectionString;
public static int ExecuteNonQuery(string query, IDictionary<string, object> parameters)
{
using (var con = new SqlConnection(connectionString))
using (var command = con.CreateCommand())
{
con.Open();
command.CommandText = query;
foreach (var p in parameters)
{
command.Parameters.AddWithValue(p.Key, p.Value);
}
return command.ExecuteNonQuery();
}
}
}
and then you could call this method in order to perform the INSERT statement:
AdoHelper.ExecuteNonQuery(
"INSERT INTO ContactForm (Name, Email, Subject, Message, Reply) VALUES (#Name, #Email, #Subject, #Message, #Reply)",
new Dictionary<string, object>
{
{ "#Name", "form.Name" },
{ "#Email", "form.Email" },
{ "#Subject", "form.Subject" },
{ "#Message", "form.Message" },
{ "#Reply", "form.Reply" }
}
);
What you need is parametrized queries. In the cmd object in ADO.NET, for example, there is a straight forward to do that:
using (var cmd = new SqlCommand())
{
// Add the input parameter and set its properties.
using (var parameter = new SqlParameter())
{
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
cmd.Parameters.Add(parameter);
// Now you can execute query
}
}
http://msdn.microsoft.com/en-us/library/yy6y35y8%28v=vs.110%29.aspx

Resources