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

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;

Related

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);

Crud operation in 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()
});
}

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;
}
}
}

exception occurence in mvc

****I am getting an exception of type 'System.IndexOutOfRangeException' in System.Data.dll but was not handled in user code****
public List<ItemModel> med()
{
List<ItemModel> itemList = new List<ItemModel>();
connection();
SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PstrOperationFlag", "S-drugname");
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
ItemModel item = new ItemModel();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
ItemModel io = new ItemModel();
while (sdr.Read())
{
io = new ItemModel();
io.medication = sdr["medications"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
}
Try this
public List<ItemModel> med()
{
List<ItemModel> itemList = new List<ItemModel>();
ItemModel io;
connection();
SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PstrOperationFlag", "S-drugname");
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
io = new ItemModel();
io.medication = sdr["medications"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}

How to fill dropdownlist in MVC-4 using dapper

I filled Drop Down List in MVC which is working fine but now I want to do it using Dapper but got stuck.
DropDownList in MVC without Dapper
Controller
[HttpPost]
public ActionResult Create(User ur)
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
ModelState.Clear();
FillCountry();
}
public void FillCountry()
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "select * from tbl_country ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
while (rdr.Read())
{
li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
}
ViewData["country"] = li;
}
View
#{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new {onchange = "this.form.submit();" })
#{ Html.EndForm(); }
This is what I am trying to do now
DropDownList in MVC with Dapper
Model
public class Region
{
private int _CountryId;
private string _CountryName;
public int CountryId
{
get { return _CountryId; }
set { _CountryId = value; }
}
public string CountryName
{
get { return _CountryName; }
set { _CountryName = value; }
}
Controller
[HttpPost]
public ActionResult AddMobiles(TBMobileDetails MD, HttpPostedFileBase file)
{
FileUpload(file);
MobileMain MM = new MobileMain();
MM.AddMobiles(MD);
FillCountry();
return RedirectToAction("AllMobileList");
}
Stuck in this part how to fill it using dapper? How to populate my list?
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
}
View
#{ Html.BeginForm("AddMobiles", "AddMobile", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }
You are passing in ViewData["country"] object of type IEnumerable<Region> while in View you are casting it to IEnumerable<SelectListItem> which won't work obviously in action change FillCountry() to make SelectList:
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
var list = new SelectList(result,"CountryId","CountryName");
}
and in View now cast it to SelectList:
#Html.DropDownList("country", ViewData["country"] as SelectList, new {onchange = "this.form.submit();" })
This will get you going.

Resources