C#: how to display the employee names with lowest salary - c#-4.0

I have to create an appropriate GUI to enter information for at least 10 employee. for each employee i have to enter the following information. employee ID, employee first name, employee last name and yearly salary. besides i have to check for the correctness of the input data. in addition i need to create a separate class EMPLOYEE, containing employee information: employee ID, first name , last name and yearly salary. the class should have constructors properties and methods. all the employee information has to be stored in a array of type employee. after reading form GUI the information about particular employee , also create an object of class employee(element of the array) with the relevant constructor. the user would like to be able to find the employee with lowest yearly salary despite of having more than one employee with lowest yearly salary. and display information about them. user should be provided with appropriate GUI to display the required information.
i need to assure including in my program appropriate code for handling exceptions and also methods where appropriate.
here is the class employee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Searchbtn_Click(object sender, EventArgs e)
{
employee[0] = new Employee();
employee[1] = new Employee(17433, "Adrian", "Smith", 8000.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 12000.00);
//employee[10] = new Employee(17442, "Mark", "Jonson", 17000.00);
for(int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
richTextBox1.AppendText(employeeString);
}
}
Employee[] employee = new Employee[10];
private void getinfibtn_Click(object sender, EventArgs e)
{
Find();
}
private void Find()
{
}
}
}
My question is:
How the user can find the employee with the lowest yearly salary. i have to make sure that there can be more than one employee with lowest yearly salary and display the information about them. providing the user with an appropriate GUI (e.g a message box) to display the required information with including appropriate code for handling exceptions and also use methods where appropriate?

You need to make your class Employee to implement the IComparable interface, then compare the objects against the salary and in the other class sort the array...
Example:
public class Employee :IComparable<Employee>
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public int CompareTo(Employee other)
{
return salary.CompareTo(other.salary);
}
}
private void Find()
{
Array.Sort(employee); // after this Employee is sorted
employee[0];
or
employee[9];
}

this will give a list of lowest salary emplyees
employee.Add(new Employee(17434, "Stephen", "Rad", 9000.00));
employee.Add(new Employee(17435, "Jesse", "Harris", 800.00));
employee.Add(new Employee(17436, "jonatan", "Morris", 9500.00));
var c = employee.OrderBy(i => i.salary).ToList();
var e = employee.Where(i => Math.Abs(i.salary - c[0].salary) < 1).ToList();

Modified you code a little bit
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
//public Employee()
//{
// employeeID = 0;
// fullName = "";
// lastName = "";
// salary = 0.0;
//}
//public Employee(int empIDValue, string fullNameVal, string lastNameVal)
//{
// employeeID = empIDValue;
// fullName = fullNameVal;
// lastName = lastNameVal;
// salary = 0.0;
//}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
and to get min values in list
var minEmpSalarylist = employee.Where(x => x.Salary == employee.Min(y => y.Salary)).ToList();
If default constructor is present then all minEmpSalarylist become initialized with default constructor.
and
employee[0] = new Employee();
to change it to
employee[0] = new Employee(17433, "XXX", "YYY", 8000.00);

Related

Servicestack ORMLite update child collection

I can see you can do stuff like this in ORMLite:
var customer = new Customer {
Name = "Customer 1",
PrimaryAddress = new CustomerAddress {
AddressLine1 = "1 Australia Street",
Country = "Australia"
},
Orders = new[] {
new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
}.ToList(),
};
db.Save(customer, references:true);
But what about updating child collections?
How is this done?
To expand on this.
I have a UserAccount class and an Image class internal to UserAccount:
public class UserAccount
{
[AutoIncrement]
public int Id {
get ;
set;
}
public UserAccount()
{
Images = new List<UserImage>();
}
public List<UserImage> Images { get; protected set; }
public UserImage Image { get; set; }
public class UserImage
{
public UserImage()
{
Created = DateTime.Now;
}
public UserImage(string name)
{
Value = name;
Created = DateTime.Now;
}
public string Value { get; set; }
}
}
Doing this:
var fullImage = new UserAccount.UserImage(newImageUrl);
fullImage.IsDefault = true;
user.Image = fullImage;
db.Update (fullImage);
Doesn't work.
Doing this:
var fullImage = new UserAccount.UserImage(newImageUrl);
fullImage.IsDefault = true;
user.Images.Add(fullImage);
db.Update (fullImage);
Doesn't work...
Also doing the same but having image as a seperate entity with it's own ID and setting reference on the parent class doesn't work?
I think this is the way:
var image = new UserImage(newImageUrl);
image.IsDefault = true;
db.Save (image);
var images = user.Images;
images.Add (image);
db.Update (new UserAccount{Id = user.Id, Image = image, Images = images});
I hope I am wrong because that is so ugly :/
[UPDATE]
I have it looking like this now which is much nicer:
db.UpdateOnly (user,
onlyFields: a=> new { a.Image, a.Images},
where: ua => ua.Id == user.Id);

Get property values from a string using Reflection

I am new to this concept of reflection and finding problem in retrieving property value from a string. E.g.
I have a class Employee with following properties :
public string Name {get;set;}
public int Age {get;set;}
public string EmployeeID {get;set;}
string s = "Name=ABCD;Age=25;EmployeeID=A12";
I want to retrieve the value of each property from this string and create a new object of Employee with those values retrieved from the string for each field.
Can anyone please suggest how it can be done using reflection ??
//may be..
string s = "Name=ABCD;Age=25;EmployeeID=A12";
string[] words = s.Split(';');
foreach (string word in words)
{
string[] data = word.Split('=');
string _data = data[1];
Console.WriteLine(Name);
}
Here an example of how you maybe could do it
it used Reflection like you wanted ^^
using System;
using System.Collections.Generic;
using System.Reflection;
namespace replace
{
public class Program
{
private static void Main(string[] args)
{
var s = "Name=ABCD;Age=25;EmployeeID=A12";
var list = s.Split(';');
var dic = new Dictionary<string, object>();
foreach (var item in list)
{
var probVal = item.Split('=');
dic.Add(probVal[0], probVal[1]);
}
var obj = new MyClass();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(dic[property.Name]);
if (property.PropertyType == typeof(Int32))
property.SetValue(obj, Convert.ToInt32(dic[property.Name]));
//else if (property.PropertyType== typeof(yourtype))
// property.SetValue(obj, (yourtype)dic[property.Name]);
else
property.SetValue(obj, dic[property.Name]);
}
Console.WriteLine("------------");
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Age);
Console.WriteLine(obj.EmployeeID);
Console.Read();
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
public string EmployeeID { get; set; }
}
}

ServiceStack OrmLite How can I achieve automatic setting of foreign key/related properties?

I have created the following example to test Foreign Keys and up to this point, it works well. What I would like to be able to do, is use this framework that I built to set the property of the relationship and have it Save the child object when the Parent is saved and automatically set the PrimaryKey and Foreign Key.
The DataManager class exposes the Connection
public class DataManager
{
DataManager()
{
OrmLiteConfig.DialectProvider = SqliteDialect.Provider;
ConnectionString = SqliteFileDb;
updateTables();
}
private void updateTables()
{
using (var dbConn = OpenDbConnection())
{
dbConn.DropAndCreateTable<Person>();
dbConn.DropAndCreateTable<PhoneNumber>();
}
}
public static string SqliteFileDb = "~/App_Data/db.sqlite".MapAbsolutePath();
private static DataManager manager;
public static DataManager Manager {
get
{
if (manager == null)
manager = new DataManager();
return manager;
}
}
public IDbConnection InMemoryDbConnection { get; set; }
public IDbConnection OpenDbConnection(string connString = null)
{
connString = ConnectionString;
return connString.OpenDbConnection();
}
protected virtual string ConnectionString { get; set; }
protected virtual string GetFileConnectionString()
{
var connectionString = SqliteFileDb;
return connectionString;
}
}
These are my POCO's with the BaseClass used to Achieve my results:
public class Person : LiteBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
private List<PhoneNumber> numbers;
public List<PhoneNumber> PhoneNumbers {
get
{
if (numbers == null)
numbers = GetList<PhoneNumber>(p => p.Person == Id);
return numbers;
}
}
}
public class PhoneNumber
{
public string Number { get; set; }
public string Description { get; set; }
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[References(typeof (Person))]
public int Person { get; set; }
public void AddPerson(Person person)
{
Person = person.Id;
}
}
public class LiteBase:INotifyPropertyChanged
{
public List<T> GetList<T>(Expression< Func<T,bool>> thefunction) where T : new()
{
var objects = new List<T>();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
objects = conn.Where<T>(thefunction);
}
return objects;
}
public T GetItem<T>(Expression<Func<T, bool>> thefunction) where T : new()
{
T obj = new T();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
obj = conn.Where<T>(thefunction).FirstOrDefault<T>();
}
return obj;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Simple Class to Create Person and PhoneNumber objects
public class PersonManager
{
public void CreatePerson(string name, string surname, string number)
{
using (var conn = DataManager.Manager.OpenDbConnection())
{
var pnum = new PhoneNumber { Number = number };
var person = new Person
{
Name=name,
Surname = surname,
};
conn.Save<Person>(person);
var id = conn.GetLastInsertId();
person.Id = (int)id;
pnum.AddPerson(person);
conn.Save<PhoneNumber>(pnum);
}
}
public List<Person> GetPeople()
{
List<Person> people;
using (var conn = DataManager.Manager.OpenDbConnection())
{
people = conn.Select<Person>();
}
return people;
}
public List<PhoneNumber> GetNumbers()
{
List<PhoneNumber> numbers;
using (var conn = DataManager.Manager.OpenDbConnection())
{
numbers = conn.Select<PhoneNumber>();
}
return numbers;
}
}
And here is the usage:
var manager = new PersonManager();
manager.CreatePerson("John", "Doe", "12345679");
manager.CreatePerson("Jack", "Smith", "12345679");
manager.CreatePerson("Peter", "Jones", "12345679");
manager.CreatePerson("Dan", "Hardy", "12345679");
var people = manager.GetPeople();
var numbers = manager.GetNumbers();
for (int i = 0; i < people.Count; i++)
{
Console.WriteLine("{0} {1} {2}",
people[i].Name,people[i].Surname,people[i].Id);
}
for (int n = 0; n < numbers.Count; n++)
{
Console.WriteLine("PN: {0} {1}",
numbers[n].Number,numbers[n].Person);
}
for (int p = 0; p < people.Count; p++)
{
var person = people[p];
Console.WriteLine("{0}: {1} {2} {3}",
person.Id,person.Name,person.Surname,person.GetItem<PhoneNumber>(x=>x.Person==person.Id).Number);
}
The output is as I expected :
John Doe 1
Jack Smith 2
Peter Jones 3
Dan Hardy 4
PN: 12345679 1
PN: 12345679 2
PN: 12345679 3
PN: 12345679 4
1: John Doe 12345679
2: Jack Smith 12345679
3: Peter Jones 12345679
4: Dan Hardy 12345679
What I really would like to be able to do is the following:
var john = new Person
{
Name = "John",
Surname = "Smith",
PhoneNumber = new PhoneNumber { Number = "123456789" }
};
conn.Save<Person>(john);
var number = john.PhoneNumber.Number
Is this at all possible?
By default OrmLite v3 blobs all complex types properties in a string field and you need to explicitly set all references.
In the next major v4 release (ETA late Nov 2013), OrmLite adds some support for external references with the [Reference] attribute, which lets you tell OrmLite these properties should be stored in an external table and not blobbed, e.g:
public class Customer
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public CustomerAddress PrimaryAddress { get; set; }
[Reference]
public List<Order> Orders { get; set; }
}
This will allow you to call db.SaveReferences() to save the reference properties, e.g:
var customer = new Customer
{
Name = "Customer 1",
PrimaryAddress = new CustomerAddress {
AddressLine1 = "1 Humpty Street",
City = "Humpty Doo",
State = "Northern Territory",
Country = "Australia"
},
Orders = new[] {
new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
}.ToList(),
};
Assert.That(customer.Id, Is.EqualTo(0)); //Id is not saved yet
//Inserts customer, populates auto-incrementing customer.Id
//Specify `references:true` to populate the ForeignKey ids and
//save the related rows as well, e.g:
db.Save(customer, references:true);
Assert.That(customer.Id, Is.GreaterThan(0));
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(customer.Id));
Assert.That(customer.Orders.All(x => x.CustomerId == customer.Id));
Saving References manually
For more fine-grained control you can also choose which references you want to save, e.g:
db.Save(customer); //Doesn't save related rows
//1:1 PrimaryAddress Reference not saved yet
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(0));
//1:1 PrimaryAddress Reference saved and ForeignKey id populated
db.SaveReferences(customer, customer.PrimaryAddress);
//1:Many Orders References saved and ForeignKey ids populated
db.SaveReferences(customer, customer.Orders);
Loading all related rows with the entity
You can then load the master row and all its references with db.LoadSingleById, e.g:
var dbCustomer = db.LoadSingleById<Customer>(customer.Id);
dbCustomer.PrintDump();
Assert.That(dbCustomer.PrimaryAddress, Is.Not.Null);
Assert.That(dbCustomer.Orders.Count, Is.EqualTo(2));

Displaying a Calculated Column in DynamicData Site table?

According to what I've read, to add a calculated Column to display in the ASP DynamicData table, I just need to add a Readonly property to the table class, and set: [ScaffoldColumn(true)] and return the value.
Here's what I did according to those rules, and it does not work:
public struct Rep
{
public int ID;
public string Name;
}
[ScaffoldTable(true)]
public partial class RepInfo
{
private static bool IsGotAllReps = false;
public static List<Rep> Reps
{
get
{
IQueryable<int> srID = null;
IQueryable<Rep> srName = null;
if (!IsGotAllReps)
{
using (MiscDataContext dc = new MiscDataContext())
{
srID = dc.MdmSalesAdjustment.Select(s => s.RepID).Distinct();
}
using (DWDataContext dc = new DWDataContext())
{
srName = dc.ReportHierarchy.Select(s => new Rep { ID = s.RepEmployeeID, Name = s.RepFirstName + " " + s.RepLastName }).Distinct();
}
}
IsGotAllReps = true;
return srID.Join(srName, id => id, name => name.ID, (id, name) => new Rep { ID = name.ID, Name = name.Name }).ToList();
}
}
//THIS IS AN EXISTING COLUMN IN THE TABLE THAT I WILL USE TO GET THE REPNAME - SEEL CALC COL BELOW
public virtual int RepID
{
get;
set;
}
//THIS IS THE CALCULATED COLUMN THAT I WANT TO SHOW.
[ScaffoldColumn(true)]
public virtual string RepName
{
get
{
return Reps.Where(r => r.ID == this.RepID).FirstOrDefault().Name;
}
}
}
Everything still works, table displays as expected, it's just that I'm not seeing the calculated column.
Thanks!

Having trouble writing a constructor for a object inside another class

Please don't get mad, I am amiting this is help on my homework but I like to learn this and can't find it anywhere. I have looked for it and couldn't find anything like it, idk if I am looking in all the wrong places or for the wrong thing I have two other classes inside my code and having trouble creating another class with class objectives inside of it, I will show what I attempted and see if yall can please help me out. Also, I want to make sure I am using the keyword " this" right in my other two classes. She wanted us to use this in our program and the comments are what we are told to do:
public class Person
{
private String lastName;
private String firstName;
//default constructor
public Person()
{
lastName= null;
firstName = null;
}
//two-parameter constructor
public Person(String lastName, String firstName)
{
this.lastName=lastName;
this.firstName=firstName;
}
//copy constructor
public Person(Person object2)
{
this.lastName=object2.lastName;
this.firstName=object2.firstName;
}
// standard accessor method for each of the two fields
public String getLastName(String lastName)
{
lastName = this.lastName;
return lastName;
}
public String getFirstName(String firstName)
{
firstName = this.firstName;
return firstName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
//mutator method for both fields—using standard mutator methods
public void setName(String lastName,String firstName)
{
this.lastName= lastName;
this.firstName = firstName;
}
//toString method
public String toString()
{
String str = “Last Name: “ + lastName + “\nFirst Name: “ + firstName;
return str;
}
//equals method
public boolean equals(Person name2)
{
boolean status;
if (this.lastName.equals(name2.lastName) && this.firstName.equals(name2.firstName))
status = true;
else
status = false;
return status;
}
//copy method
public Person copy()
{
Person copyObject = new Person(lastName, firstName);
return copyObject;
}
}
public class Date
{
private int month;
private int day;
private int year;
//default constructor
public Date()
{
this (0,0,0);
}
//three-parameter constructor
public Date(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
}
//copy constructor
public Date(Date object2)
{
this (object2.month, object2.day, object2.year);
}
//standard accessor method for each field
public int getMonth(int month)
{
month = this.month;
return month;
}
public int getDay(int day)
{
day = this.day;
return day;
}
public int getYear(int year)
{
year = this.year;
return year;
}
//standard mutator method for each field
public void setMonth(int month)
{
this.month = month;
}
public void setDay(int day)
{
this.day = day;
}
public void setYear(int year)
{
this.year = year;
}
//mutator method for both fields—using standard mutator methods
public void setDate(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year= year;
}
//toString method
public String toString()
{
String str = "Date:" + month+ " " + day + ", " + year;
return str;
}
//equals method
public boolean equals (Date object2)
{
boolean status;
if (this.month == object2.month && this.day == object2.day && this.year == object2.year)
status = true;
else
status = false;
return status;
}
//copy method
public Date copy()
{
Date copyObject = new Date(month, day, year);
return copyObject;
}
}
And this is what I have been trying for my other class and It shows an ERROR:
public class PersonalInfo
{
private Person name;
private Date birthday;
private int idNumber;
// the default constructor
public PersonalInfo()
{
Person name = new Person();
Date birthday = new Date();
this.idNumber = 0;
}
// A constructor that passes 6 parameters
public PersonalInfo(String lastName, String firstName, int month, int day, int year, int idNumber )
{
Person name = new Person(lastName, firstName);
Date birthday= new Date(month, day, year);
this.idNumber = idNumber;
}
}
Please help! And thank you for looking
Since you haven't specified the language or the error message, this is only a qualified guess. If this isn't the actual problem, provide more details.
public PersonalInfo()
{
Person name = new Person();
Date birthday = new Date();
this.idNumber = 0;
}
You are declaring new local variables name and birthday here, rather than using the class members. That means the class members never get initialized, and I suspect that's what the error is trying to tell you.
The right way to do this is to just refer directly to the variables:
this.name = new Person();
this.birthday = new Date();
or, since this is implied when there is no local variable or parameter with the same name:
name = new Person();
birthday = new Date();

Resources