08 exceptions and aop

9
C# Exceptions and AOP

Upload: eleksdev

Post on 10-May-2015

704 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: 08  Exceptions and AOP

C# Exceptions and AOP

Page 2: 08  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.

Page 3: 08  Exceptions and AOP

Use Exceptions or not use exceptions?

-• Вони невидимі з викликаючого коду.• Створюються непередбачувані точки виходу з метода.• Exceptions повільні. (exceptions use resources only when an exception occurs.)+ • Зручність використання.• Інформативність отриманих помилок більша по

відношенні до статус-кодів.• Принцип використання. Throw на самий верхній рівень.• Більш елегантні архітектурні рішення та зменшення

часу розробки.

Page 4: 08  Exceptions and AOP

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*/ }

Page 5: 08  Exceptions and AOP

Attributes

• Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth).

Page 6: 08  Exceptions and AOP

Aspect Oriented Programming

• Logging• Data validating• Security mechanism• …

Page 7: 08  Exceptions and AOP

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; }

}

Page 8: 08  Exceptions and AOP

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 } }

Page 9: 08  Exceptions and AOP

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.