Date validation

Asked

Viewed 114 times

1

I’m doing a function of ExcelToEntityList, i.e., import Excel data into a list, but need to validate start and end dates.

I’m doing it right?

The function:

  public List<ProdutosConfiguracaoTaxas> ExcelToEntityList(ExcelPackage package, out bool hadErrors)
    {
        hadErrors = false;
        List<ProdutosConfiguracaoTaxas> taxes = new List<ProdutosConfiguracaoTaxas>();
        ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
        DataTable table = new DataTable();
        foreach (ExcelRangeBase firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
        {
            table.Columns.Add(firstRowCell.Text);
        }
        for (int rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
        {
            ProdutosConfiguracaoTaxas tax = new ProdutosConfiguracaoTaxas();
            ExcelRangeBase row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];

            DateTime DtInicio, DtFim;

            DataRow newRow = table.NewRow();
            bool value = false;
            foreach (ExcelRangeBase cell in row)
            {
                newRow[cell.Start.Column - 1] = cell.Text;
                if (!string.IsNullOrEmpty(cell.Text))
                {
                    value = true;
                }
            }

            if (!value) { return taxes; }

            try
            {
                string dateString;

                var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
                if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DtInicio))
                {
                    tax.Data_Incio = ITCore.ExtensionsMethods.ToDateTime((string)newRow[2]);
                }
                else
                {

                }

                tax.NumeroPrestacoes = (int)newRow[0];
                tax.TAN = (int)newRow[1];


                tax.Data_Fim = ITCore.ExtensionsMethods.ToDateTime((string)newRow[3]);
            }
            catch (Exception)
            {
                hadErrors = true;
            }

            taxes.Add(tax);
        }
        return taxes;
    }

Part I’m doing the date validation:

        try
            {
                string dateString;

                var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
                if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DtInicio))
                {
                    tax.Data_Incio = ITCore.ExtensionsMethods.ToDateTime((string)newRow[2]);
                }
                else
                {

                }

                tax.NumeroPrestacoes = (int)newRow[0];
                tax.TAN = (int)newRow[1];


                tax.Data_Fim = ITCore.ExtensionsMethods.ToDateTime((string)newRow[3]);
            }
            catch (Exception)
  • 2

    It would be nice if you said what was the problem you found when testing (If there was an error, if it just didn’t work, these things). It is not very reasonable that someone needs to take your code, try to analyze which part you talk about, test to see if you have error, and you can already simply say the difficulty, no? I did not deny your question, but I understand who has denied it, among other things by what I have just said. There are some very nice people here to help, but it’s good to already clarify the situation more objectively, then it makes it easier for everyone.

  • Test your code if it fails we can help you.

  • He of the error in Try/catch, does not allow to compile, as it gives error in dateString, hence want to know if this is the correct way to validate the dates.

1 answer

2


I assume you’re using the Epplus.

From what I understand, you are trying to throw the Excel data to a DataTable (because it creates DataTables and DataRows in the middle of it there), but at the same time creates a list of a class that receives the Excel data and returns it. It’s weird, but we can adjust.

You’re already using the right functions. Just understand what they’re for. Starting with your question, you’ve already done the parse. Just need to assign:

            var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
            if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DtInicio))
            {
                tax.Data_Incio = DtInicio;
            }

DateTime.TryParseExact does all the work for you and returns two values:

  1. Whether the function execution result was successful or failed;
  2. The result of the conversion of the String for DateTime, in the variable DtInicio passed by reference.

That’s it. The rest is done. Taking advantage, I will edit your code a little with some suggestions.

// Mudei o retorno porque não precisamos voltar necessariamente um List.
// Pode ser também uma Collection ou uma função geradora.
public IEnumerable<ProdutosConfiguracaoTaxas> ExcelToEntityList(ExcelPackage package, out bool hadErrors)
{
    hadErrors = false;

    // Tirei isso porque vou acumular o retorno da função, 
    // Então isto não é mais necessário.
    // var taxes = new List<ProdutosConfiguracaoTaxas>();

    var workSheet = package.Workbook.Worksheets.First();

    // Não vai ser usado.
    // DataTable table = new DataTable();

    // Você está devolvendo uma lista de objetos. Não precisa povoar uma 
    // DataTable pra isso. 
    // foreach (ExcelRangeBase firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
    // {
    //     table.Columns.Add(firstRowCell.Text);
    // }
    for (int rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
    {
        var tax = new ProdutosConfiguracaoTaxas();
        ExcelRangeBase row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];

        DateTime DtInicio, DtFim;

        // Isto também não precisa (já que não tem mais DataTable).
        // DataRow newRow = table.NewRow();
        bool value = false;
        foreach (ExcelRangeBase cell in row)
        {
            newRow[cell.Start.Column - 1] = cell.Text;
            if (!string.IsNullOrEmpty(cell.Text))
            {
                value = true;
            }
        }

        if (!value) { return taxes; }

        try
        {
            string dateString;

            var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
            if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DtInicio))
            {
                tax.Data_Incio = DtInicio;
            }
            // Tirei o else porque ele não faz nada, então não precisa existir.
            // else
            // {

            // }

            // Como não temos mais a DataRow, mudei de newRow para row.
            tax.NumeroPrestacoes = (int)row[0];
            tax.TAN = (int)row[1];

            tax.Data_Fim = ITCore.ExtensionsMethods.ToDateTime((string)row[3]);
        }
        catch (Exception)
        {
            hadErrors = true;
        }

        // Tirei isso porque não estou mais usando a lista de Tax.
        // taxes.Add(tax);
    }

    // yield return acumula taxes no retorno. Quando o loop terminar, 
    // uma enumeração de tax será retornada. 
    yield return taxes;
}
  • 1

    Thanks for the help, that was it! It worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.