mirror of
https://github.com/Lendaia/oe-alga-feladatok.git
synced 2026-04-23 04:16:32 +01:00
103 lines
2.4 KiB
C#
103 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
namespace OE.ALGA;
|
|
|
|
public class Product
|
|
{
|
|
[Validation(AttributeValidation.NotEmpty)]
|
|
public string Name { get; }
|
|
|
|
[Validation(AttributeValidation.PositiveNumber)]
|
|
public decimal Price { get; }
|
|
|
|
[Validation(AttributeValidation.NonNegative)]
|
|
public int Quantity { get; }
|
|
|
|
[Validation(AttributeValidation.FutureDate)]
|
|
public DateTime? Experiation { get; }
|
|
|
|
public Product(string name, decimal price, int quantity, DateTime? experiarion)
|
|
{
|
|
Name = name;
|
|
Price = price;
|
|
Quantity = quantity;
|
|
Experiation = experiarion;
|
|
}
|
|
}
|
|
public enum AttributeValidation
|
|
{
|
|
NotEmpty,
|
|
PositiveNumber,
|
|
NonNegative,
|
|
FutureDate
|
|
}
|
|
public class ValidationAttribute : Attribute
|
|
{
|
|
public AttributeValidation Rule { get; }
|
|
public ValidationAttribute(AttributeValidation rule)
|
|
{
|
|
Rule = rule;
|
|
}
|
|
}
|
|
public static class Validator
|
|
{
|
|
public static void Validate(Product product)
|
|
{
|
|
bool flag = false;
|
|
var t = product.GetType();
|
|
|
|
foreach (var p in t.GetProperties())
|
|
{
|
|
var value = p.GetValue(product);
|
|
|
|
switch (p.GetCustomAttribute<ValidationAttribute>().Rule)
|
|
{
|
|
case AttributeValidation.NotEmpty:
|
|
if (Convert.ToString(value) == "")
|
|
{
|
|
flag = true;
|
|
}
|
|
break;
|
|
|
|
case AttributeValidation.PositiveNumber:
|
|
if (Convert.ToInt32(value) <= 0)
|
|
{
|
|
flag = true;
|
|
}
|
|
break;
|
|
|
|
case AttributeValidation.NonNegative:
|
|
if (Convert.ToInt32(value) < 0)
|
|
{
|
|
flag = true;
|
|
}
|
|
break;
|
|
|
|
case AttributeValidation.FutureDate:
|
|
if (Convert.ToDateTime(value) < DateTime.Now)
|
|
{
|
|
flag = true;
|
|
}
|
|
break;
|
|
}
|
|
|
|
}
|
|
if (flag)
|
|
{
|
|
throw new WrongProductException();
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine("Product added successfuly");
|
|
}
|
|
}
|
|
}
|
|
public class WrongProductException : Exception
|
|
{
|
|
|
|
}
|