In a C# win forms payroll application I need to calculate employee salary based on their attendance. I've written a stored procedure which calculates earnings of all employees from the data available in attendance table. So when the application calls the SP the data will be shown on a data grid view and then immediately these data will be saved in SalaryTrans
table.
Please note in following demo code I've excluded the use of Interfaces and DI.
Since this is an object oriented development employing MVP design pattern, could you please advice me whether the way I've done this acceptable?
I know that I've not used a Model
, in this case SalaryModel
as the DataService
return a DataSet
object with all earnings figures of all employees. So Could you please show me a way of using a Model (in this case SalaryModel
) in this scenario if possible?
Form
public partial class frmSalary : Form
{
public frmSalary()
{
InitializeComponent();
}
private void btnProcessEarning_Click(object sender, EventArgs e)
{
SalaryPresenter presenter= new SalaryPresenter();
presenter.ShowEarnings();
presenter.SaveEarnings();
}
}
Presenter
class SalaryPresenter
{
private void ShowEarnings()
{
_View.dgEmployeeSalary.DataSource = CalculateEarnings(dtpStartDate.Value,dtpEndDate.Value);
}
private void SaveEarnings()
{
_DataService.InsertEarnings(dgEmployeeSalary);
}
private DataTable CalculateEarnings(DateTime startDate, DateTime endDate)
{
return _DataService.Calculate(startDate, endDate);
}
}
Data Service
class DataService
{
public DataTable Calculate( DateTime fromDate, DateTime toDate)
{
using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand("dbo.sp_Earnings", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("@fromDate", SqlDbType.DateTime).Value = fromDate;
sqlCommand.Parameters.Add("@toDate", SqlDbType.DateTime).Value = toDate;
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand))
{
using (DataSet dataSet = new DataSet())
using (DataTable dataTable = new DataTable())
{
sqlConnection.Open();
dataSet.Tables.Add(dataTable);
sqlAdapter.Fill(dataTable);
return dataTable;
}
}
}
}
}
public void InsertEarnings(DataGrid dataGrid)
{
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
foreach (DataGridViewRow row in dataGrid.Rows)
{
if (row.Cells[1].Value != null)
{
string commandString = "IF NOT EXISTS (SELECT * FROM SalaryTrans WHERE emp_id=@emp_id) BEGIN INSERT INTO salaryTrans..."
//Database transaction code here
}
}
}
}
}