method overloading Visual Studio - c#

I am doing a project. This project involves a database with a table called 'Customers'. In the same project, I have a form called 'frmAddNewCustomer'. This form takes in 9 attributes relating to the customer. There is a button that when clicked has code that allows these attributes to be entered into the database respectively. I also have a class called 'CustomerDAL' that allows me to performs tasks on the database table (Insert, Update, Delete etc.) and class holds the method that I used to enter data into the database from the 'frmAddNewCustomer' form. Finally, I have a Class called 'CustomerModel' which represents a record in the database. In the CustomerDAL class, the parameters for the method mentioned earlier (the one that allows me to enter data to the database through the UI form) are an object created from the CustomerModel class. my problem is that in the UI form it says that the method has no overload for 9 arguements.
this is the customer model class:
public int CustomerID { get; set; }
public string Title { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Streetname { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string WeddingGiftList { get; set; }
public CustomerModel( string title, string forename, string surname, string email, string streetname,string town, string county, string postcode, string weddingGiftlist)
{
Title = title;
Forename = forename;
Surname = surname;
Email = email;
Streetname = streetname;
Town = town;
County = county;
Postcode = postcode;
WeddingGiftList = weddingGiftlist;
}
public CustomerModel()
{
}
this is the CustomerDAL class:
private static string _connectionString = ConfigurationManager.ConnectionStrings["SimpsonsConnection"].ConnectionString;
public static int AddNewCustomer(CustomerModel newCustomer)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
string sqlQuery = string.Format("INSERT INTO [Customer] VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}','{6}','{7}','{8}')", newCustomer.Title, newCustomer.Forename, newCustomer.Surname, newCustomer.Email, newCustomer.Streetname, newCustomer.Town, newCustomer.County, newCustomer.Postcode, newCustomer.WeddingGiftList);
SqlCommand insertCommand = new SqlCommand(sqlQuery, connection);
int rowsAffected = insertCommand.ExecuteNonQuery();
connection.Close();
return rowsAffected;
}
}
//this is the UI forms click event on the button:
//this is to add the customer details to the database when the 'Create button is clicked'
if ( cmbxTitle.Text != "" || txtForename.Text != "" || txtSurname.Text != "" || txtEmail.Text != "" || txtStreetName.Text != "" || txtTown.Text != "" || txtCounty.Text != "" || txtPostCode.Text != "" || cmbxWeddingGiftList.Text != "")
{
int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text);
if(rowsAffected == 1)
{
MessageBox.Show("Customer has been added successfully");
Form myNextScreen = new frmMenu();
myNextScreen.Show();
}
else
{
MessageBox.Show("Customer was not able to be registered. Please re-enter details carefully");
}
}
else
{
lblInfo.Visible = true;
MessageBox.Show("Please enter all details");
}
In the UI form my error is when I reference the 'AddNewCustomer' method from the CustomerDAL class.error Image
I'm just not sure how to fix this error as I think I have 9 arguments?
It would mean a lot if you could help me with this as I'm relatively new to databases in c#

In my opinion, your problem can be in not defining the object
int rowsAffected = CustomerDAL.AddNewCustomer(new CustomerModel{....});

instead of this
int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text);
have this
var newCustomer = new Customer
{
Title = cmbxTitle.Text,
//rest of customer properties
};
int rowsAffected = CustomerDAL.AddNewCustomer(newCustomer)

Related

Checking if an object is on the list I created [duplicate]

This question already has answers here:
how to check if List<T> element contains an item with a Particular Property Value
(7 answers)
Closed 1 year ago.
I am making a code that registers a number of parameters and then checks if these parameters are already in the list, in the case, for example, I want to check if an Email is in this list, how can I do this check?
List<Professional> lprofessional = new List<Professional>();
public int role_id = 1;
public string First_name { get; set; }
public string Last_name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
public Professional(int role_id, string firstname, string lastname, string email, string phone, string description) {
this.First_name = firstname;
this.Last_name = lastname;
this.Email = email;
this.Phone = phone;
this.Description = description;
}
public void Create()
{
Professional pro = new Professional(role_id, First_name, Last_name, Email, Phone, Description);
if (lprofessional.Contains(email)//Here is the check maybe...
{
lprofessional.Add(pro);
role_id++;
}
}
if (lprofessional.Any(p => p.Email == email))
{
// already in the list
}
else
{
// not yet in the list
}
Alternatively:
var p = lprofessional.FirstOrDefault(p => p.Email == email);
if (p is object)
{
//already in the list, and you can use "p" to see or change other properties
}
else
{
// not in the list
}
I know there are also newer options using pattern matching to do this in even less code, but I've not yet incorporated pattern matching into my own workflow.
var email = "test#test.com";
var listElement = lprofessional.Where(x=> x.Email.Equals(email)).FirstOrDefault();
if(listElement != null)
{
//some code
}
or
var email = "test#test.com";
var result = lprofessional.Any(x => x.Email.Equals(email));
if( result)
{
//some code here
}

Dapper Multi Mapping stops at 3rd lavel nesting

I have taken a question and modified it to form my question. I have a query that is mapping correctly from the initial class, to the second class and elements attached to the second class (3rd) but not elements attached to the 3rd class. an example as follows.
public class Part {
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address {
public int Id { get; set; }
public string Street { get; set; }
public SiteOu Ou { get; set; }
}
public class SiteOu {
public int Id { get; set; }
public SiteOuName SiteOuN { get; set; }
}
public class SiteOuName
{
public int Id { get; set; }
public string Name { get; set; }
}
Dapper:
public void TestSplitOn()
{
var conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=db");
conn.Open();
const string sql = "select Id = 1, Name = 'My Part', " +
"Id = 2, Street = 'My Street', " +
"Id = 1, SiteOuNameId = '1'" +
"Id = 1, Name = 'My Site', " +;
var result = conn.Query<Part, Address, SiteOu, SiteOuName, Part>(sql, (part, address, siteOu, siteOuName) =>
{
part.Address = address;
address.Ou = siteOu;
SiteOu.SiteOuName = siteOuName
return part;
},
commandType: CommandType.Text
).FirstOrDefault();
}
If I remove SiteOuName from the Dapper mapping, the code works but doesn't map the SiteOuName object, but when I leave it as it is, it shows me that the address object reference is null.
As far as I can see there are couple of issues in your Dapper code.
Firstly, your query should be like;
const string sql = "select Id = 1, Name = 'My Part', " +
"Id = 2, Street = 'My Street', " +
"Id = 1, SiteOuNameId = '1'," +
"Id = 1, Name = 'My Site'";
You are missing a comma next to the SiteOuNameId = '1' and you have extra comma and '+' sign next to Name = 'My Site'
Secondly, your mapping is wrong, it should be like
part.Address = address;
address.Ou = siteOu;
siteOu.SiteOuN = siteOuName;
return part;
In your code, S is upper case which makes complier think you are using the SiteOu class.
Also, SiteOu class doesn't have a property named SiteOuName, it should be SiteOuN.

Filling DataGridView from database

I have a DataGridView which I want to fill from my database. I got an empty DataGridView. Here's my script and what I tried :
private void listUser_Load(object sender, EventArgs e)
{
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers;
}
My class :
class User
{
private int id { get; set; }
private int level { get; set; }
private string name { get; set; }
private string password { get; set; }
private string email { get; set; }
public User(int idP, int levelP, string nameP, string passwordP, string emailP)
{
id = idP;
level = levelP;
name = nameP;
password = passwordP;
email = emailP;
}
}
And the way I got my data :
public static List<User> getUsers()
{
MySqlDataReader result = executerSelect("SELECT id, level, name, email, password FROM users");
List<User> users = new List<User>();
if(result != null)
{
while(result.Read())
{
int id = int.Parse(result[0].ToString());
int level = int.Parse(result[1].ToString());
string name = result[2].ToString();
string email = result[3].ToString();
string password = result[4].ToString();
users.Add(new User(id, level, name, password, email));
}
}
return (users.ToList());
}
I already tried with a binding source but I'm not able to link with my datagridview
Thanks for help
You need to assign lesUsers , instead of getUsers which is a method
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers ;
EDIT
check if you have public properties which would be used to display the contents of the Class as columns in the DataGridView

MySQL query data retrieve giving everything null despite data in database

so like my question said, I doing a mySQL query but the query is giving me some headache as I am trying to retrieve the data from my database as a object so I can reiterate in my javascript code however the data I retrieve out from the database is all null and 0 despite my database it self do not have value with null or 0. I have set my database value that it cannot be null.
So, this is the value in my database:
This is the data that I retrieved till.
{"Musicid":0,"Audioid":null,"Description":null,"MusicTitle":null,"AudioPath":null,"ImagePath":null,"PriceType":null,"UploadDate":"\/Date(-62135596800000)\/","Views":0,"Likes":0,"NoOfReports":0,"Type":null}
This is my C# class
public class music{
public int Musicid { get; set; }
public String Audioid { get; set; }
public String Description { get; set; }
public String MusicTitle { get; set; }
public String AudioPath { get; set; }
public String ImagePath { get; set; }
public String PriceType { get; set; }
public DateTime UploadDate { get; set; }
public int Views { get; set; }
public int Likes { get; set; }
public int NoOfReports { get; set; }
public String Type { get; set; }
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
musicid = this.Musicid;
audioid = this.Audioid;
description = this.Description;
MusicTitle = this.MusicTitle;
audioPath = this.AudioPath;
imagePath = this.ImagePath;
priceType = this.PriceType;
uploadDate = this.UploadDate;
views = this.Views;
likes = this.Likes;
noOfreports = this.NoOfReports;
Type = this.Type;
}
}
This is my c# code
public List<music> Searchdatabase(String searchvalue)
{
List<music> al = new List<music>();
ArrayList array = new ArrayList();
//sql connection, query values to database error need help
string cs = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
con.Open();
String query = "SELECT music.* FROM music WHERE MusicTitle LIKE #search";
MySqlCommand command = new MySqlCommand(query, con);
command.Parameters.AddWithValue("#search", "%" + searchvalue + "%");
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (searchvalue == null || searchvalue == "")
{
break;
}
else
{
al.Add(new music(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(5), reader.GetString(6), reader.GetDateTime(7), reader.GetInt32(8), reader.GetInt32(9) , reader.GetInt32(10), reader.GetString(11)));
}
}
if (reader != null)
reader.Close();
}
}
return al;
}
The command seems to be working just like whatever I key to the searchbox value which is for searchvalue like anything that not related to the musicTitle in the database will provided me with nothing which is correct. But anything that have relation to the musicTitle it return me the object array just that the value retrieved is null and 0 despite having data in database.
I know this may be lengthy, hopefully someone can help me. Thanks
Your constructor code is wrong. You're assigning values to constructor parameters rather than the other way around.
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
this.Musicid = musicid;
....
this.NoOfReports = noOfreports;
this.Type = Type;
}
Also, look into object initializers instead, so you don't write these ridiculous constructors.
new music { Musicid = musicid, Type, NoOfReports = noOfreports .... };
In this case you don't even need a constructor. As you can see, if the variable name is the same as the property name, you don't have to write this as X = Y, but just X. So it's like a constructor, but you don't have to write the actual constructor.
Your constructor has everything in reverse order. You are setting the arguments instead of the properties. Change it to this and try again.
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
this.Musicid =musicid;
this.Audioid = audioid;
this.Description = description;
this.MusicTitle = MusicTitle;
this.AudioPath = audioPath;
this.ImagePath = imagePath;
this.PriceType = priceType;
this.UploadDate = uploadDate;
this.Views = views;
this.Likes = likes;
this.NoOfReports = noOfreports;
this.Type = Type;
}

How to get values from a list<class>

I have these classes, which i want to use it to login, to check if the email and password is the same, then it will redirect to the respective page.
public class Account
{
public Account(){}
public int accID { get; set; }
public string emailAddress { get; set; }
public string password { get; set; }
public string name { get; set; }
public string company { get; set; }
public string position { get; set; }
public string department { get; set; }
public string mobileNo { get; set; }
public string officeNo { get; set; }
}
public static SADataReader DoSelectQuery(String sql)
{
SAConnection myConnection = new SAConnection(DB_STR);
//open the connection
myConnection.Open();
//Create a command object.
SACommand myCommand = myConnection.CreateCommand();
//Specify a query.
myCommand.CommandText = sql;
//Create a DataReader for the command
SADataReader reader = myCommand.ExecuteReader();
return reader;
}
public static List<Account> getAllAccountFromReader(SADataReader reader){
List<Account> results = new List<Account>();
while (reader.Read())
{
int accID = reader.GetInt32(0);
string emailAddress = reader.GetString(1);
string password = reader.GetString(2);
string name = reader.GetString(3);
string company = reader.GetString(4);
string position = reader.GetString(5);
string department = reader.GetString(6);
string mobileNo = reader.GetString(7);
string officeNo = reader.GetString(8);
Account Accounts = new Account();
Accounts.accID = accID;
Accounts.emailAddress = emailAddress;
Accounts.password = password;
Accounts.name = name;
Accounts.company = company;
Accounts.position = position;
Accounts.department = department;
Accounts.mobileNo = mobileNo;
Accounts.officeNo = officeNo;
results.Add(Accounts);
}
return results;
}
public static List<Account> getAllAccounts()
{
//Specify a query.
string sql = "SELECT accountID,emailAddress,password,name,company,position,department,mobileNo,officeNo FROM account";
SADataReader reader = DoSelectQuery(sql);
List<Account> results = getAllAccountFromReader(reader);
return results;
}
.CS file to check for fields
protected void btnSubmit_Click(object sender, EventArgs e)
{
string email = tbEmail.Text;
string password = tbPW.Text;
List<Account> getAccounts = MinuteDB.getAllAccounts();
// Session["getAllAccount"] = getAccounts;
if(email ==?? && password == ??)
{
//Session["name"] = name.ToString();
//Session["ID"] = Convert.ToInt32(accID.ToString());
Response.Redirect("HomePage.aspx");
}
else if (email == "" && password == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please enter Login and Password!');", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Wrong Login Or Password!');", true);
}
}
How do i retrieve the email and password from the List getAccounts so that i can check for if (email == email from the list account && password == password from list account) ??
Try LINQ/extension methods.
var account = MinuteDB.getAllAccounts()
.Where(p=> p.emailAddress==email && p.password==password)
.FirstOrDefault();
if(account!=null)
{
Session["id"]=account.accID;
Session["name"]=account.name;
Response.Redirect("~/other_page.aspx");
}
Write following code in other_page.aspx to read session key-value.
int id=0;
string name="";
if(Session["id"]!=null)
id=int.Parse(Session["id"].ToString());
if(Session["name"]!=null)
name=Session["name"];
PS: Do not store password in the List<T>. You may assign Account object reference to the Session.
e.g
if(account!=null)
{
Session["account"]=account;
Response.Redirect("~/other_page.aspx");
}
and to retrieve the account value from session:
Account account=Session["account"] as Account;
if(account!=null)
{
//read the property value of Account
}
Are you wanting to find the email in the list of accounts and check the password entered matches? If so, superficially you just loop through each along the lines of:
private bool isPasswordValid(string email, string password)
{
foreach (Account account in Accounts)
{
if (account.emailAddress != email)
continue;
return (account.password == password);
}
return false;
}
You could alternatively return a Dictionary<string, Account> to simplify and speed up the search.
Update
So instead of the following line:
if(email ==?? && password == ??)
Insert
if (isPasswordValid(email, password))
// it is valid
else
// it is not valid, redirect
This assumes the getAccounts variable is accessible to isPasswordValid. In your current code it would not be visible, so you might want to pass it in as a parameter.

Categories