CRUD operation in MVC with out Entity framework - sql-server

Hi I am beginner in MVC , I am trying to achieve CRUD operation in MVC using SQL with out Entity Framework or LINQ-SQL class. I done well with insert and getting the details of the selected table but when coming to Edit, details and delete I am confused how to perform so can some one help me out.
This is my code
Create a new Employee
public ActionResult Index(Test test)
{
try
{
if (ModelState.IsValid)
{
test.insert(test);
test.Name = "";
test.LastName = "";
}
}
catch (Exception)
{
}
return View(test);
}
Display all results
public ActionResult display()
{
Test tst = new Test();
return View(tst.getList());
}
This is my code in class file
public class Test
{
public int EmpID { get; set; }
[Required]
[DisplayName("Name")]
public string Name { get; set; }
[Required]
[DisplayName("LastName")]
public string LastName { get; set; }
string strConnection = ConfigurationManager.ConnectionStrings["SomeDataBase"].ConnectionString.ToString();
public void insert(Test test)
{
using (SqlConnection con = new SqlConnection(strConnection))
{
SqlCommand cmd = new SqlCommand("insert into Employee values('" + test.Name + "','" + test.LastName + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
public List<Test> getList()
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
public List<Test> edit(int id)
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
}
Can some one help me how to do the remaining operations like Details, Edit update and Delete.

for Details you can use
public Test details(int id)
{
Test _products = new Test();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
_products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_products.Name = dr["FirstName"].ToString();
_products.LastName = dr["LastName"].ToString();
}
catch(exception ex)
{
/* Do Some Stuff */
}
return _products;
}
And from your Controller
public ActionResult Details(int id)
{
Test tst = new Test();
return tst.Details(id);
}
for Edit you can use
public Bool Edit(test tst)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("UPDATE TABLE Employee SET FirstName='"+tst.Name+"',Lastname='"+tst.LastName+"' where EmpID='" + tst.EmpId + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
return true;
}
catch(exception ex)
{
/* Do Some Stuff */
}
}
And from your Controller
public ActionResult Edit(test tsts)
{
Test tst = new Test();
return tst.Edit(tsts);
}
and proceed similarly for the rest of the cases

Related

Convert SqlDataReader to object for .NET Framework 4

I am working on a class Library with .NET Framework 4.0. I have managed to pull a row using ADO.NET, but I'm unable to read individual values. I want the end result in class object. I have tried reading individual value dbReader.GetValue(dbReader.GetOrdinal("BranchCode")) but getting empty result.
Branch class:
public class Branch
{
public Branch() { }
public int BranchId { get; set; }
public string BranchCode { get; set; }
public string BranchName { get; set; }
}
DataReader class:
public void Initialize()
{
try
{
string connectionString = "xyz";
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from dbo.Branch", dbConnection);
dbConnection.Open();
SqlDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var x1 = dbReader.GetValue(dbReader.GetOrdinal("BranchId"));
var x2 = dbReader.GetValue(dbReader.GetOrdinal("BranchCode"));
var x3 = dbReader.GetValue(dbReader.GetOrdinal("BranchName"));
}
var dd = "Dd";
}
catch(Exception ex)
{
throw ex;
}
}
You have a number of issues with your code.
You need to actually create the Branch objects and do something with them. For example, return List.
To read the values, the easiest way is to do (typeNameHere) dbReader["ColumnName"]
You should SELECT exactly the right columns not SELECT *
Don't catch then re-throw exceptions with throw ex; as it wipes the stakc trace.
public List<Branch> Initialize()
{
string connectionString = "xyz";
const string query = #"
Select
b.BranchId,
b.BranchCode,
b.BranchName
from dbo.Branch b;
";
using (SqlConnection dbConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
using (SqlDataReader dbReader = cmd.ExecuteReader())
{
var list = new List<Branch>();
while (dbReader.Read())
{
var b = new Branch();
b.BranchId = (int)dbReader["BranchId"];
b.BranchCode = (string)dbReader["BranchCode"];
b.BranchName = (string)dbReader["BranchName"];
list.Add(b);
}
return list;
}
}
}

How to insert data into database using formcollection

I am trying insert data into a database table. Unfortunately, the data does not get inserted into the database.
Controller:
public class UserController : Controller
{
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
string query = "INSERT INTO Member (#ID, #Name, #City, #Address) " +
"VALUES (ID, Name, City, Address)";
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
//model get,set method does not access
sqlcmd.ExecuteNonQuery();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
Repository:
public class UserMasterRepository : IUserMasterRepository
{
private List<UserMaster> users = new List<UserMaster>();
private int _nextId = 1;
public UserMaster Add(UserMaster item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.ID = _nextId++;
users.Add(item);
return item;
}
}
IUserMasterRepository:
public interface IUserMasterRepository
{
IEnumerable<UserMaster> GetAll();
UserMaster Get(int id);
UserMaster Add(UserMaster item);
bool Update(UserMaster item);
bool Delete(int id);
}
How can I resolve this issue?
As suggested by #marc_s you need to change your inline query for insertion and before inserting value you need to fetch records from FormCollection.
I assume that you have view model something like this.
public class VM
{
public int Id { get; set; }
public string Name { get; set; }
public string City{ get; set; }
public string Adderess{ get; set; }
}
Retrieve input values from FormCollection Object in action method:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
//model get,set method does not access
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Value = collection["ID"];
sqlcmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = collection["Name"];
sqlcmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = collection["City"];
sqlcmd.Parameters.Add("#Address", SqlDbType.VarChar, 100).Value =collection["Address"];
///continue
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I believe for SQL Server, your INSERT statement is wrong - try this:
string query = "INSERT INTO Member (ID, Name, City, Address) " +
"VALUES (#ID, #Name, #City, #Address)";
The list of columns after the INSERT INTO must list the column names as defined in the database table - and those are without a leading #.
On the other hand, the parameter placeholders in the VALUES (...) section are just that - parameters - and they must have the leading # for their name.
Those parameters must then be defined and a value must be provided for each of them before the .ExecuteNonQuery() call:
//model get,set method does not access
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Value = 42;
sqlcmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = "Miller";
sqlcmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = "London";
sqlcmd.Parameters.Add("#Address", SqlDbType.VarChar, 100).Value = "123 Earl's Court";
sqlcmd.ExecuteNonQuery();

Retrieving the data from the database based on the parameter

ValuesController.cs (sending the HTTP request such as GET, POST, DELETE and etc):
public class ValuesController : ApiController
{
Database_Access_Data.db dblayer = new Database_Access_Data.db();
[HttpPost]
[Route("api/Values/SendLocation")]
public IHttpActionResult SendLocation([FromBody]Location cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.SendLocation(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
[HttpGet]
[Route("api/Values/GetLocationHistory")]
public DataSet GetLocationHistory()
{
DataSet ds = dblayer.GetLocationHistory();
return ds;
}
[HttpPost]
[Route("api/Values/SendDistance")]
public IHttpActionResult SendDistance([FromBody]Location cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.SendDistance(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
[HttpGet]
[Route("api/Values/GetUser")]
public DataSet GetUser()
{
DataSet ds = dblayer.GetUser();
return ds;
}
[HttpPost]
[Route("api/Values/FlagingDevice")]
public IHttpActionResult FlagingDevice([FromBody]Timer cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.FlagingDevice(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
[HttpPost]
[Route("api/Values/SendBox")]
public IHttpActionResult SendBox([FromBody]Box cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.SendBox(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
}
db.cs (used to call the stored procedure as well as sending the parameter):
public class db
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["localhost"].ConnectionString);
Location cs = new Location();
public void SendLocation(Location cs)
{
SqlCommand com = new SqlCommand("SendGPS",con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#DeviceImei", cs.DeviceImei);
com.Parameters.AddWithValue("#Latitude",cs.Latitude);
com.Parameters.AddWithValue("#Longitude",cs.Longitude);
com.Parameters.AddWithValue("#Distance", cs.Distance);
com.Parameters.AddWithValue("#LocationSend",cs.LocationSend);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
public DataSet GetLocationHistory()
{
SqlCommand com = new SqlCommand("GetLocationHistory", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public DataSet GetUser()
{
SqlCommand com = new SqlCommand("GetUser", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public void SendDistance(Location cs)
{
SqlCommand com = new SqlCommand("SendDistance", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#DeviceImei", cs.DeviceImei);
com.Parameters.AddWithValue("#Distance", cs.Distance);
com.Parameters.AddWithValue("#LocationSend", cs.LocationSend);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
public void FlagingDevice(Timer cs)
{
SqlCommand com = new SqlCommand("FlagingDevice", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Interval", cs.Interval);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
public void SendBox(Box cs)
{
SqlCommand com = new SqlCommand("SendBox", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Id", cs.Id);
com.Parameters.AddWithValue("#PollingStationID", cs.PollingStationID);
com.Parameters.AddWithValue("#DeviceImei", cs.DeviceImei);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
}
The stored procedure that used to return the data from the table:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[FlagingDevice]
#Interval INT
AS
DECLARE #Time DATETIME
IF #Interval = 5
BEGIN
SET #Time = (SELECT MAX(LocationSend) FROM dbo.Location)
SELECT D.imei, L.*, L1.*
FROM Device D
OUTER APPLY
(SELECT *
FROM dbo.Location L1
WHERE L1.DeviceImei = D.Imei
GROUP BY DeviceImei, Latitude, Longitude, Distance, LocationSend
HAVING DATEDIFF(MINUTE, LocationSend, #Time) <= #Interval) AS L
OUTER APPLY
(SELECT TOP 1 L4.ID AS 'Station', L3.Name
FROM [dbo].[ElectionDivision] L3, dbo.PollingStation L4
WHERE L.Latitude IS NOT NULL
AND L.Longitude IS NOT NULL
AND L.Distance IS NOT NULL
AND L.DeviceImei = D.ImeI) AS L1
END
ELSE IF #Interval = 0
BEGIN
SELECT D.imei, L.*, L1.*
FROM Device D
OUTER APPLY
(SELECT TOP 1 *
FROM dbo.Location L1
WHERE L1.DeviceImei = D.Imei
ORDER BY (LocationSend) DESC) AS L
OUTER APPLY
(SELECT TOP 1 L4.ID AS 'Station', L3.Name
FROM [dbo].[ElectionDivision] L3, dbo.PollingStation L4
WHERE L.Latitude IS NOT NULL
AND L.Longitude IS NOT NULL
AND L.Distance IS NOT NULL
AND L.DeviceImei = D.ImeI) AS L1
END
Update: I am using sqldatareader and put the data into a list but not sure how to return the FlaggingDevice Method as shown in the valuescontroller class. Should i be creating the list inside a class or something else. Any Suggestions ?
public List<FlagingDevice> FlagingDevice(FlagingDevice cs)
{
SqlCommand com = new SqlCommand("FlagingDevice", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Interval", cs.Interval);
con.Open();
com.Connection = con;
using (SqlDataReader sqlDataReader = com.ExecuteReader())
{
int movieGenreIDIndex = sqlDataReader.GetOrdinal("DeviceImei");
int movieIDIndex = sqlDataReader.GetOrdinal("Latitude");
int genreIDIndex = sqlDataReader.GetOrdinal("Longitude");
int genreIDIndex1 = sqlDataReader.GetOrdinal("Distance");
int genreIDIndex2 = sqlDataReader.GetOrdinal("LocationSend");
int genreIDIndex3 = sqlDataReader.GetOrdinal("Station");
int genreIDIndex4 = sqlDataReader.GetOrdinal("Name");
while (sqlDataReader.Read())
{
student.Add(new FlagingDevice()
{
DeviceImei = sqlDataReader.IsDBNull(movieGenreIDIndex) ? null : sqlDataReader.GetString(movieGenreIDIndex),
Latitude = sqlDataReader.IsDBNull(movieIDIndex) ? null : sqlDataReader.GetString(movieIDIndex),
Longitude = sqlDataReader.IsDBNull(genreIDIndex) ? null : sqlDataReader.GetString(genreIDIndex),
Distance = sqlDataReader.IsDBNull(genreIDIndex1) ? null : sqlDataReader.GetString(genreIDIndex1),
LocationSend = sqlDataReader.IsDBNull(genreIDIndex2) ? null : Convert.ToString(sqlDataReader["LocationSend"]),
Name = sqlDataReader.IsDBNull(genreIDIndex4) ? null : sqlDataReader.GetString(genreIDIndex4)
});
}
sqlDataReader.Close();
con.Close();
return student;
}
}

Login for users of different positions

I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.

Reader always returns NULL

I'm new to C#. I want to write an application that can easily connect to a SQL Server database. I have a separate DBConnection class, and I want to call this class from any form.
The problem is that my "reader" always returns Null.
class DBconnection
{
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataReader rdr;
private DataTable dt;
private SqlConnection MyConnection
{
get
{
if (this.conn == null)
{
this.conn = new SqlConnection(DrivingSchool.Properties.Settings.Default.cdsConnectionString);
}
return conn;
}
}
private SqlCommand MyCommand
{
get
{
if (cmd == null)
{
cmd = new SqlCommand();
MyCommand.Connection = conn;
}
return cmd;
}
}
public DataTable RunQuery(string query)
{
dt = new DataTable();
MyCommand.CommandText = query;
MyCommand.Connection = conn;
MyConnection.Open();
rdr = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
if(rdr.HasRows)
{
dt.Load(rdr);
}
MyConnection.Close();
return dt;
}
}
It seems to me that in factoring out the creation of the connection and SqlCommand that you have over-complicated your code.
To fill a DataTable, you should use an SqlDataAdapter (or the appropriate DataAdapter for whatever database you use), something like this:
static public DataTable GetDataTableFromQuery(string queryString)
{
DataTable dt = null;
string connStr = DrivingSchool.Properties.Settings.Default.cdsConnectionString;
using (SqlDataAdapter da = new SqlDataAdapter(queryString, connStr))
{
da.Fill(dt);
}
return dt;
}

Resources