i was creating a simple rest service in asp.net mvc.my problem is my value is not passing to respository class. i think i miss something can anyone help..?
here is my controller
static LoginRespository repository = new LoginRespository();
public string AddEmployees(Login Emp)
{
//calling EmpRepository Class Method and storing Repsonse
var response = repository.AddEmployees(Emp);
return response;
}
and my respositoryclass like this
public string AddEmployees(Login Emp)
{
SqlCommand com;
SqlConnection con = new SqlConnection(#"Data Source=DOTNET;Initial Catalog=edin;Integrated Security=True;Pooling=False");
try
{
com = new SqlCommand("select * from data where name='" + Emp.username + "'", con);
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
return "success";
}
else
{
return "error";
}
con.Close();
}
catch (Exception aa)
{
return aa.ToString();
}
}
and my modelis
public string username { get; set; }
public string password { get; set; }
Pay attention to:
In method AddEmployees instead of passing collection of Employees you pass single employee and suggest change to AddEmployee
Instead of Insert you add Employee with Select
If you receive null Employee in AddEmployee that means that you send null Employee in your controller.
If you calling the AddEmployees on button click event. Try this:
Emp employeeRec = new Emp();
employeeRec.username = txtName.text;
employeeRec.password = txtPassword.text;
AddEmployees(employeeRec);
Related
Trying to return value from GetStage_details() methods and bind it to ViewBag.Stage_details but getting error at var result.
Error msg is :
can't implicitly convert type oracle.ManagedDtaAccessclient.oracledatareader to System.Collection.generic.List<Models.Stage_Details."
Any idea how to resolve it show that correct value return from table and bind to ViewBag.Stage_details will be appreciated.
public class Stage_details
{
public int Stage_Cd { get; set; }
public string Stage_Desc { get; set; }
}
public ActionResult Index_shift()
{
ViewBag.Stage_details = new SelectList(GetStage_details(), "Stage_Cd", "Stage_Desc");
}
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText= "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText,conn);
command.CommandType = CommandType.Text;
var result = command.ExecuteReader();
return result;
}
According to Microsoft documentation, You could read each element from reader and build Stage_detail object inside loop, like the following code :
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText = "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText, conn)
{
CommandType = CommandType.Text
};
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Stage_detail.Add(new Stage_details { Stage_Cd = (int)reader["stage_cd"], Stage_Desc = reader["stage_desc"].ToString() });
}
}
return Stage_detail;
}
I hope you find this helpful.
I want to add all Id from customer table in combobox using class and this is my connection class connectionClass in which I made a function for selecting data from databse.
The second is my Customer form(this is customer form coding customerForm) in which i call a function which i made in connection class .
but it only showing the last id in customer form and i want all id in combobox
In the select() method you are returning a string,instead of that you need to populate
dataset and bind the data to combobox.
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("customerid", typeof(string));
dt.Columns.Add("contactname", typeof(string));
dt.Load(reader);
regards
chandra
Instead of string return a List of strings as follows:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Fill_Combo();
}
public void Fill_Combo()
{
Connection2DB cst = new Connection2DB();
cmbBoxId.Items.AddRange(cst.Select().ToArray());
}
}
class Connection2DB
{
public List<string> Select()
{
var ids = new List<string>();
try
{
string sqlqry = "select ID from Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con);
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
ids.Add(dr["ID"].ToString());
}
}
catch (Exception ex)
{
// Handle exception here
}
return ids;
}
}
this function only returning only ID from Customer table. I want to multiple data from Customer table using same method. Can you help me in this one??
Normally, this is not how this site works. First, you should ask a specific question, and show what you have done. Then we may help you.
Here I will try to give you two general solutions for working with a database.
Solution 1:
Let`s say you want to display everything retrieved from the database to your windows form.
First, create the DataGridView object let's call it dataGridView1. You can create it using the designer as any other control. then use the codes below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = GetData();
}
public DataTable GetData()
{
string ConStr = " your connection string "; // Write here your connection string
string query = #"SELECT * FROM Customer"; // or write your specific query
DataTable dataTable = new DataTable();
SqlConnection conn = new SqlConnection(ConStr);
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = null;
try
{
conn.Open();
// create data adapter
da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show($"Cannot read database: {ex.Message}");
}
finally
{
conn.Close();
if (da != null)
da.Dispose();
}
return dataTable;
}
public void FillDataGrid()
{
Connection2DB cst = new Connection2DB();
dataGridView1.DataSource = cst.GetData();
}
}
Solution 2:
Let's say from your database table you want to extract 3 columns: ID (INT), Name (VARCHAR(100)) and Value (VARCHAR(MAX).
First, create a class:
public class Customer
{
public int ID { get; set; }
public string Nmae { get; set; }
public string Value { get; set; }
}
Create the function which returns the list of Customers:
public List<Customer> GetCustomers()
{
var customers = new List<Customer>();
try
{
string sqlqry = "SELECT ID, Name, Value FROM Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con); // here _con is your predefined SqlConnection object
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
customers.Add(new Customer
{
ID = (int)dr["ID"],
Nmae = dr["Name"].ToString(),
Value = dr["Value"].ToString(),
});
}
}
catch (Exception ex)
{
// Handle exception here
}
return customers;
}
Then you can use this data as you want. For example, to fill your ComboBox with IDs you can use this:
public void Fill_Combo()
{
var customers = GetCustomers();
var ids = customers.Select(x => x.ID.ToString());
cmbBoxId.Items.AddRange(ids.ToArray());
}
My GetProduct() method always returns that a product is not found and I have no idea why! I am connected to a database, and I am trying to use the search box on my form to search for an exact product code, and return the code, description, and price.
Exact instructions:
Add a static method named GetProduct to the ProductDB class. This method should receive the product code of the product to be retrieved, and it should return a Product object for that product. If a product with the product code isn’t found, this method should return null. Place the code that works with the database in the try block of a try-catch statement, include a catch block that catches and then throws any SqlException that occurs, and include a finally block that closes the connection.
Here is what I have so far:
static Product product = new Product();
public static Product GetProduct(string code)
{
SqlConnection connection = Connection.GetConnection();
string select = #"SELECT ProductCode, Description, UnitPrice FROM Products WHERE ProductCode = #ProductCode";
SqlCommand selectCommand = new SqlCommand(select, connection);
SqlParameter pCode = new SqlParameter();
pCode.ParameterName = "#ProductCode";
pCode.Value = product.Code;
SqlParameter pDesc = new SqlParameter();
pDesc.ParameterName = "#Description";
pDesc.Value = product.Description;
SqlParameter pPrice = new SqlParameter();
pPrice.ParameterName = "#UnitPrice";
pPrice.Value = product.Price;
selectCommand.Parameters.AddWithValue("#ProductCode", code);
try
{
connection.Open();
SqlDataReader prodReader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);
if (prodReader.Read())
{
product.Code = prodReader["ProductCode"].ToString(); ;
product.Description = prodReader["Description"].ToString();
product.Price = ((decimal)prodReader["UnitPrice"]);
return product;
}
else
{
return null;
}
}
Here is the frmProductSearch.cs
private void btnGetProduct_Click(object sender, EventArgs e)
{
if (Validator.IsPresent(txtCode))
{
this.GetProduct(txtCode.Text);
if (product == null)
{
MessageBox.Show("No product found with this code. " +
"Please try again.", "Product Not Found");
this.ClearControls();
}
else
this.DisplayProduct();
}
}
private void GetProduct(string code)
{
try
{
ProductDB.GetProduct(code); // Add a statement here to call the GetProduct method of the ProductDB class.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
You should probably get rid of any private static Product product fields you have. I think this may be what's causing you confusion because it appears that you're referencing one in your ProductDB class and a different one in your frmProductSearch class. If this is the case, that would explain why you're getting null - because the ProductDB class never touches the static field of the frmProductSearch class (and it shouldn't).
You should simply have all your methods return a Product, and have the calling methods use the returned value rather than relying on a static field to get updated.
So, to modify your code a little, your 'ProductDB' method should return a new product:
public static Product GetProduct(string code)
{
try
{
SqlConnection connection = Connection.GetConnection();
string select = #"SELECT ProductCode, Description, UnitPrice " +
"FROM Products WHERE ProductCode = #ProductCode";
SqlCommand selectCommand = new SqlCommand(select, connection);
selectCommand.Parameters.AddWithValue("#ProductCode", code);
connection.Open();
SqlDataReader prodReader =
selectCommand.ExecuteReader(CommandBehavior.SingleRow);
if (prodReader.Read())
{
return new Product
{
Code = prodReader["ProductCode"].ToString(),
Description = prodReader["Description"].ToString(),
Price = (decimal) prodReader["UnitPrice"]
};
}
else
{
return null;
}
}
catch (SqlException)
{
throw;
}
finally
{
connection.Close();
connection.Dispose();
}
}
Your form method can now consume the return value of this method directly, and pass it along:
private Product GetProduct(string code)
{
// Add a statement here to call the GetProduct method of the ProductDB class.
return ProductDB.GetProduct(code);
}
Finally, you can consume the returned product in your other form method and pass it to your DisplayProduct method:
private void btnGetProduct_Click(object sender, EventArgs e)
{
if (Validator.IsPresent(txtCode))
{
Product product = this.GetProduct(txtCode.Text);
if (product == null)
{
MessageBox.Show("No product found with this code. Please try again.",
"Product Not Found");
this.ClearControls();
}
else
{
this.DisplayProduct(product);
}
}
}
Of course this means you'll need to update your DisplayProduct method to take in the parameter and use that instead of a static field:
private static void DisplayProduct(Product product)
{
// Implementation here...
}
I have created a database with 1 table "emp" and have some data in it. Now every time i start the app, i want a list to fetch the data from db and save it in list because i want to perform some calculations like tax and Gross-Salary on data at runtime for display only(don't want to save it in db ). I have tried many times but i am unable to understand how this can be done. This is my code:
Main Class:
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<emplyee> empLST1 = new List<emplyee>();
if (empLST1 == null)
{
empDB1.loadLST(out empLST1);
}
}
empDB Class:
class empDB
{
private string ConnectionString = #"server=localhost;DATABASE=hris;uid=root;Password=123456;";
internal void loadLST(out List<emplyee> loadedLST)
{
string query = "select name, grade from emp";
try
{
MySqlConnection con = new MySqlConnection(ConnectionString);
con.Open();
MySqlDataReader rdr = null;
MySqlCommand cmd = new MySqlCommand(query, con);
rdr = cmd.ExecuteReader();
while(rdr.Read())
{
List<employee> returnedLst = new List<employee>();
returnedLst.Add(rdr["name"].ToString(), rdr["grade"].ToString());
}
loadedLst = returnedLst;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
I have no idea even if my approach is right or not. I have googled it a few times but i just started working in .net a few days ago so i don't understand how to do it.
Okay i tried this and it also dosn't work:
internal void GetDatabaseList()
{
List<employee> databases = new List<employee>();
MySqlConnection con = new MySqlConnection(ConnectionString);
{
con.Open();
DataTable tbl = con.GetSchema("Databases");
con.Close();
foreach (DataRow row in tbl.Rows)
{
databases.Add(row["hris"].ToString());
}
}
}
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<emplyee> empLST1 = new List<emplyee>();
**if (empLST1 == null)
{
empDB1.loadLST(out empLST1);
}**
}
this will always be false because you defined empLST1 as a new List, meaning its not null
try this
public class Employee
{
public string Name { get; set; }
public string Grade { get; set; }
}
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<Employee> empLST1 = new List<Employee>();
empDB1.loadLST(ref empLST1);
}
public class empDB
{
public void loadLst(ref List<Employee> loadedLST)
{
string query = "select name, grade from emp";
try
{
MySqlConnection con = new MySqlConnection(ConnectionString);
con.Open();
MySqlDataReader rdr = null;
MySqlCommand cmd = new MySqlCommand(query, con);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee emp = new Employee();
emp.Name = rdr["name"].ToString();
emp.Grade = rdr["grade"].ToString();
loadedLST.Add(emp);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Assuming, that that employee class looks like this:
class employee
{
public string Name { get; set; }
public string Grade { get; set; }
}
I'd rewrite loadLST like this:
internal List<employee> loadLST()
{
string query = "select name, grade from emp";
// we should dispose IDisposable implementations:
// connection, command and data reader
using (var con = new MySqlConnection(ConnectionString))
{
con.Open();
using (var cmd = new MySqlCommand(query, con))
using (var rdr = cmd.ExecuteReader())
{
// it is hard to maintain manual mapping
// between query results and objects;
// let's use helper like Automapper to make this easier
Mapper.CreateMap<IDataReader, employee>();
Mapper.AssertConfigurationIsValid();
return Mapper.Map<List<employee>>(rdr);
}
}
}
Improvements:
IDisposable implementations must be disposed explicitly (see this and this)
to avoid manual mapping code, which maps the result from data reader and object (employee instance in your case), the code uses Automapper package
exception handling and out parameter are thrown away. There's no need for exception handling and out parameter here, unless you're writing method like TryToDoSomething (and even in that case your method must return bool to indicate the state of operation, and catch only specific exceptions instead of Exception).
Also note, that your code doesn't match naming guidelines (e.g., employee should be Employee).
I am having trouble with my property always being null in my app, but I believe that the problem may be deeper than that. The requirement is to have a data layer class that contains my connection string to my access database. This calls another class which pulls the database information and sets it back to the data layer class. I must then use ONLY the data layer class to get my records. The problem is that my property is always null. Here is the code for the data layer class:
{
class CustomerDL
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CIS3341.accdb;");
string names;
public void initializeConnection()
{
Customer.initializeConnection(aConnection);
}
public string getNames
{
get { return names; }
set { names = value; }
}
}
}
And here is the other class:
class Customer
{
static OleDbConnection aConnection = null;
string names;
public static void initializeConnection(OleDbConnection aDbConnection)
{
aConnection = aDbConnection;
aConnection.Open();
getNames();
}
public static void getNames()
{
CustomerDL aCustomer = new CustomerDL();
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
OleDbCommand cmd = aConnection.CreateCommand();
OleDbDataReader dbReader = null;
cmd.CommandText = "SELECT CustomerName FROM Customer";
dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
aCustomer.getNames += (string)dbReader["CustomerName"].ToString() + "\r\n";
}
dbReader.Close();
//return aCustomer ;
}
}
Now when i use this code on my form:
public partial class Form1 : Form
{
CustomerDL customer = new CustomerDL();
public Form1()
{
InitializeComponent();
customer.initializeConnection();
string fast = customer.getNames;
richTextBox1.Text = fast;
}
customer.getNames; is always null. Any ideas?
You aren't assigning anything to the proper instance of CustomerDL.
customer.getNames never gets accessed whatsoever. You are initializing your connection, but in that method you use a new CustomerDL: CustomerDL aCustomer = new CustomerDL();. You have to provide that instance to the static method for it to do something.
in CustomerDL the member names has the default value null, you can initialize it with string names = string.Empty;
You really should consolidate the Customer and CustomerDL classes into one class. There is too much duplication. So instead of having CustomerDL call Customer, just put the getnames() code in your CustomerDL class. And scrap all the static modifiers. By your form example, you are instantiating CustomerDL and calling methods on it. Make the class and its methods non-static, and this will work much better for you.
One of the problems that is preventing you from figuring this one out is your naming conventions...
You have both properties and methods named the same (I would leave the word "get" off of properties).
You have a "CustomerDL" object that you named "customer". The problem is you also have a "Customer" class.
You have a static method coded to do what you want, but you are never calling it.
IMHO if you take a little more care in your naming conventions, it will be a lot easier to troubleshoot these kinds of issues....There are a few things wrong with the code, but I quickly gave fixing it a shot. Hope it helps:
class CustomerDL
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CIS3341.accdb;");
public string GetNames()
{
string NamesToReturn = "";
try
{
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
OleDbCommand cmd = aConnection.CreateCommand();
OleDbDataReader dbReader = null;
cmd.CommandText = "SELECT CustomerName FROM Customer";
dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
NamesToReturn += (string)dbReader["CustomerName"].ToString() + "\r\n";
}
dbReader.Close();
catch(Exception ex)
{
}
finally
{
aConnection.Close(); //makes sure it closes...
}
return NamesToReturn;
}
}
Then you can do this:
class Customer
{
private CustomerDL customerData = new CustomerDL();
public string Names { get; set; }
public string FillNames()
{
this.Names = customerData.GetNames();
}
}
public partial class Form1 : Form
{
Customer customer = new Customer();
public Form1()
{
InitializeComponent();
customer.FillNames();
richTextBox1.Text = customer.Names;
}
}
Note: This code is very crude and I have not double checked it, but I beleive it will get you pointed in the right direction.