SlideShare a Scribd company logo
1 of 23
Connection Resiliency & Command 
Interception
Connection Resiliency
Problem 
• Applications connecting to a database server have always been vulnerable to 
connection breaks due to back-end failures and network instability. 
• However, in a LAN based environment working against dedicated database 
servers these errors are rare enough that extra logic to handle those failures is 
not often required.
Cause of Problem 
• With the rise of cloud based database servers such as Windows Azure SQL 
Database and connections over less reliable networks it is now more common for 
connection breaks to occur. 
• This could be due to defensive techniques that cloud databases use to ensure 
fairness of service, such as connection throttling, or to instability in the network 
causing intermittent timeouts and other transient errors.
Connection Resiliency / Retry Logic in EF 
• Connection Resiliency refers to the ability for EF to automatically retry any 
commands that fail due to these connection breaks.
Why Connection Resiliency and Command 
Interception? 
• Two features of Entity Framework 6 that are especially valuable when you are 
deploying to the cloud environment: 
• connection resiliency (automatic retries for transient errors) and 
• command interception (catch all SQL queries sent to the database in order to log or change 
them).
Configuring Connection Resiliency Features 
The connection resiliency feature must be configured appropriately for a particular 
database service: 
• It has to know which exceptions are likely to be transient. You want to retry 
errors caused by a temporary loss in network connectivity, not errors caused by 
program bugs, for example. 
• It has to wait an appropriate amount of time between retries of a failed 
operation. You can wait longer between retries for a batch process than you can 
for an online web page where a user is waiting for a response. 
• It has to retry an appropriate number of times before it gives up. You might want 
to retry more times in a batch process that you would in an online application.
Execution Strategies in EF 
• Connection retry is taken care of by an implementation of the 
IDbExecutionStrategy interface. Implementations of the IDbExecutionStrategy 
will be responsible for accepting an operation and, if an exception occurs, 
determining if a retry is appropriate and retrying if it is. 
• There are four execution strategies that ship with EF: 
• DefaultExecutionStrategy 
• DefaultSqlExecutionStrategy 
• DbExecutionStrategy 
• SqlAzureExecutionStrategy
Execution Strategies in EF (Contd.) 
• DefaultExecutionStrategy: this execution strategy does not retry any operations, it is the 
default for databases other than SQL server. 
• DefaultSqlExecutionStrategy: this is an internal execution strategy that is used by 
default. This strategy does not retry at all, however, it will wrap any exceptions that could 
be transient to inform users that they might want to enable connection resiliency. 
• DbExecutionStrategy: this class is suitable as a base class for other execution strategies, 
including your own custom ones. It implements an exponential retry policy, where the 
initial retry happens with zero delay and the delay increases exponentially until the 
maximum retry count is hit. This class has an abstract ShouldRetryOn method that can be 
implemented in derived execution strategies to control which exceptions should be 
retried. 
• SqlAzureExecutionStrategy: this execution strategy inherits from DbExecutionStrategy 
and will retry on exceptions that are known to be possibly transient when working with 
SqlAzure.
Configuring Execution Strategy in EF 
• This code tells EF to use the SqlAzureExecutionStrategy when connecting to SQL 
Server.
REFERENCES 
• http://msdn.microsoft.com/en-us/data/dn456835.aspx 
• http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/connection-resiliency- 
and-command-interception-with-the-entity-framework-in-an-asp-net-mvc- 
application 
• http://channel9.msdn.com/Events/Visual-Studio/Launch-2013/LB104 
• http://entityframework.codeplex.com/wikipage?title=Connection%20Resiliency% 
20Spec 
• http://www.codeproject.com/Tips/758469/Implementing-Connection-Resiliency-with- 
Entity-Fra
Command Interception
Command Interception in EF 
• The high-level goal for the interception feature is to allow external code to 
observe and potentially intercept EF operations. 
• Anytime Entity Framework sends a command to the database this command can 
be intercepted by application code.
Usage of Command Interception 
• This is most commonly used for logging SQL, but can also be used to modify or 
abort the command.
Interception interface 
• The interception code is built around the concept of interception interfaces. 
• EF 6 provides the ability to intercept the context using IDbCommandInterceptor, 
before and after it performs the ExecuteNonQuery, ExecuteScalar and 
ExecuteReader operations to the database.
Interception interface (Contd.)
Interception Context 
• The object DbInterceptionContext contains contextual information 
about the action that EF is taking. 
• For example, if the action is being taken on behalf of a DbContext, 
then the DbContext is included in the DbInterceptionContext. 
Similarly, for commands that are being executed asynchronously, the 
IsAsync flag is set on DbCommandInterceptionContext.
Interception Result handling 
• The DbCommandInterceptionContext class contains four properties 
• Result 
• OriginalResult 
• Exception 
• OriginalException. 
• If the operation is executed and succeeds, then Result and OriginalResult are set 
to the result of the operation. Likewise, if the operation throws, then the 
Exception and OriginalException properties will be set.
Interception Suppressing execution 
• If an interceptor sets the Result property before the command has executed (in 
one of the …Executing methods) then EF will not attempt to actually execute the 
command, but will instead just use the result set and continue as if the command 
had been executed. 
• Execution can also be suppressed by setting the Exception property in one of the 
…Executing methods. This causes EF to continue as if execution of the operation 
had failed by throwing the given exception. 
• For example, this could be used in test environments to test the behavior of an 
application when command execution fails.
Interception: Changing the result after 
execution 
• If an interceptor sets the Result property after the command has executed (in 
one of the …Executed methods) then EF will use the changed result instead of the 
result that was actually returned from the operation. 
• Similarly, if an interceptor sets the Exception property after the command has 
executed, then EF will throw the set exception as if the operation had thrown the 
exception.
Interception: OriginalResult and 
OriginalException 
• The OriginalResult and OriginalException properties are 
• read-only 
• only set by EF 
• These properties cannot be set by interceptors. This means that any interceptor 
can distinguish between an exception or result that has been set by some other 
interceptor as opposed to the real exception or result that occurred when the 
operation was executed.
Configuring Interceptor
REFERENCES 
• http://msdn.microsoft.com/en-us/data/dn469464 
• http://www.entityframeworktutorial.net/EntityFramework6/database 
-command-interception.aspx 
• http://entityframework.codeplex.com/wikipage?title=Interception

More Related Content

What's hot

Process improvement techniques
Process improvement techniquesProcess improvement techniques
Process improvement techniquesHakeem-Ur- Rehman
 
Lean Six Sigma 101
Lean Six Sigma 101Lean Six Sigma 101
Lean Six Sigma 101shailsood
 
A comprehensive guide to SAP PLM 7.01
A comprehensive guide to SAP PLM 7.01A comprehensive guide to SAP PLM 7.01
A comprehensive guide to SAP PLM 7.01Shobhit Singhal
 
Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...
Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...
Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...Sulaman Muhammad
 
SuccessFactors Application Management Services
SuccessFactors Application Management ServicesSuccessFactors Application Management Services
SuccessFactors Application Management ServicesNGA Human Resources
 
Customer Development Syllabus
Customer Development SyllabusCustomer Development Syllabus
Customer Development SyllabusVenture Hacks
 
SCP Six Sigma presentation 6.30.2010
SCP Six Sigma presentation 6.30.2010SCP Six Sigma presentation 6.30.2010
SCP Six Sigma presentation 6.30.2010The Hackett Group
 
Preventive maintenance kpi
Preventive maintenance kpiPreventive maintenance kpi
Preventive maintenance kpisagophane
 

What's hot (11)

Six Sigma
Six SigmaSix Sigma
Six Sigma
 
Sap architecture
Sap architectureSap architecture
Sap architecture
 
Process improvement techniques
Process improvement techniquesProcess improvement techniques
Process improvement techniques
 
Lean Six Sigma 101
Lean Six Sigma 101Lean Six Sigma 101
Lean Six Sigma 101
 
Six Sigma
Six SigmaSix Sigma
Six Sigma
 
A comprehensive guide to SAP PLM 7.01
A comprehensive guide to SAP PLM 7.01A comprehensive guide to SAP PLM 7.01
A comprehensive guide to SAP PLM 7.01
 
Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...
Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...
Quality Improvement Of Fan Manufacturing Industry By Using Basic Seven Tools ...
 
SuccessFactors Application Management Services
SuccessFactors Application Management ServicesSuccessFactors Application Management Services
SuccessFactors Application Management Services
 
Customer Development Syllabus
Customer Development SyllabusCustomer Development Syllabus
Customer Development Syllabus
 
SCP Six Sigma presentation 6.30.2010
SCP Six Sigma presentation 6.30.2010SCP Six Sigma presentation 6.30.2010
SCP Six Sigma presentation 6.30.2010
 
Preventive maintenance kpi
Preventive maintenance kpiPreventive maintenance kpi
Preventive maintenance kpi
 

Similar to Connection Resiliency and Command Interception in Entity Framework

Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with EpsilonSina Madani
 
Performance tuning Grails Applications GR8Conf US 2014
Performance tuning Grails Applications GR8Conf US 2014Performance tuning Grails Applications GR8Conf US 2014
Performance tuning Grails Applications GR8Conf US 2014Lari Hotari
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready AppsVMware Tanzu
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Derek Ashmore
 
Building a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable FunctionsBuilding a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable FunctionsJoonas Westlin
 
Summer internship report
Summer internship reportSummer internship report
Summer internship reportIpsit Pradhan
 
Fault tolerant presentation
Fault tolerant presentationFault tolerant presentation
Fault tolerant presentationskadyan1
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?satejsahu
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Parallel Computing
Parallel ComputingParallel Computing
Parallel ComputingMohsin Bhat
 
Distributed Performance testing by funkload
Distributed Performance testing by funkloadDistributed Performance testing by funkload
Distributed Performance testing by funkloadAkhil Singh
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Real World Java Compatibility
Real World Java CompatibilityReal World Java Compatibility
Real World Java CompatibilityTim Ellison
 
Cqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For DevelopersCqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For Developerswojtek_s
 

Similar to Connection Resiliency and Command Interception in Entity Framework (20)

Advanced python
Advanced pythonAdvanced python
Advanced python
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with Epsilon
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
Performance tuning Grails Applications GR8Conf US 2014
Performance tuning Grails Applications GR8Conf US 2014Performance tuning Grails Applications GR8Conf US 2014
Performance tuning Grails Applications GR8Conf US 2014
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready Apps
 
Circuit Breaker.pptx
Circuit Breaker.pptxCircuit Breaker.pptx
Circuit Breaker.pptx
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
Building a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable FunctionsBuilding a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable Functions
 
Summer internship report
Summer internship reportSummer internship report
Summer internship report
 
Struts Interceptors
Struts InterceptorsStruts Interceptors
Struts Interceptors
 
Fault tolerant presentation
Fault tolerant presentationFault tolerant presentation
Fault tolerant presentation
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Parallel Computing
Parallel ComputingParallel Computing
Parallel Computing
 
Distributed Performance testing by funkload
Distributed Performance testing by funkloadDistributed Performance testing by funkload
Distributed Performance testing by funkload
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Real World Java Compatibility
Real World Java CompatibilityReal World Java Compatibility
Real World Java Compatibility
 
Cqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For DevelopersCqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For Developers
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Recently uploaded (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Connection Resiliency and Command Interception in Entity Framework

  • 1. Connection Resiliency & Command Interception
  • 3. Problem • Applications connecting to a database server have always been vulnerable to connection breaks due to back-end failures and network instability. • However, in a LAN based environment working against dedicated database servers these errors are rare enough that extra logic to handle those failures is not often required.
  • 4. Cause of Problem • With the rise of cloud based database servers such as Windows Azure SQL Database and connections over less reliable networks it is now more common for connection breaks to occur. • This could be due to defensive techniques that cloud databases use to ensure fairness of service, such as connection throttling, or to instability in the network causing intermittent timeouts and other transient errors.
  • 5. Connection Resiliency / Retry Logic in EF • Connection Resiliency refers to the ability for EF to automatically retry any commands that fail due to these connection breaks.
  • 6. Why Connection Resiliency and Command Interception? • Two features of Entity Framework 6 that are especially valuable when you are deploying to the cloud environment: • connection resiliency (automatic retries for transient errors) and • command interception (catch all SQL queries sent to the database in order to log or change them).
  • 7. Configuring Connection Resiliency Features The connection resiliency feature must be configured appropriately for a particular database service: • It has to know which exceptions are likely to be transient. You want to retry errors caused by a temporary loss in network connectivity, not errors caused by program bugs, for example. • It has to wait an appropriate amount of time between retries of a failed operation. You can wait longer between retries for a batch process than you can for an online web page where a user is waiting for a response. • It has to retry an appropriate number of times before it gives up. You might want to retry more times in a batch process that you would in an online application.
  • 8. Execution Strategies in EF • Connection retry is taken care of by an implementation of the IDbExecutionStrategy interface. Implementations of the IDbExecutionStrategy will be responsible for accepting an operation and, if an exception occurs, determining if a retry is appropriate and retrying if it is. • There are four execution strategies that ship with EF: • DefaultExecutionStrategy • DefaultSqlExecutionStrategy • DbExecutionStrategy • SqlAzureExecutionStrategy
  • 9. Execution Strategies in EF (Contd.) • DefaultExecutionStrategy: this execution strategy does not retry any operations, it is the default for databases other than SQL server. • DefaultSqlExecutionStrategy: this is an internal execution strategy that is used by default. This strategy does not retry at all, however, it will wrap any exceptions that could be transient to inform users that they might want to enable connection resiliency. • DbExecutionStrategy: this class is suitable as a base class for other execution strategies, including your own custom ones. It implements an exponential retry policy, where the initial retry happens with zero delay and the delay increases exponentially until the maximum retry count is hit. This class has an abstract ShouldRetryOn method that can be implemented in derived execution strategies to control which exceptions should be retried. • SqlAzureExecutionStrategy: this execution strategy inherits from DbExecutionStrategy and will retry on exceptions that are known to be possibly transient when working with SqlAzure.
  • 10. Configuring Execution Strategy in EF • This code tells EF to use the SqlAzureExecutionStrategy when connecting to SQL Server.
  • 11. REFERENCES • http://msdn.microsoft.com/en-us/data/dn456835.aspx • http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/connection-resiliency- and-command-interception-with-the-entity-framework-in-an-asp-net-mvc- application • http://channel9.msdn.com/Events/Visual-Studio/Launch-2013/LB104 • http://entityframework.codeplex.com/wikipage?title=Connection%20Resiliency% 20Spec • http://www.codeproject.com/Tips/758469/Implementing-Connection-Resiliency-with- Entity-Fra
  • 13. Command Interception in EF • The high-level goal for the interception feature is to allow external code to observe and potentially intercept EF operations. • Anytime Entity Framework sends a command to the database this command can be intercepted by application code.
  • 14. Usage of Command Interception • This is most commonly used for logging SQL, but can also be used to modify or abort the command.
  • 15. Interception interface • The interception code is built around the concept of interception interfaces. • EF 6 provides the ability to intercept the context using IDbCommandInterceptor, before and after it performs the ExecuteNonQuery, ExecuteScalar and ExecuteReader operations to the database.
  • 17. Interception Context • The object DbInterceptionContext contains contextual information about the action that EF is taking. • For example, if the action is being taken on behalf of a DbContext, then the DbContext is included in the DbInterceptionContext. Similarly, for commands that are being executed asynchronously, the IsAsync flag is set on DbCommandInterceptionContext.
  • 18. Interception Result handling • The DbCommandInterceptionContext class contains four properties • Result • OriginalResult • Exception • OriginalException. • If the operation is executed and succeeds, then Result and OriginalResult are set to the result of the operation. Likewise, if the operation throws, then the Exception and OriginalException properties will be set.
  • 19. Interception Suppressing execution • If an interceptor sets the Result property before the command has executed (in one of the …Executing methods) then EF will not attempt to actually execute the command, but will instead just use the result set and continue as if the command had been executed. • Execution can also be suppressed by setting the Exception property in one of the …Executing methods. This causes EF to continue as if execution of the operation had failed by throwing the given exception. • For example, this could be used in test environments to test the behavior of an application when command execution fails.
  • 20. Interception: Changing the result after execution • If an interceptor sets the Result property after the command has executed (in one of the …Executed methods) then EF will use the changed result instead of the result that was actually returned from the operation. • Similarly, if an interceptor sets the Exception property after the command has executed, then EF will throw the set exception as if the operation had thrown the exception.
  • 21. Interception: OriginalResult and OriginalException • The OriginalResult and OriginalException properties are • read-only • only set by EF • These properties cannot be set by interceptors. This means that any interceptor can distinguish between an exception or result that has been set by some other interceptor as opposed to the real exception or result that occurred when the operation was executed.
  • 23. REFERENCES • http://msdn.microsoft.com/en-us/data/dn469464 • http://www.entityframeworktutorial.net/EntityFramework6/database -command-interception.aspx • http://entityframework.codeplex.com/wikipage?title=Interception