Convert query to parametrized asp.net query - asp.net

How would I make this parametrized ?!
string query = "";
query += " SELECT DistID FROM Distributor";
query += " WHERE Username = '" + username_id.Text + "'";
query += " AND Password = '" + password.Text + "'";
GeneralFunctions.GetData( query );
Can it be done here or would it have to be done inside the GetData method?
Here are the two methods:
public static DataTable GetData ( string query )
{
SqlDataAdapter dataAdapter;
DataTable table;
try
{
dataAdapter = new SqlDataAdapter( query, GetConnectionString() );
table = new DataTable();
dataAdapter.Fill( table );
return table;
}
catch ( Exception ex )
{
}
finally
{
dataAdapter = null;
table = null;
}
return table;
}
public static string GetConnectionString ()
{
string connectionString = ConfigurationManager.ConnectionStrings[ "CAPortalConnectionString" ].ConnectionString;
return connectionString;
}

I'd recommend you designing specific methods to query your database, like this:
public static int? GetDistID(string username, string password)
{
using (var conn = new SqlConnection(GetConnectionString()))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText =
#"SELECT
DistID
FROM
Distributor
WHERE
Username = #username
AND
Password = #password";
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
// no results found
return null;
}
return reader.GetInt32(reader.GetOrdinal("DistID"));
}
}
}
and then:
var distId = GeneralFunctions.GetDistID(username_id.Text, password.Text);
No need of DataTables/Sets/Adapters. Work with strongly typed objects.

Use the SqlCommand object, and you can create a parameterized query like this:
public object GetDistID(string username, string password)
{
using (var conn = new SqlConnection("..."))
{
using (var cmd = new SqlCommand("SELECT DistID FROM Distributor WHERE Username=#Username AND Password=#Password", conn))
{
cmd.Connection.Open();
cmd.Parameters.AddWithValue("#Username", username);
cmd.Parameters.AddWithValue("#Password", password);
return cmd.ExecuteScalar();
}
}
}
If it's useful to you, here's a class you can use. It's tailored towards stored procedures, but it should be easy enough to add a method that accepts a query:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
namespace NESCTC.Data
{
public class DataAccess : IDisposable
{
#region declarations
private SqlCommand _cmd;
private string _SqlConnString;
#endregion
#region constructors
public DataAccess(string ConnectionString)
{
_cmd = new SqlCommand();
_cmd.CommandTimeout = 240;
_SqlConnString = ConnectionString;
}
#endregion
#region IDisposable implementation
~DataAccess()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_cmd.Connection.Dispose();
_cmd.Dispose();
}
}
#endregion
#region data retrieval methods
public DataTable ExecReturnDataTable()
{
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
try
{
PrepareCommandForExecution(conn);
using (SqlDataAdapter adap = new SqlDataAdapter(_cmd))
{
DataTable dt = new DataTable();
adap.Fill(dt);
return dt;
}
}
catch
{
_cmd.Connection.Close();
throw;
}
finally
{
_cmd.Connection.Close();
}
}
}
public object ExecScalar()
{
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
try
{
PrepareCommandForExecution(conn);
return _cmd.ExecuteScalar();
}
catch (Exception ex)
{
_cmd.Connection.Close();
throw ex;
}
finally
{
_cmd.Connection.Close();
}
}
}
#endregion
#region data insert and update methods
public void ExecNonQuery()
{
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
try
{
PrepareCommandForExecution(conn);
_cmd.ExecuteNonQuery();
}
catch
{
_cmd.Connection.Close();
throw;
}
finally
{
_cmd.Connection.Close();
}
}
}
#endregion
#region helper methods
public void AddParm(string ParameterName, SqlDbType ParameterType, object Value)
{ _cmd.Parameters.Add(ParameterName, ParameterType).Value = Value; }
private SqlCommand PrepareCommandForExecution(SqlConnection conn)
{
try
{
_cmd.Connection = conn;
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.CommandTimeout = this.CommandTimeout;
_cmd.Connection.Open();
return _cmd;
}
catch
{
_cmd.Connection.Close();
throw;
}
}
#endregion
#region properties
public int CommandTimeout
{
get { return _cmd.CommandTimeout; }
set { _cmd.CommandTimeout = value; }
}
public string ProcedureName
{
get { return _cmd.CommandText; }
set { _cmd.CommandText = value; }
}
public string ConnectionString
{
get { return _SqlConnString; }
set { _SqlConnString = value; }
}
#endregion
}
}
You can use the class like this:
public object GetDistID(string username, string password)
{
using (var data = new DataAccess("ConnectionString"))
{
data.ProcedureName = "GetDistID";
data.AddParm("#Username", SqlDbType.VarChar, username);
data.AddParm("#Password", SqlDbType.VarChar, password);
return data.ExecScalar();
}
}

Related

how to refactoring IEnumerable<T> ExecuteDataReader<T> to async method

public static IEnumerable<T> ExecuteDataReader<T>(string sql, Func<TdDataReader, T> action)
{
using (var connection = new TdConnection(TDConnstring))
{
connection.Open();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
yield return action.Invoke(dr);
}
}
}
}
*how to use async task> rewirte *
public static async Task<IEnumerable<T>> ExecuteDataReaderAsync<T>(string sql, Func<TdDataReader, T> action)
{
using (var connection = new TdConnection(TDConnstring))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var dr = await cmd.ExecuteReaderAsync())
{
while (await dr.ReadAsync())
{
yield return action.Invoke(dr);
}
}
}
}
}
* error
Severity Code Description Project File Line Suppression State
Error CS1624 The body of 'TeraDataHelper.ExecuteDataReaderAsync(string, Func)' cannot be an iterator block because 'Task>' is not an iterator interface type \TeraDataHelper.cs 141 Active
*
got it
public static async Task<IEnumerable<T>> ExecuteDataReaderAsync<T>(string sql, Func<TdDataReader, T> action)
{
using (var connection = new TdConnection(TDConnstring))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var dr = await cmd.ExecuteReaderAsync())
{
return dr.Select(r => action(r)).ToList();
}
}
}
}
public static class Extensions
{
public static IEnumerable<T> Select<T>(
this TdDataReader reader, Func<TdDataReader, T> action)
{
while (reader.Read())
{
yield return action(reader);
}
}
}

I can't get my static class working with a Generic List

I have a static class that needs to pass a generic List of strings to a function using an integer as a index to the List in the class. The problem is the static class doesn't have a List collect and I don't have a proper index to access the class in the function it is passed to. The class, the calling code, and the receiving function are below.
My Class:
public class QueryContainer
{
public static QueryContainer Instance = new QueryContainer();
private int _id;
private string _query = "";
private int _searchID;
public QueryContainer() { }
public string Query
{
get
{
if (Instance != null)
return Instance._query;
else
return "";
}
set { _query = value; _id =+ 1; }
}
public int ID { get { return _id; } }
public int SearchID
{
set { _searchID = value; }
get { return _searchID; }
}
}
The calling code:
public int GetAccountSortByAccountCode(int account)
{
int Id = 0;
QueryContainer.Instance.Query = "SELECT ac_sort_order FROM lkup_account_codes where ac_code = " + account.ToString();
return Convert.ToInt32(ExecuteScaler(Id));
}
The function that the static class is passed to:
public int GetAccountSortByAccountCode(int account)
{
int Id = 0;
QueryContainer.Instance.Query = "SELECT ac_sort_order FROM lkup_account_codes where ac_code = " + account.ToString();
return Convert.ToInt32(ExecuteScaler(Id));
}
The Function
protected Object ExecuteScaler(int ID)
{
object returnValue = null;
if (!_iserror)
{
if (_trace)
{ DoTrace("TAMIS.Data.Loader.ExecuteScalar", QueryContainer.Instance.Query); }
if (_connection == null || _connection.State == ConnectionState.Closed)
{
OpenConnection();
}
DbCommand command = _provider.CreateCommand();
command.Connection = _connection;
{
command.CommandText = QueryContainer.Instance.Query;
command.CommandType = CommandType.Text;
if (_useTransaction) { command.Transaction = _transaction; }
try
{
returnValue = command.ExecuteScalar();
}
catch (Exception ex)
{
if (ex is EntryPointNotFoundException)
throw ex;
//if (_useTransaction == true)
//_transaction.Rollback();
RollBack();
LogBLL bll = new LogBLL();
bll.WriteErrorLog(ex);
_iserror = true;
}
finally
{
if ((!KeepAlive && _connection.State == ConnectionState.Open) || _iserror == true)
{
CloseConnection();
}
}
}
}
else
{
returnValue = -1;
}
return returnValue;
}
You are using QueryContainer as a Singleton.
In ASP.Net, you receives multiple requests from different users. It is not a good way to construct dynamic query.
Basically, what you are doing is all requests will use same QueryContainer instance. I don't think it is what you want.
The bottom line is do not use static in your scenario.

CRUD Operations in MVC 5

I am developing an application in MVC 5 and perform CRUD operations on it.
I have successfully added Northwind database as an Entity Data Model and taking Customer in the Model. Now with the help of Scaffolding I generated the CustomersController.
When I create a new record in a Customer Table. There is no problem.
But when I click on that new record, Edit, Details and Delete are not working. After clicking any of these:
The following page occurs:
My Controller Code:
namespace MvcNorthwindSample.Controllers
{
public class CustomersController : Controller
{
private NORTHWNDEntities db = new NORTHWNDEntities();
// GET: Customers
public ActionResult Index()
{
return View(db.Customers.ToList());
}
// GET: Customers/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// GET: Customers/Create
public ActionResult Create()
{
return View();
}
// POST: Customers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
if (ModelState.IsValid)
{
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My View Part:
My Create Code Result view while debugging:
EDIT: After you posted your controller:
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
Are you sure that you have a customer with an id of 1994? If not, your logic would return HttpNotFound().
In the screenshot you posted, I can read HTTP 404 error message and the requested URL was /Customer/Edit/1994.
So for that I assume you must be have the following controller/action:
public class CustomerController
{
public ActionResult Edit(int id)
{
return View();
}
}
Now the most common mistake most people make (including me) is properly passing id in the URL. You have id specified as an optional parameter in your route pattern:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
So if you don't want to use id you could pass something else as a key name in the the query component, e.g., /Customer/Edit?year=1994.
The error is a 404 Error.
It is looking in the Controller Customers for an Edit action.
Also pointed out in the comments the Id 1994 has a encoded space character following it. If the id is suppose to be strings, you can change the parameter to type string instead of int
public class CustomersController
{
public ActionResult Edit(int id)
{
return View();
}
}
I solved it. I changed the table at last. There is a problem on the table named Customers of the Northwind database. I download database backup file. The Customer ID column is adding a space as a default with the inserted value.
First create your models and Dbcontext.
public class TaskManagerContext : DbContext
{
public TaskManagerContext()
: base("TaskManagerDB")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Task> Tasks { get; set; }
}
Then allow migrations and update the database from the PM. Create a folder Repositories with a BaseRepo that the rest must inherit.
public class BaseRepository<T> where T:BaseModel, new()
{
protected TaskManagerContext context;
protected DbSet<T> dbSet;
public BaseRepository()
{
this.context = new TaskManagerContext();
this.dbSet = this.context.Set<T>();
}
public void Insert(T item)
{
this.dbSet.Add(item);
this.context.SaveChanges();
}
public void Update(T item)
{
this.context.Entry(item).State = EntityState.Modified;
this.context.SaveChanges();
}
public void Delete(int id)
{
this.dbSet.Remove(this.dbSet.Find(id));
this.context.SaveChanges();
}
public IEnumerable<T> GetAll()
{
return this.dbSet;
}
}
like this:
public class UsersRepository : BaseRepository<User>
{
public UsersRepository()
: base()
{
}
}
Then you create the controllers in which you use the methods from the repos.
public class UsersController : Controller
{
//
// GET: /Users/
public ActionResult List()
{
List<User> users = new List<User>();
users = new UsersRepository().GetAll().ToList();
return View(users);
}
public ActionResult Edit(int id)
{
User user = new UsersRepository().GetAll().FirstOrDefault(u => u.ID == id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User user)
{
UsersRepository repo = new UsersRepository();
repo.Update(user);
return RedirectToAction("List");
}
public ActionResult Delete(int id)
{
UsersRepository repo = new UsersRepository();
repo.Delete(id);
return RedirectToAction("List");
}
public ActionResult Create()
{
User u = new User();
return View(u);
}
[HttpPost]
public ActionResult Create(User user)
{
UsersRepository repo = new UsersRepository();
repo.Insert(user);
return RedirectToAction("List");
}
}
The actions for the TaskContr are simillar exept the List in which you connect the 2 models by ID:
public ActionResult List(int? id)
{
TasksRepository repo = new TasksRepository();
List<Task> tasks = new List<Task>();
tasks = repo.GetAll().Where(t => t.UserID == id).ToList();
return View(tasks);
}
Don't forget to generate views(on the Get methods) and change the List view for the Users:
#Html.ActionLink("Details", "List", "Tasks", new { id=item.ID }, null) |
That way when clicking Details you can see the tasks for that user.
public ActionResult Index()
{
using (DevExam db = new DevExam())
{
var intern = from m in db.Interns
select m;
return View(intern.ToList());
}
/* using (DevExam db = new DevExam())
{
var interns = db.Interns
.Include(s => s.InternID)
.Select(s => new Intern
{
InternID = s.InternID,
lname = s.lname,
fname = s.fname
});
return View(interns);
}
*/
}
// GET: CRUD/Details/5
public ActionResult Details(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// GET: CRUD/Create
public ActionResult Create()
{
return View();
}
// POST: CRUD/Create
[HttpPost]
public ActionResult Create(Intern intern)
{
try
{
// TODO: Add insert logic here
using (DevExam db = new DevExam())
{
db.Interns.Add(intern);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: CRUD/Edit/5
public ActionResult Edit(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// POST: CRUD/Edit/5
[HttpPost]
public ActionResult Edit(int id,Intern intern)
{
try
{
// TODO: Add update logic here
using (DevExam db = new DevExam())
{
db.Entry(intern).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: CRUD/Delete/5
public ActionResult Delete(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// POST: CRUD/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
using (DevExam db = new DevExam())
{
Intern intern = db.Interns.Where(x => x.InternID == id).FirstOrDefault();
db.Interns.Remove(intern);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
create table tblemployee(
EmpId int NOT NULL identity(1,1),
EmpName varchar(100),
PhoneNumber varchar(10),
Country int,
State int,
maritalstetus varchar(50),
isvoting varchar(50),
dob datetime,
doj datetime
primary key (EmpId)
)
create table tblCountry(
Id int NOT NULL identity(1,1),
Name varchar(100),
primary key (Id)
)
insert into tblCountry(Name) values ('India')
insert into tblCountry(Name) values ('US')
insert into tblCountry(Name) values ('UK')
create table tblstate(
Id int NOT NULL identity(1,1),
Name varchar(100),
countryId int,
primary key (Id)
)
insert into tblstate(Name ,countryId) values ('Delhi',1)
insert into tblstate(Name , countryId) values ('Bihar' ,1)
insert into tblstate(Name , countryId) values ('Up',1)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace webTest.Models
{
public class Employee
{
public int id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public int Country { get; set; }
[Required]
public int State { get; set; }
[Required]
public bool MarritalStatus { get; set; }
public bool IsVoting { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DOJ { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using webTest.Models;
namespace webTest.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public static string constr = "Data Source=DIVYANSHU;Initial Catalog=EmployeeData;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
public ActionResult ViewList()
{
List<Employee> employees = new List<Employee>();
try
{
conn.Open();
string sqlquery = "select * from tblEmployee";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
employees.Add(emp);
}
conn.Close();
}
catch (Exception ex)
{
}
return View(employees);
}
public ActionResult Create()
{
SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCountry", constr);
DataTable _dt = new DataTable();
_da.Fill(_dt);
ViewBag.Country = ToSelectList(_dt, "Id", "Name");
_da.Dispose();
SqlDataAdapter _da1 = new SqlDataAdapter("Select * From tblState", constr);
DataTable _dt1 = new DataTable();
_da1.Fill(_dt1);
ViewBag.State = ToSelectList(_dt1, "Id", "Name");
_da1.Dispose();
Employee emp = new Employee();
return View(emp);
}
public SelectList ToSelectList(DataTable table, string valueField, string textField)
{
List<SelectListItem> list = new List<SelectListItem>();
foreach (DataRow row in table.Rows)
{
list.Add(new SelectListItem()
{
Text = row[textField].ToString(),
Value = row[valueField].ToString()
});
}
return new SelectList(list, "Value", "Text");
}
[HttpPost]
public ActionResult Create(Employee empmodel)
{
List<Employee> employees = new List<Employee>();
try
{
conn.Open();
string sqlquery = "insert into tblEmployee(EmpName,PhoneNumber,Country,State,maritalstetus,isvoting,dob,doj) values('" + empmodel.Name + "','" + empmodel.PhoneNumber + "'," + empmodel.Country + "," + empmodel.State + ",'" + empmodel.MarritalStatus + "','" + empmodel.IsVoting + "','" + empmodel.DOB + "','" + empmodel.DOJ + "')";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
employees = listEmployee();
}
catch (Exception ex)
{
}
return View("ViewList", employees);
}
public ActionResult Edit(int id)
{
Employee emp = new Employee();
try
{
SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCountry", constr);
DataTable _dt = new DataTable();
_da.Fill(_dt);
ViewBag.Country = ToSelectList(_dt, "Id", "Name");
_da.Dispose();
SqlDataAdapter _da1 = new SqlDataAdapter("Select * From tblState", constr);
DataTable _dt1 = new DataTable();
_da1.Fill(_dt1);
ViewBag.State = ToSelectList(_dt1, "Id", "Name");
_da1.Dispose();
conn.Open();
string sqlquery = "select * from tblemployee where empid=" + id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
}
conn.Close();
}
catch (Exception ex)
{
}
return View(emp);
}
[HttpPost]
public ActionResult Edit(Employee empmodel)
{
try
{
conn.Open();
string sqlquery = "update tblEmployee set EmpName='" + empmodel.Name + "',PhoneNumber='" + empmodel.PhoneNumber + "',Country=" + empmodel.Country + ",State=" + empmodel.State + ",maritalstetus='" + empmodel.MarritalStatus + "',isvoting='" + empmodel.IsVoting + "',dob='" + empmodel.DOB + "',doj='" + empmodel.DOJ + "' where empid=" + empmodel.id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
List<Employee> list = listEmployee();
return View("ViewList", list);
}
public ActionResult Delete(int id)
{
try
{
conn.Open();
string sqlquery = "Delete from tblEmployee where empid=" + id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
List<Employee> list = listEmployee();
return View("ViewList", list);
}
public List<Employee> listEmployee()
{
List<Employee> employees = new List<Employee>();
conn.Open();
string sqlquery = "select * from tblEmployee";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
employees.Add(emp);
}
conn.Close();
return employees;
}
}
}
//in Edit view and in create view replace edit for to
#Html.DropDownListFor(model => model.Country, ViewBag.Country as SelectList, new { #class = "form-control" })
#Html.DropDownListFor(model => model.State, ViewBag.State as SelectList, new { #class = "form-control" })

i am getting an error while inserting data in database by creating Class File in Asp.Net for Database Manipulations

error :: The parameterized query '(#CustomerName
varchar(50),#CustomerGender varchar(50),#Customer' expects the
parameter '#CustomerName', which was not supplied. Statement(s) could
not be prepared.
my code of .cs file is:
public class CustomerCls
{
private int custid;
public int CustomerId
{
set { custid = value; }
get { return custid; }
}
private string custname;
public string CustomerName
{
set { custname = value; }
get { return custname; }
}
private string gender;
public string CustomerGender
{
set { gender = value; }
get { return gender; }
}
private string city;
public string CustomerCity
{
set { city = value; }
get { return city; }
}
private string strcon;
public CustomerCls()
{
strcon = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;
}
public void InsertCustomer()
{
string sql = "Insert Into Customer(Cust_Name,Cust_Gender,Cust_City) " + " VALUES(#CustomerName,#CustomerGender,#CustomerCity)";
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar,50).Value = CustomerName;
cmd.Parameters.Add("#CustomerGender", SqlDbType.VarChar,50).Value = CustomerGender;
cmd.Parameters.Add("#CustomerCity", SqlDbType.VarChar,50).Value = CustomerCity;
cmd.Prepare();
cmd.ExecuteNonQuery();
con.Close();
}
}
Make sure the CustomerCls object calling the InsertCustomer() method has the necessary properties set in code before the call to the method is made:
CustomerCls oCustomerCls = new CustomerCls();
oCustomerCls.CustomerName = "John Doe";
// etc...
oCustomerCls.InsertCustomer();
Try changing these lines to
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar,50).Value = CustomerName;
cmd.Parameters.Add("#CustomerGender", SqlDbType.VarChar,50).Value = CustomerGender;
cmd.Parameters.Add("#CustomerCity", SqlDbType.VarChar,50).Value = CustomerCity;
to
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar,50).Value = custname;
cmd.Parameters.Add("#CustomerGender", SqlDbType.VarChar,50).Value = gender;
cmd.Parameters.Add("#CustomerCity", SqlDbType.VarChar,50).Value = city;

Traverse a list and retrieve a specified value from List<> in asp.net/c#

I have a list which is defined as
List<SoftwareTitles> softwareTitlesList = new List<SoftwareTitles>();
and the SoftwareTitles is a class which is defines as follows:
public class SoftwareTitles
{
string softwareTitle;
string invoiceNumber;
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
this.softwareTitle = softwareTitle;
this.invoiceNumber = invoiceNumber;
}
string InvoiceNumber
{
get
{
return this.invoiceNumber;
}
}
string SoftwareTitle
{
get
{
return this.softwareTitle;
}
}
}
And now I'm adding the values from the sql server database to the list defines as follows:
public List<SoftwareTitles> SoftwareListRetrieve()
{
ConnectionToSql con1 = new ConnectionToSql();
string connectionString = con1.ConnectionStringMethod();
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd2 = new SqlCommand("SelectionOfSoftwareTitles", sqlConnection);
cmd2.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
String softwareTitle = (String)dr2[0];
String invoiceNumber = (String)dr2[1];
SoftwareTitles s1 = new SoftwareTitles(softwareTitle, invoiceNumber);
softwareTitlesList.Add(s1);
}
}
sqlConnection.Close();
dr2.Close();
return softwareTitlesList;
}
I want to find out the software title for every occurence of invoice number by looping through List<>. And I don't know how ? I have tried to loop through the List<> by the following code. I wanted to use something like contains i.e., softwareTitlesList[i].contains but seems like there is no such property or method
for(int i=0; i<softwareTitlesList.Count;i++)
{
softwareTitlesList[i]. [BUT IT IS NOT SUGGESTING ME ANYTHING]
}
I'm stuck with this from morning. I don't how to solve this dilemma.
Please help me
Thanks in anticipation
search for an invoice number
string invoiceNumber = "111111111";
using linq
IList<string> titles = softwareTitlesList
.Where(st => st.InvoiceNumber == invoiceNumber)
.Select(st => st.SoftwareTitle);
or
IList<string> titles = softwareTitlesList
.Where(st => st.InvoiceNumber.Contains(invoiceNumber))
.Select(st => st.SoftwareTitle);
w/o using linq, it's still pretty basic
IList<string> titles = new List<string>();
foreach(var softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(invoiceNumber))
titles.Add(softwareTitle.SoftwareTitle);
}
you could also rewrite your class like this:
public class SoftwareTitles
{
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
SoftwareTitle = softwareTitle;
InvoiceNumber = invoiceNumber;
}
public string InvoiceNumber { get; private set; }
public string SoftwareTitle { get; private set; }
}

Resources