08 exceptions and aop
TRANSCRIPT
C# Exceptions and AOP
What are Exceptions?
• An exception is any error condition or unexpected behavior encountered by an executing program.
• In the .NET Framework, an exception is an object that inherits from the Exception Class class.
• The exception is passed up the stack until the application handles it or the program terminates.
Use Exceptions or not use exceptions?
-• Вони невидимі з викликаючого коду.• Створюються непередбачувані точки виходу з метода.• Exceptions повільні. (exceptions use resources only when an exception occurs.)+ • Зручність використання.• Інформативність отриманих помилок більша по
відношенні до статус-кодів.• Принцип використання. Throw на самий верхній рівень.• Більш елегантні архітектурні рішення та зменшення
часу розробки.
C# Exception handling• try…catch…finally• throw• Catch as high as you can• try{ }
catch(Exception1){ /*exception1 handler*/ }catch(Exception2) { /*exception2 handler*/ }catch(Exception) { /*exception handler*/ }
Attributes
• Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth).
Aspect Oriented Programming
• Logging• Data validating• Security mechanism• …
Validation sample (AOP sample)
public class User{
[StringLengthValidator(1, 255, MessageTemplate = "Login cannot be empty.")] public string Login { get; set; } [StringLengthValidator(1, 127, MessageTemplate = "Domain cannot be empty.")]
public string Domain { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[StringLengthValidator(1, 50, MessageTemplate = "Email cannot be empty.")] public string Email { get; set; }
}
Custom attributes
- Creating [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class LoggingRequiredAttribute : Attribute { }
- Usages public class UserService { [LoggingRequired] public static void CreateUser() { //Note: logic here }
public static void EditUser() { //Note: logic here } }
Reflections
Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime.