Kinyanjui Kamau
Kinyanjui Kamau

Reputation: 1936

C# A better way to validate fields. (Linq to SQL)

Im still trying to learn the C# programming language and have been using Visual Studio 2010 IDE.

I am making a Payroll program and for my Payroll Period module, I have 2 files under Payroll.DLL; IEmployerPeriodService.cs (interface) and EmployerPeriodService.cs.

The code (IEmployerPeriodService.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Payroll.DAL;

namespace Payroll.BLL
{
    public interface IEmployerPeriodService
    {
        IEnumerable<EmployerPeriod> GetAllEmployerPeriods();

        EmployerPeriod GetEmployerPeriod(string code);

        void AddEmployerPeriod(EmployerPeriod employerPeriod);

        void AddEmployerPeriod(EmployerPeriod employerPeriod, string taxYear, string dayHours, string weekDays, string weekHours, string monthDays, string monthHours, string fortnightDays, string fortnightHours, string weeksInMonth, string numberOfFortnights);

        void UpdateEmployerPeriod(EmployerPeriod employerPeriod);

        void UpdateEmployerPeriod(EmployerPeriod employerPeriod, string taxYear, string dayHours, string weekDays, string weekHours, string monthDays, string monthHours, string fortnightDays, string fortnightHours, string weeksInMonth, string numberOfFortnights);

        void DeleteEmployerPeriod(EmployerPeriod employerPeriod);

        string GenerateSAPCode();
    }
}

The code (EmployerPeriodService.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using Payroll.DAL;
using Payroll.Util.Extensions;
using Payroll.Util.Helpers;

namespace Payroll.BLL
{
    public class EmployerPeriodService : IEmployerPeriodService
    {
        private readonly IEmployerPeriodRepository _employerPeriodRepository;

        public EmployerPeriodService(
            IEmployerPeriodRepository employerPeriodRepository)
        {
            Guard.AgainstNullParameter(employerPeriodRepository, "employerPeriodRepository");

            _employerPeriodRepository = employerPeriodRepository;
        }

        public IEnumerable<EmployerPeriod> GetAllEmployerPeriods()
        {
            return _employerPeriodRepository.SelectAll();
        }

        public EmployerPeriod GetEmployerPeriod(string code)
        {
            var rulesException = new RulesException<EmployerPeriod>();

            // Business rule: Answer Id cannot be less than 1
            if (!code.HasValue())
                rulesException.ErrorFor(x => x.Code, "Code cannot be null");

            if (rulesException.Errors.Any()) throw rulesException;

            return _employerPeriodRepository.GetEntity(code);
        }

        public void AddEmployerPeriod(EmployerPeriod employerPeriod)
        {
            // Business rule: 0
            var errors = DataAnnotationsValidationRunner.GetErrors(employerPeriod);

            var rulesException = new RulesException();

            rulesException.ErrorsForModel(errors);

            // Other validation rules

            if (rulesException.Errors.Any()) throw rulesException;

            // Save to database
            _employerPeriodRepository.Insert(employerPeriod);
        }

        public void AddEmployerPeriod(EmployerPeriod employerPeriod, string taxYear, string dayHours, string weekDays, string weekHours, string monthDays, string monthHours, string fortnightDays, string fortnightHours, string weeksInMonth, string numberOfFortnights)
        {
            var rulesException = new RulesException<EmployerPeriod>();

            var tYear = default(short);

            if (!short.TryParse(taxYear, out tYear))
                rulesException.ErrorFor(x => x.U_Tax_year, "The Tax Year field is not in the correct format");
            else employerPeriod.U_Tax_year = tYear;

            var dHours = default(short);

            if (!short.TryParse(dayHours, out dHours))
                rulesException.ErrorFor(x => x.U_Day_hrs, "The Number of Hours in a Day field is not in the correct format");
            else employerPeriod.U_Day_hrs = dHours;

            var wDays = default(short);

            if (!short.TryParse(weekDays, out wDays))
                rulesException.ErrorFor(x => x.U_Week_days, "The Number of Days in a Week field is not in the correct format");
            else employerPeriod.U_Week_days = wDays;

            var wHours = default(short);

            if (!short.TryParse(weekHours, out wHours))
                rulesException.ErrorFor(x => x.U_Week_hrs, "The Number of Hours in a Week field is not in the correct format");
            else employerPeriod.U_Week_hrs = wHours;

            var mDays = default(short);

            if (!short.TryParse(monthDays, out mDays))
                rulesException.ErrorFor(x => x.U_Month_days, "The Number of Days in a Month field is not in the correct format");
            else employerPeriod.U_Month_days = mDays;

            var mHours = default(short);

            if (!short.TryParse(monthHours, out mHours))
                rulesException.ErrorFor(x => x.U_Month_hrs, "The Number of Hours in a Month field is not in the correct format");
            else employerPeriod.U_Month_hrs = mHours;

            var fnDays = default(short);

            if (!short.TryParse(fortnightDays, out fnDays))
                rulesException.ErrorFor(x => x.U_Fortnight_days, "The Number of Days in a Fortnight field is not in the correct format");
            else employerPeriod.U_Fortnight_days = fnDays;

            var fnHours = default(short);

            if (!short.TryParse(fortnightHours, out fnHours))
                rulesException.ErrorFor(x => x.U_Fortnight_hrs, "The Number of Hours in a Fortnight field is not in the correct format");
            else employerPeriod.U_Fortnight_hrs = fnHours;

            var wInMonth = default(short);

            if (!short.TryParse(weeksInMonth, out wInMonth))
                rulesException.ErrorFor(x => x.U_Weeks_in_month, "The Number of Weeks in a Month field is not in the correct format");
            else employerPeriod.U_Weeks_in_month = wInMonth;

            var nOfFn = default(short);

            if (!short.TryParse(numberOfFortnights, out nOfFn))
                rulesException.ErrorFor(x => x.U_No_of_Fortnights, "The Number of Fortnights in a Month field is not in the correct format");
            else employerPeriod.U_No_of_Fortnights = nOfFn;

            if (rulesException.Errors.Any()) throw rulesException;

            AddEmployerPeriod(employerPeriod);
        }

        public void UpdateEmployerPeriod(EmployerPeriod employerPeriod)
        {
            // Business rule: 0
            var errors = DataAnnotationsValidationRunner.GetErrors(employerPeriod);

            var rulesException = new RulesException();

            rulesException.ErrorsForModel(errors);

            // Other validation rules

            if (rulesException.Errors.Any()) throw rulesException;

            // Save to database
            _employerPeriodRepository.Update(employerPeriod);
        }

        public void UpdateEmployerPeriod(EmployerPeriod employerPeriod, string taxYear, string dayHours, string weekDays, string weekHours, string monthDays, string monthHours, string fortnightDays, string fortnightHours, string weeksInMonth, string numberOfFortnights)
        {
            var rulesException = new RulesException<EmployerPeriod>();

            var tYear = default(short);

            if (!short.TryParse(taxYear, out tYear))
                rulesException.ErrorFor(x => x.U_Tax_year, "The Tax Year field is not in the correct format");
            else employerPeriod.U_Tax_year = tYear;

            var dHours = default(short);

            if (!short.TryParse(dayHours, out dHours))
                rulesException.ErrorFor(x => x.U_Day_hrs, "The Number of Hours in a Day field is not in the correct format");
            else employerPeriod.U_Day_hrs = dHours;

            var wDays = default(short);

            if (!short.TryParse(weekDays, out wDays))
                rulesException.ErrorFor(x => x.U_Week_days, "The Number of Days in a Week field is not in the correct format");
            else employerPeriod.U_Week_days = wDays;

            var wHours = default(short);

            if (!short.TryParse(weekHours, out wHours))
                rulesException.ErrorFor(x => x.U_Week_hrs, "The Number of Hours in a Week field is not in the correct format");
            else employerPeriod.U_Week_hrs = wHours;

            var mDays = default(short);

            if (!short.TryParse(monthDays, out mDays))
                rulesException.ErrorFor(x => x.U_Month_days, "The Number of Days in a Month field is not in the correct format");
            else employerPeriod.U_Month_days = mDays;

            var mHours = default(short);

            if (!short.TryParse(monthHours, out mHours))
                rulesException.ErrorFor(x => x.U_Month_hrs, "The Number of Hours in a Month field is not in the correct format");
            else employerPeriod.U_Month_hrs = mHours;

            var fnDays = default(short);

            if (!short.TryParse(fortnightDays, out fnDays))
                rulesException.ErrorFor(x => x.U_Fortnight_days, "The Number of Days in a Fortnight field is not in the correct format");
            else employerPeriod.U_Fortnight_days = fnDays;

            var fnHours = default(short);

            if (!short.TryParse(fortnightHours, out fnHours))
                rulesException.ErrorFor(x => x.U_Fortnight_hrs, "The Number of Hours in a Fortnight field is not in the correct format");
            else employerPeriod.U_Fortnight_hrs = fnHours;

            var wInMonth = default(short);

            if (!short.TryParse(weeksInMonth, out wInMonth))
                rulesException.ErrorFor(x => x.U_Weeks_in_month, "The Number of Weeks in a Month field is not in the correct format");
            else employerPeriod.U_Weeks_in_month = wInMonth;

            var nOfFn = default(short);

            if (!short.TryParse(numberOfFortnights, out nOfFn))
                rulesException.ErrorFor(x => x.U_No_of_Fortnights, "The Number of Fortnights in a Month field is not in the correct format");
            else employerPeriod.U_No_of_Fortnights = nOfFn;

            if (rulesException.Errors.Any()) throw rulesException;

            UpdateEmployerPeriod(employerPeriod); 
        }

        public void DeleteEmployerPeriod(EmployerPeriod employerPeriod)
        {
            var bm = GetEmployerPeriod(employerPeriod.Code);

            if (bm != null)
            {
                // Delete from database
                _employerPeriodRepository.Delete(bm);
            }
        }

        public string GenerateSAPCode()
        {
            var result = default(long);

            var codesList = from b in GetAllEmployerPeriods()
                            select new { Code = long.Parse(b.Code) };

            codesList = codesList.OrderBy(x => x.Code);

            var lastRecord = codesList.LastOrDefault();

            if (lastRecord != null)
                result = lastRecord.Code + 1;

            return result.ToString();
        }
    }
}

The Code (PayRollPeriodForm.cs):

This the code behind the form

private void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                // Get service instance
                var employerPeriodService = Program.Kernel.Get<IEmployerPeriodService>();

                // Get new code
                var newCode = employerPeriodService.GenerateSAPCode();

                // Create object
                var employerPeriodAdd =
                    new EmployerPeriod
                    {
                        Code = newCode,
                        Name = newCode,
                        U_Starting_period = dateTimePicker1.Value,
                        U_Ending_period = dateTimePicker2.Value,
                    };

                // Save record
                employerPeriodService.AddEmployerPeriod(
                    employerPeriodAdd,
                    cb_tax_year.Text,
                    cb_number_hours.Text,
                    cb_number_days_week.Text,
                    txt_number_hours_week.Text,
                    cb_number_days_month.Text,
                    txt_number_hours_month.Text,
                    cb_number_days_fortnight.Text,
                    txt_number_hours_fortnight.Text,
                    cb_avg_weeks_month.Text,
                    cb_avg_fortnights_month.Text);

                MessageBox.Show("Employer Payroll Period Added Successfully. Intake Ref: " + newCode.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                //clear textfields after input
                cb_tax_year.Text = null;
                cb_number_hours.Text = null;
                cb_number_days_week.Text = null;
                txt_number_hours_week.Text = "";
                cb_number_days_month.Text = null;
                txt_number_hours_month.Text = "";
                cb_number_days_fortnight.Text = null;
                txt_number_hours_fortnight.Text = "";
                cb_avg_weeks_month.Text = null;
                cb_avg_fortnights_month.Text = null;
                dateTimePicker1.Text = null;
                dateTimePicker2.Text = null;

                btn_add.Enabled = false;
            }
            catch (RulesException ex)
            {
                MessageBox.Show(ex.GetErrorMessages(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

Is there a better way to validate the fields that I have in the overloaded method of AddEmployerPeriod. I have a table with more than 30 fields and I was thinking there has to be a better way to validate the fields.

I also want to use something similar for updating(editing) details.

the code for editing is:

private void btn_update_Click(object sender, EventArgs e)
        {
            try
            {
                // Get service instance
                var employerPeriodService = Program.Kernel.Get<IEmployerPeriodService>();

                // Get record
                var employerPeriodUpdate = employerPeriodService.GetEmployerPeriod(SAPCodePeriod);

                if (employerPeriodUpdate != null)
                {
                    // Update record

                    employerPeriodUpdate.U_Tax_year = short.Parse(cb_tax_year.Text);
                    employerPeriodUpdate.U_Day_hrs = short.Parse(cb_number_hours.Text);
                    employerPeriodUpdate.U_Week_days = short.Parse(cb_number_days_week.Text);
                    employerPeriodUpdate.U_Week_hrs = short.Parse(txt_number_hours_week.Text);
                    employerPeriodUpdate.U_Month_days = short.Parse(cb_number_days_month.Text);
                    employerPeriodUpdate.U_Month_hrs = short.Parse(txt_number_hours_month.Text);
                    employerPeriodUpdate.U_Fortnight_days = short.Parse(cb_number_days_fortnight.Text);
                    employerPeriodUpdate.U_Fortnight_hrs = short.Parse(txt_number_hours_fortnight.Text);
                    employerPeriodUpdate.U_Weeks_in_month = short.Parse(cb_avg_weeks_month.Text);
                    employerPeriodUpdate.U_No_of_Fortnights = short.Parse(cb_avg_fortnights_month.Text);
                    employerPeriodUpdate.U_Starting_period = dateTimePicker1.Value;
                    employerPeriodUpdate.U_Ending_period = dateTimePicker2.Value;

                    // Save record
                   //employerPeriodService.UpdateEmployerPeriod(employerPeriodUpdate);

                    MessageBox.Show("Tax Year Details Edited Successfully");
                }
            }
            catch (RulesException ex)
            {
                MessageBox.Show(ex.GetErrorMessages(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

Do I use something similar to my add overload method? I hope my questions are clear enough.

Upvotes: 2

Views: 1046

Answers (1)

Atzoya
Atzoya

Reputation: 1387

There are many libraries that can handle this kind of validation, and you can always build a custom validation framework.

The library that i am using is the enterprise library validation application block. You can create validators in your views under the controls that need validating and write the validation rules in your model class (EmployerPeriod in your case) by adding attributes to the properties that need validating.

Upvotes: 2

Related Questions