How do I create and handle multiple exceptions in Windows Forms? - c#

In the code below, which does work, I would like to handle 5 different exceptions that could be created by user input.
I understand I should use an IF statement to handle these exceptions but the requirement is to handle the errors with exception handlers. So please I am only looking for input in doing that and not alternatives.
I would like to handle them with exception handlers.
The problem I am having is where to put the exception handling code.
Also being I have 5 exceptions I want to check for does that mean I need 5 different try/catch blocks or can I handle them all in the same block?
The exceptions I am looking for are, trying to create more than 19 accounts, trying to create an account with an initial balance below $300, withdrawing more than the current balance from an account, attempting a transaction on an account that hasn't been created and entering anything other than a number in the TextBox.
So if a user makes one of these errors I would like to throw the error and display a message to the user of the error they have made.
Any assistance is greatly appreciated.
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 MoreRobustBankGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int _nextIndex = 0;
List<Account> accounts = new List<Account>();
decimal balance = 0;
private void createButton1_Click(object sender, EventArgs e)
{
if (accounts.Count < 19 && balance > 300)
{
_nextIndex++;
int accountId = _nextIndex;
decimal.TryParse(amountTextBox2.Text, out balance);
transactionLabel3.Text = "Account: #" + accountId + " created with a starting balance of $" + balance;
accountTextBox1.Text = "" + accountId;
accounts.Add(new Account(balance)
{
AccountId = accountId
});
}
else
{
transactionLabel3.Text = "Can only create up to 19 accounts and starting balance must be $300";
}
}
private void executeButton2_Click(object sender, EventArgs e)
{
decimal amount = 0;
int accountID;
string textAmount = amountTextBox2.Text == "" ? "0" : amountTextBox2.Text;
if (depositRadioButton3.Checked == true)
{
if (string.IsNullOrEmpty(accountTextBox1.Text)) return;
bool accountCanBeConverted = int.TryParse(accountTextBox1?.Text, out accountID);
bool ammountCanBeConverted = decimal.TryParse(amountTextBox2?.Text, out amount);
if (accountCanBeConverted && ammountCanBeConverted && amount > 0)
{
var selectedAccount = GetAccount(accountID);
selectedAccount.DepositFunds(amount);
transactionLabel3.Text = $"Account: #{selectedAccount.AccountId} You made a deposit of ${amount}";
}
}
else if (withdrawRadioButton2.Checked == true)
{
if (string.IsNullOrEmpty(accountTextBox1.Text)) return;
bool accountCanBeConverted = int.TryParse(accountTextBox1?.Text, out accountID);
bool ammountCanBeConverted = decimal.TryParse(amountTextBox2?.Text, out amount);
if (accountCanBeConverted && ammountCanBeConverted && amount > 0)
{
var selectedAccount = GetAccount(accountID);
if (selectedAccount.HasAvailableFunds)
{
selectedAccount.WithdrawFromAccount(amount);
transactionLabel3.Text = $"Account: #{selectedAccount.AccountId} You made a withdrawal of ${amount}";
}
else
{
transactionLabel3.Text = $"Account: #{selectedAccount.AccountId} Does not have available funds to withdraw";
}
}
}
else if (balanceRadioButton3.Checked == true)
{
if (string.IsNullOrEmpty(accountTextBox1.Text)) return;
bool accountCanBeConverted = int.TryParse(accountTextBox1?.Text, out accountID);
var selectedAccount = GetAccount(accountID);
var balance = selectedAccount.GetAvailableBalanceForAccount(accountID);
if (balance == -1234567890)
{
transactionLabel3.Text = $"Invalid account number passed.";
}
else
{
transactionLabel3.Text = $"Account: #{selectedAccount.AccountId} Balance: $ {selectedAccount.GetAvailableBalanceForAccount(accountID)}";
}
}
clearFields();
}
public void clearFields()
{
amountTextBox2.Text = "";
}
public Account GetAccount(int id)
{
return accounts.Where(x => x.AccountId == id).FirstOrDefault();
}
public class Account
{
public Account(decimal balance)
{
Balance = balance;
}
public int AccountId { get; set; }
public decimal Balance { get; set; }
public void WithdrawFromAccount(decimal deductionAmount)
{
Balance -= deductionAmount;
}
public void DepositFunds(decimal depositAmount)
{
Balance += depositAmount;
}
public bool HasAvailableFunds => Balance > 0;
public decimal GetAvailableBalanceForAccount(int accountId)
{
if (accountId == AccountId)
{
return Balance;
}
else
{
return -1234567890;
}
}
}
}
}

Sorry for this being a 'don't do that' answer...
Using exceptions for 'normal' business control flow is not good practice. Exceptions should be for exceptional events.
It is clearly normal for people to create accounts with too little balance, and (for me anyway) to try and withdraw more than they have in the account. These errors should be handled in by normal control flows ( (if balance < MIN_BALANCE) type things).
For a bigger discussion look here https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why
For a way forward maybe investigate raising events when business rules are broken.
There are a lot of ways you can do this... here is a simple thing you could try.
Understanding events and event handlers in C#

I agree that is a poor idea and hope you really know what you are doing. Proper exception handling is a pet peeve of mine and your idea does not sound remotely solid. Here are two articles on the matter I consider must reads and link a lot:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
That all being said, somebody once had a problem that he could not use TryParse because he was running on .NET 1.1. So I quickly cobelled this tryParse alternative together:
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).
bool TryParse(string input, out int output){
try{
output = int.Parse(input);
}
catch (Exception ex){
if(ex is ArgumentNullException ||
ex is FormatException ||
ex is OverflowException){
//these are the exceptions I am looking for. I will do my thing.
output = 0;
return false;
}
else{
//Not the exceptions I expect. Best to just let them go on their way.
throw;
}
}
//I am pretty sure the Exception replaces the return value in exception case.
//So this one will only be returned without any Exceptions, expected or unexpected
return true;
}
I think the problem (very far apart exceptions with the exact same handling) is the same as yours.

Although i totally agree with #Loofer's answer (+1 for that).
Seems you have different Use case.
So giving answer to that
Also being I have 5 exceptions I want to check for does that mean I
need 5 different try/catch blocks or can I handle them all in the same
block?
You should use Multiple Catch block
Something Like
try
{
//
}
catch(Type1Exception exception)
{
}
catch(Type2Exception exception)
{
}
catch(Type3Exception exception)
{
}
And So On.
But there is another way also which answers both of your question.
which is personal suggestion too and that would be to create one helper method something like
private void HandleCustomException(Exception exception)
{
// Your Error Handling Code goes here
if(exception is Type1Exception)
{...}
...
}
And then put separate try catch in you click events, which will send any Exception received to this helper method
Something like this
private void createButton1_Click(object sender, EventArgs e)
{
try
{
if(Your Condition)
{
throw new Type1Exception();
}
}
catch(Exception exception)
{
HandleCustomException(exception);
}
}

Related

Bank Application that Handles Exceptions

I want to create a Banking Application that can handle errors and throw exceptions to handle does errors that occur. These are the Exceptions i want the program to handle :
Withdrawing more than the current balance from an account. This should print an error message.
Attempting a transaction (deposit, withdrawal, or balance) on an account that has not been created yet.
Trying to create more than the maximum number (19) of accounts.
Here is My Code :
using static System.Console;
namespace Bank
{
public partial class Bank : Form
{
public Bank()
{
InitializeComponent();
}
private int _nextIndex = 0;
Accounts[] arrayAccounts = new Accounts[19];
private void createAccountButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
var account = new Accounts();
int accountID;
int balance = 0;
bool success = int.TryParse(accountIDTexTBox.Text, out accountID);
if (!int.TryParse(amountTextBox.Text, out balance))
{
result.Text = "Invalid Format in the Amount Fields please correct";
// MessageBox.Show("Invalid Format in the Amount Fields please correct");
}
if (balance < 300)
{
label5.Text = ("initial deposit must be $300 or greater");
}
else if (success)
{
account.AccountId = accountID;
account.Balance = balance;
arrayAccounts[_nextIndex] = account;
OutPutLabel.Text = "Account # " + accountID + " open with balance of " + balance;
}
else
{
result.Text = ("invalid AccountID entered, Please Correct");
}
}
private Accounts GetAccounts(int id)
{
return arrayAccounts.Where(x => x.AccountId == id).FirstOrDefault();
}
private void DepositRadioButton_CheckedChanged(object sender, EventArgs e)
{
// if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
int amount = 0;
int accountID;
bool succcess1 = int.TryParse(accountIDTexTBox.Text, out accountID);
bool success2 = int.TryParse(amountTextBox.Text, out amount);
try
{
if (succcess1 && success2 && amount > 0)
{
var selectedAccount = GetAccounts(accountID);
selectedAccount.Balance += amount;
OutPutLabel.Text = "Account # " + accountID + " deposit " + amount;
}
else if (!succcess1)
{
result.Text = "You are attempting to deposit to a non-number ID";
}
else if (!success2)
{
result.Text = "Youu are Attempting to deposit \n "+
"to a non_Number amount \n Please reenter the amount";
}
}
catch(NullReferenceException)
{
result.Text = "Account has not being Created , \n Please create an Account";
}
}
private void WithdrawRadioButton_CheckedChanged(object sender, EventArgs e)
{
// if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
int amount = 0;
int accountID;
bool success1 = int.TryParse(accountIDTexTBox.Text, out accountID);
bool success2 = int.TryParse(amountTextBox.Text, out amount);
try
{
if (success1 && success2 && amount > 0)
{
var selectedAccount = GetAccounts(accountID);
selectedAccount.Balance -= amount;
OutPutLabel.Text = amount + " withdraw from account # " + accountID;
}
else if (!success1)
{
result.Text = "You are attempting to withdraw from a non-number ID";
}
else if (!success2)
{
result.Text = "Youu are Attempting to Withdraw \n " +
"a non_Number amount \n Please reenter the amount";
}
}
catch (NullReferenceException)
{
result.Text = "Account has not being created , \n Please Create Account";
}
}
private void exceuteButton_Click(object sender, EventArgs e)
{
/// if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
}
private void balanceRadioButton_CheckedChanged(object sender, EventArgs e)
{
int amount = 0;
int accountID;
bool success1 = int.TryParse(accountIDTexTBox.Text, out accountID);
try
{
if (success1)
{
var selectedAccount = GetAccounts(accountID);
OutPutLabel.Text = "Account # " + accountID + " has a balance of " + selectedAccount.Balance;
}
}
catch (NullReferenceException)
{
result.Text = "Account has not being Created"
+ "\n Please create account.";
}
}
}
class NegativeNumberException : Exception
{
private static string msg = "The Amount you enter is a negative number";
public NegativeNumberException() : base(msg)
{
}
}
I have being able to handle some of the errors using TryParse and If/else statements. Is there a better way to handle those errors using Exceptions.
here is the code for Account Class:
public class Accounts
{
public int AccountId { get; set; }
public decimal Balance { get; set; }
public void Deposit(decimal amount)
{
Balance += amount;
}
public void Withdraw(decimal amount)
{
Balance -= amount;
}
}
}
I really need help on handle those errors using exceptions.
First you'll have to create the requested exception types in your code which we will be using later on.
public class InsufficientBalanceException : Exception
{
// Exception for when a user tries to perform a withdrawal/deposit on an account with an insufficient balance of funds.
public InsufficientBalanceException() { }
public InsufficientBalanceException(string message)
: base(message) { }
public InsufficientBalanceException(string message, Exception inner)
: base(message, inner) { }
}
public class InvalidAccountException : Exception
{
// Exception for when a user is trying to perform an operation on an invalid account.
public InvalidAccountException() { }
public InvalidAccountException(string message)
: base(message) { }
public InvalidAccountException(string message, Exception inner)
: base(message, inner) { }
}
public class InvalidNumberOfAccountsException : Exception
{
// Exception for when a user is trying to create an account beyond the given limit.
public InvalidNumberOfAccountsException() { }
public InvalidNumberOfAccountsException(string message)
: base(message) { }
public InvalidNumberOfAccountsException(string message, Exception inner)
: base(message, inner) { }
}
Then, you need to specify in what conditions you'll be throwing each one of those exceptions.
Keep in mind you do not want to do this in your entity class since those are designed to be kept as simple as possible.
You'll most likely want to put that logic into some sort of a helper class (and not in the UI as you display in your code). Regardless, your code should look similar to the following:
public class AccountHelper
{
public Account GetAccount(int accountID)
{
/* Put some logic in here that retrieves an account object based on the accountID.
* Return Account object if possible, otherwise return Null */
return new Account();
}
public bool IsValidAccount(int accountID)
{
/* Put some logic in here that validates the account.
* Return True if account exists, otherwise return False */
return true;
}
public bool IsValidAmount(decimal amount)
{
/* Put some logic in here that validates the amount.
* Return True if amount is valid, otherwise return False */
return amount > 0;
}
public bool IsSufficientAmount(Account account, decimal amount)
{
/* Put some logic in here that validates the requested amount against the given account.
* Return True if account balance is valid, otherwise return False */
if (account == null)
return false;
return account.Balance >= amount;
}
public void DepositToAccount(int accountID, decimal amount)
{
Account account = null;
if (!IsValidAmount(amount))
throw new InvalidAmountException();
if (!IsValidAccount(accountID))
throw new InvalidAccountException();
account = GetAccount(accountID);
account.Deposit(amount);
}
public void WithdrawFromAccount(int accountID, decimal amount)
{
Account account = null;
if (!IsValidAmount(amount))
throw new InvalidAmountException();
if (!IsValidAccount(accountID))
throw new InvalidAccountException();
account = GetAccount(accountID);
if (!IsSufficientAmount(account, amount))
throw new InsufficientBalanceException();
account.Withdraw(amount);
}
}
Additional Notes:
Your Accounts class should be renamed to Account, as each
instance of that object represents one single account.
You should be trying to separate your business logic from the UI. It
is not a good practice to mix things up together as later on you
might face problems in case changes will have to be made. It will be
much easier to locate the required lines of code if you keep all of
your logic in one file and outside the UI.

C# how to get control focus when exception is thrown in middle layer class

I'm developing a Windows Forms app that has a lot of text and combo boxes which have to be entered manually. So there is a lot of checks if particular control is empty. I would like to get read of all validations in my UI and move them to the Middle Layer. This is great as UI is now validation free and exceptions are triggered as expected, but now I can't know which control causes exception to trigger. Well, I can, but not without intervention in my UI, which I obviously don't want, because this would make Middle layer validation unnecessary, as I could do it completely in UI. So, in short, what I would like to achieve is: if validation is triggered I would like to set focus to a control that causes exception, without focus hard setting in UI. Is this possible? Or if not, what would be the best solution? Any help appreciated.
I have created a simple example:
private void btnConfirm_Click(object sender, EventArgs e)
{
try
{
Customer.CustomerTN = txtCustomerTN.Text;
Customer.CustomerName = txtCustomerName.Text;
Customer.CustomerPhone = txtCustomerPhone.Text;
MessageBox.Show("Customer TN: " + Customer.CustomerTN +
Environment.NewLine +
"Customer Name: " + Customer.CustomerName +
Environment.NewLine +
"Customer Phone: " + Customer.CustomerPhone);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
//Middle Layer Class
public class Customer
{
private static string customerTN;
private static string customerName;
private static string customerPhone;
public static string CustomerTN
{
get
{
return customerTN;
}
set
{
if (value.Length == 0)
{
throw new Exception("Enter Customer TN...");
}
else
{
customerTN = value;
}
}
}
public static string CustomerName
{
get
{
return customerName;
}
set
{
if (value.Length == 0)
{
throw new Exception("Enter Customer Name...");
}
else
{
customerName = value;
}
}
}
public static string CustomerPhone
{
get
{
return customerPhone;
}
set
{
if (value.Length == 0)
{
throw new Exception("Enter Customer Phone...");
}
else
{
customerPhone = value;
}
}
}
}
You could create a hierarchy of Validation classes. Every Validation class would have a list of controls to validate. When the validation takes place, if the control doesn't complies with the rules, you can abort validation by showing up a message and giving focus to that control, e.g.:
public abstract class ControlValidator<T> where T : Control
{
protected List<T> ControlsToValidate;
public ControlValidator(IEnumerable<T> controls)
{
this.ControlsToValidate = new List<T>(controls);
}
public abstract bool ValidateControls();
}
Then, if you want a validator for text boxes you would create a validator like:
public class TextBoxValidator : ControlValidator<TextBox>
{
public TextBoxValidator(IEnumerable<TextBox> controls) : base(controls)
{}
public override bool ValidateControls()
{
foreach(TextBox tb in ControlsToValidate)
{
if (tb.Text == "") // This validates the text cannot be empty
{
MessageBox.Show("Text cannot be empty");
tb.Focus();
return false;
}
}
return True;
}
}
Then you would create a list of validators to store all the validators of your app:
List<ControlValidator> validators = ...
To validate all your controls you would do a foreach like:
foreach(var validator in validators)
{
if (!validator.ValidateControls())
break;
}
The foreach is interrupted once it finds out that at least one control wasn't successfully validated. Hope it helps.

Better way to return debug information instead of using lots of if-else

So I have a boolean method that is used to verify if a command is valid. This is used inside of an engine in which it verifies that the process can continue or not. This is the validation method:
private bool CommandIsValid(WC command)
{
if (command.Address == null ||
command.UserId < 0 ||
String.IsNullOrEmpty(command.CurrencyCode) ||
command.Amount < .01m ||
command.Address.PrimitiveAddress == null ||
String.IsNullOrEmpty(command.Address.Source) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.City) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.Country) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.FirstName) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.LastName) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.Region) ||
command.Address.Created <= DateTime.MinValue)
{
return false;
}
return true;
}
And is called here inside of my method here:
if (!CommandIsValid(cmd))
{
_logger.Debug("Invalid command);
}
The issue is that I want to have some type of information regarding what failed validation. The best solution would have a list of what validations didn't pass, so I could relay that in my logging debugger. Obviously I could do this using a bunch of if-else statements, but it seems sloppy, as having a bunch of if else statements seems very poor style and I was wondering if there is any way in c# or in general I can do to avoid this.
Are you familiar with DataAnnotations and it's associated Validator class?
It would require modifications to your object.
public PrimitiveAddress
{
[Required]
public string City {get;set;}
}
and then you use it like so:
var context = new ValidationContext(command.Address.PrimitiveAddress);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(recipe, context, results);
if (!isValid)
{
foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
}
}
if you've got a base command class you could probably add it in a more generic fashion. You can create your own validation attributes, use IValidatableObject for anything complex, customize the error messages
[Required(ErrorMessage="This is required.")]
Instead of returning a bool, return a container of bool values where first is the overall status False/True then each one reflects a condition of the above. If first element is False, then you check which condition (index) is the false. Looks like it is fixed in size then you may just agree on the sequence.
Something like this:
List<bool> YourFunction(YourDebuggerThing Input)
{
List<bool> Result = new List<bool>();
if (Input.Condition1 == false || Input.Condition2 == false || Input.Condition3 == false || Input.Condition4 == false || Input.Condition5 == false)
Result.Add(false); // first element is always the overall status
if(Input.Condition1 == false) Result.Add(false); else Result.Add(true); // element 2 is condition 1
if(Input.Condition2 == false) Result.Add(false); else Result.Add(true); // element 3 is condition 2
// ..
// ConditionN
return Result;
}
One idea might be to implement your checks within the Get/Set methods of the class' properties, using a custom exception. Such as;
public class PrimitiveAddresses
{
private string _city;
public string City
{
get
{
if(_city != null) {return _city;}
else {throw new CommandInvalidException("No valid city provided");}
}
set
{
_city = value;
}
}
}
public class CommandInvalidException: Exception
{
public CommandInvalidException(string message)
: base(message)
{
}
}
Then during you implementation, use a try/catch to handle the specific error;
public void foo()
{
try
{
if (String.IsNullOrEmpty(command.Address.PrimitiveAddress.City)){} // Ect
}
catch (CommandInvalidException e)
{
Console.WriteLine("Command invalid due to " + e.message);
// Or any other way you want to deal with the missing data
}
}
Hope it helps :)

Where's the best place for validation... constructor or leave to client to call?

This is really a generic (and probably a more subjective too) question. I have some classes where I use an interface to define a standard approach to validating the object state. When I did this, I got to scratching my head... is it best to
1.) allow the constructor (or initializing method) to silently filter out the errant information automatically or...
2.) allow the client to instantiate the object however and let the client also call the interface's IsValid property or Validate() method before moving forward?
Basically one approach is silent but could be misleading in that the client may not be aware that certain pieces of information were filtered away due to it not meeting the validation criteria. The other approach then would be more straight forward, but also adds a step or two? What's typical here?
Okay, after a long day of trying to keep up with some other things, I finally did come up with an example. Please for me for it as it's not ideal and by no means something wonderful, but hopefully should serve well enough to get the point across. My current project is just too complicated to put something simple out for this, so I made something up... and trust me... totally made up.
Alright, the objects in the example are this:
Client: representing client-side code (Console App btw)
IValidationInfo: This is the actual interface I'm using in my current project. It allows me to create a validation framework for the "back-end" objects not necessarily intended for the Client to use since the business logic could be complicated enough. This also allowed me to separate validation code and call as-needed for the business logic.
OrderManager: This is an object the client-side code can use to manage their orders. It's client-friendly so-to-speak.
OrderSpecification: This is an object the client-side code can use to request an order. But if the business logic doesn't work out, an exception can be raised (or if necessary the order not added and exceptions ignored...) In my real-world example I actually have an object that's not quite so black-and-white as to which side of this fence it goes... thus my original question when I realized I could push validation request (calling IsValid or Validate()) to the cilent.
CustomerDescription: represents customers to which I've classified (pretending to have been read from a DB.
Product: Represents a particular product which is classified also.
OrderDescription: Represents the official order request.The business rule is that the Customer cannot order anything to which they've not been classified (I know.. that's not very real-world, but it gave me something to work with...)
Ok... I just realized I can't attach a file here, so here's the code. I apologize for it's lengthy appearance. That was the best I could do to create a client-friendly front-end and business logic back-end using my Validation interface:
public class Client
{
static OrderManager orderMgr = new OrderManager();
static void Main(string[] args)
{
//Request a new order
//Note: Only the OrderManager and OrderSpecification are used by the Client as to keep the
// Client from having to know and understand the framework beyond that point.
OrderSpecification orderSpec = new OrderSpecification("Customer1", new Product(IndustryCategory.FoodServices, "Vending Items"));
orderMgr.SubmitOrderRequest(orderSpec);
Console.WriteLine("The OrderManager has {0} items for {1} customers.", orderMgr.ProductCount, orderMgr.CustomerCount);
//Now add a second item proving that the business logic to add for an existing customer works
Console.WriteLine("Adding another valid item for the same customer.");
orderSpec = new OrderSpecification("Customer1", new Product(IndustryCategory.FoodServices, "Sodas"));
orderMgr.SubmitOrderRequest(orderSpec);
Console.WriteLine("The OrderManager now has {0} items for {1} customers.", orderMgr.ProductCount, orderMgr.CustomerCount);
Console.WriteLine("Adding a new valid order for a new customer.");
orderSpec = new OrderSpecification("Customer2", new Product(IndustryCategory.Residential, "Magazines"));
orderMgr.SubmitOrderRequest(orderSpec);
Console.WriteLine("The OrderManager now has {0} items for {1} customers.", orderMgr.ProductCount, orderMgr.CustomerCount);
Console.WriteLine("Adding a invalid one will not work because the customer is not set up to receive these kinds of items. Should get an exception with message...");
try
{
orderSpec = new OrderSpecification("Customer3", new Product(IndustryCategory.Residential, "Magazines"));
orderMgr.SubmitOrderRequest(orderSpec);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
public interface IValidationInfo
{
string[] ValidationItems { get; }
bool IsValid { get; }
void Validate();
List<string> GetValidationErrors();
string GetValidationError(string itemName);
}
public class OrderManager
{
private List<OrderDescription> _orders = new List<OrderDescription>();
public List<OrderDescription> Orders
{
get { return new List<OrderDescription>(_orders); }
private set { _orders = value; }
}
public int ProductCount
{
get
{
int itemCount = 0;
this.Orders.ForEach(o => itemCount += o.Products.Count);
return itemCount;
}
}
public int CustomerCount
{
get
{
//since there's only one customer per order, just return the number of orders
return this.Orders.Count;
}
}
public void SubmitOrderRequest(OrderSpecification orderSpec)
{
if (orderSpec.IsValid)
{
List<OrderDescription> orders = this.Orders;
//Since the particular customer may already have an order, we might as well add to an existing
OrderDescription existingOrder = orders.FirstOrDefault(o => string.Compare(orderSpec.Order.Customer.Name, o.Customer.Name, true) == 0) as OrderDescription;
if (existingOrder != null)
{
List<Product> existingProducts = orderSpec.Order.Products;
orderSpec.Order.Products.ForEach(p => existingOrder.AddProduct(p));
}
else
{
orders.Add(orderSpec.Order);
}
this.Orders = orders;
}
else
orderSpec.Validate(); //Let the OrderSpecification pass the business logic validation down the chain
}
}
public enum IndustryCategory
{
Residential,
Textile,
FoodServices,
Something
}
public class OrderSpecification : IValidationInfo
{
public OrderDescription Order { get; private set; }
public OrderSpecification(string customerName, Product product)
{
//Should use a method in the class to search and retrieve Customer... pretending here
CustomerDescription customer = null;
switch (customerName)
{
case "Customer1":
customer = new CustomerDescription() { Name = customerName, Category = IndustryCategory.FoodServices };
break;
case "Customer2":
customer = new CustomerDescription() { Name = customerName, Category = IndustryCategory.Residential };
break;
case "Customer3":
customer = new CustomerDescription() { Name = customerName, Category = IndustryCategory.Textile };
break;
}
//Create an OrderDescription to potentially represent the order... valid or not since this is
//a specification being used to request the order
this.Order = new OrderDescription(new List<Product>() { product }, customer);
}
#region IValidationInfo Members
private readonly string[] _validationItems =
{
"OrderDescription"
};
public string[] ValidationItems
{
get { return _validationItems; }
}
public bool IsValid
{
get
{
List<string> validationErrors = GetValidationErrors();
if (validationErrors != null && validationErrors.Count > 0)
return false;
else
return true;
}
}
public void Validate()
{
List<string> errorMessages = GetValidationErrors();
if (errorMessages != null && errorMessages.Count > 0)
{
StringBuilder errorMessageReported = new StringBuilder();
errorMessages.ForEach(em => errorMessageReported.AppendLine(em));
throw new Exception(errorMessageReported.ToString());
}
}
public List<string> GetValidationErrors()
{
List<string> errorMessages = new List<string>();
foreach (string item in this.ValidationItems)
{
string errorMessage = GetValidationError(item);
if (!string.IsNullOrEmpty(errorMessage))
errorMessages.Add(errorMessage);
}
return errorMessages;
}
public string GetValidationError(string itemName)
{
switch (itemName)
{
case "OrderDescription":
return ValidateOrderDescription();
default:
return "Invalid item name.";
}
}
#endregion
private string ValidateOrderDescription()
{
string errorMessage = string.Empty;
if (this.Order == null)
errorMessage = "Order was not instantiated.";
else
{
if (!this.Order.IsValid)
{
List<string> orderErrors = this.Order.GetValidationErrors();
orderErrors.ForEach(ce => errorMessage += "\n" + ce);
}
}
return errorMessage;
}
}
public class CustomerDescription : IValidationInfo
{
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int ZipCode { get; set; }
public IndustryCategory Category { get; set; }
#region IValidationInfo Members
private readonly string[] _validationItems =
{
"Name",
"Street",
"City",
"State",
"ZipCode",
"Category"
};
public string[] ValidationItems
{
get { return _validationItems; }
}
public bool IsValid
{
get
{
List<string> validationErrors = GetValidationErrors();
if (validationErrors != null && validationErrors.Count > 0)
return false;
else
return true;
}
}
public void Validate()
{
List<string> errorMessages = GetValidationErrors();
if (errorMessages != null && errorMessages.Count > 0)
{
StringBuilder errorMessageReported = new StringBuilder();
errorMessages.ForEach(em => errorMessageReported.AppendLine(em));
throw new Exception(errorMessageReported.ToString());
}
}
public List<string> GetValidationErrors()
{
List<string> errorMessages = new List<string>();
foreach (string item in this.ValidationItems)
{
string errorMessage = GetValidationError(item);
if (!string.IsNullOrEmpty(errorMessage))
errorMessages.Add(errorMessage);
}
return errorMessages;
}
public string GetValidationError(string itemName)
{
//Validation methods should be called here... pretending nothings wrong for sake of discussion & simplicity
switch (itemName)
{
case "Name":
return string.Empty;
case "Street":
return string.Empty;
case "City":
return string.Empty;
case "State":
return string.Empty;
case "ZipCode":
return string.Empty;
case "Category":
return string.Empty;
default:
return "Invalid item name.";
}
}
#endregion
}
public class Product
{
public IndustryCategory Category { get; private set; }
public string Description { get; private set; }
public Product(IndustryCategory category, string description)
{
this.Category = category;
this.Description = description;
}
}
public class OrderDescription : IValidationInfo
{
public CustomerDescription Customer { get; private set; }
private List<Product> _products = new List<Product>();
public List<Product> Products
{
get { return new List<Product>(_products); }
private set { _products = value; }
}
public OrderDescription(List<Product> products, CustomerDescription customer)
{
this.Products = products;
this.Customer = customer;
}
public void PlaceOrder()
{
//If order valid, place
if (this.IsValid)
{
//Do stuff to place order
}
else
Validate(); //cause the exceptions to be raised with the validate because business rules were broken
}
public void AddProduct(Product product)
{
List<Product> productsToEvaluate = this.Products;
//some special read, validation, quantity check, pre-existing, etc here
// doing other stuff...
productsToEvaluate.Add(product);
this.Products = productsToEvaluate;
}
#region IValidationInfo Members
private readonly string[] _validationItems =
{
"Customer",
"Products"
};
public string[] ValidationItems
{
get { return _validationItems; }
}
public bool IsValid
{
get
{
List<string> validationErrors = GetValidationErrors();
if (validationErrors != null && validationErrors.Count > 0)
return false;
else
return true;
}
}
public void Validate()
{
List<string> errorMessages = GetValidationErrors();
if (errorMessages != null && errorMessages.Count > 0)
{
StringBuilder errorMessageReported = new StringBuilder();
errorMessages.ForEach(em => errorMessageReported.AppendLine(em));
throw new Exception(errorMessageReported.ToString());
}
}
public List<string> GetValidationErrors()
{
List<string> errorMessages = new List<string>();
foreach (string item in this.ValidationItems)
{
string errorMessage = GetValidationError(item);
if (!string.IsNullOrEmpty(errorMessage))
errorMessages.Add(errorMessage);
}
return errorMessages;
}
public string GetValidationError(string itemName)
{
switch (itemName)
{
case "Customer":
return ValidateCustomer();
case "Products":
return ValidateProducts();
default:
return "Invalid item name.";
}
}
#endregion
#region Validation Methods
private string ValidateCustomer()
{
string errorMessage = string.Empty;
if (this.Customer == null)
errorMessage = "CustomerDescription is missing a valid value.";
else
{
if (!this.Customer.IsValid)
{
List<string> customerErrors = this.Customer.GetValidationErrors();
customerErrors.ForEach(ce => errorMessage += "\n" + ce);
}
}
return errorMessage;
}
private string ValidateProducts()
{
string errorMessage = string.Empty;
if (this.Products == null || this.Products.Count <= 0)
errorMessage = "Invalid Order. Missing Products.";
else
{
foreach (Product product in this.Products)
{
if (product.Category != Customer.Category)
{
errorMessage += string.Format("\nThe Product, {0}, category does not match the required Customer category for {1}", product.Description, Customer.Name);
}
}
}
return errorMessage;
}
#endregion
}
Any reason you wouldn't want the constructor to noisily throw an exception if the information is valid? It's best to avoid ever creating an object in an invalid state, in my experience.
It's completely depends on the client. There's a trade-off as you already mentioned. By default approach number 1 is my favorite. Creating smart classes with good encapsulation and hiding details from client. The level of smartness depends who is going to use the object. If client is business aware you can reveal details according to the level of this awareness. This is a dichotomy and should not be treated as black or white.
Well if I correctly understood, there are basically two question - whether you should fail right away or later and whether you should omit/assume certain information.
1) I always prefer failing as soon as possible - good example is failing at compile time vs failing at run time - you always want to fail at compile time. So if something is wrong with the state of some object, as Jon said - throw exception right away as loudly as you can and deal with it - do not introduce additional complexity down the road as you'll be heading for if/elseif/elseif/elseif/else mumbo jumbo.
2) When it comes to user input, if you are in position to simply filter out errors automatically - just do it. For example, I almost never ask users for country - if I really need it, I automatically detect it from IP and display it in the form. It's way easier if user just needs to confirm/change the data - and I don't need to deal with null situation.
Now, in case we are talking about the data generated by code during some processing - for me situation is drastically different - I always want to know an much as possible (for easier debugging down the road) and ideally you never should destroy any piece of information.
To wrap up, in your case I would recommend that you keep IsValid as simple yes/no (not yes/no/maybe/kindaok/etc). If you can fix some problems automatically - do it, but consider that they keep object in IsValid yes. For everything else, you throw exception and go to IsValid=no.

Is there a way to generically wrap any function call in a try/catch block?

I am writing a bunch of integration tests for a project. I want to call each individual integration point method wrapped in a try/catch block so that when it fails, I get some sort of feedback to display, rather than just crashing the app. I also want to be able to time how long the calls take, and check return values when needed. So, I have an IntegrationResult class with some basic description, result and time elapsed properties:
class IntegrationResult
{
private StopWatch _watch;
public string Description {get;set;}
public string ResultMessage {get;set;}
public bool TestPassed {get;set;}
public string TimeElapsed {get { return _watch == null ? "0" : _watch.Elapsed.TotalMilliseconds.ToString(); } }
public void Start()
{
_watch = StopWatch.StartNew();
}
public void Stop()
{
_watch.Stop();
}
}
The code I keep writing looks like this:
IntegrationResult result = new IntegrationResult();
result.Description = "T-SQL returns expected results";
try
{
result.Start();
SomeIntegrationPoint("potential arguments"); //This is the line being tested
result.Stop();
//do some check that correct data is present
result.TestPassed = true;
result.ResultMessage = "Pulled 10 correct rows";
}
catch(Exception e)
{
result.TestPassed = false;
result.ResultMessage = String.Format("Error: {0}", e.Message);
}
I would really like to be able to just pass the SomeIntegrationPoint method in as an argument and a delegate or something to check the results, but I can't figure out if that's even possible. Are there any frameworks to handle this type of testing, or do you have any suggestions on how I might simplify the code for better reuse? I'm tired of typing this block ;)
(I'm assuming this is C#, as tagged... though the syntax was not in the question.)
You can do this. Just change your result class to include:
class IntegrationResult
{
string Description { get; set; }
string SuccessResultMessage { get; set; }
string FailResultMessage { get; set; }
public IntegrationResult(string desc, string success, string fail)
{
this.Description = desc;
this.SuccessResultMessage = success;
this.FailResultMessage = fail;
}
public bool ExecuteTest(Func<IntegrationResult, bool> test)
{
bool success = true;
try
{
this.Start();
success = test(this);
this.Stop();
this.ResultMessage = success ?
this.SuccessResultMessage :
this.FailResultMessage;
this.TestPassed = true;
}
catch(Exception e)
{
this.TestPassed = false;
this.ResultMessage = String.Format("Error: {0}", e.Message);
success = false;
}
return success;
}
...
You could then change your code for your tests to:
private void myDoTestMethod(string argumentOne, string argumentTwo)
{
IntegrationResult result = new IntegrationResult(
"T-SQL returns expected results",
"Pulled 10 correct rows",
"Wrong number of rows received");
result.Execute( r=>
{
integrationPoint.call(argumentOne, argumentTwo);
//do some check that correct data is present (return false if not)
return true;
});
}
This can easily be extended to include your timings as well.
Have you looked into AOP? PostSharp looks like a nice place to start. There is also an example on exception handling aspects.

Categories