Caching Data in ASP.NET MVC

Slides:



Advertisements
Similar presentations
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
Advertisements

Microsoft ASP.NET: An Overview of Caching. 2 Overview  Introduction to ASP.NET caching  Output caching  Data caching  Difference between Data Caching.
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Caching Chapter 12. Caching For high-performance apps Caching: storing frequently-used items in memory –Accessed more quickly Cached Web Form bypasses:
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Controls, Widgets, Grid…
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Session, TempData, Cache Andres Käver, IT Kolledž
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
XML Processing SoftUni Team Database Applications Technical Trainers
Version Control Systems
Auto Mapping Objects SoftUni Team Database Applications
Static Members and Namespaces
Introduction to Entity framework
Databases basics Course Introduction SoftUni Team Databases basics
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
C# Database Fundamentals with Microsoft SQL Server
Build a WordPress Site A Real Life Example: Create a Fully Functional WP Business Web Site from Scratch Building a WP Site SoftUni Team Technical Trainers.
Introduction to Entity Framework
ASP.NET Integration Testing
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
C# Databases Advanced with Microsoft SQL Server
EF Relations Object Composition
Entity Framework: Code First
Parsing XML XDocument and LINQ
Data Definition and Data Types
Databases advanced Course Introduction SoftUni Team Databases advanced
MVC Architecture. Routing
Install and configure theme
Entity Framework: Relations
The Right Way Control Flow
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
Transactions in Entity Framework
ASP.NET MVC Introduction
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Best Practices and Architecture
Best practices and architecture
WordPress Plugins Popular WP Plugins: Sliders, Forms, Contacts, SEO, Forum, Photo Gallery, e-Commerce WordPress Plugins SoftUni Team Technical Trainers.
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
Exporting and Importing Data
ASP.NET Filters SoftUni Team ASP.NET MVC Introduction
Making big SPA applications
Manual Mapping and AutoMapper Library
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Introduction to TypeScript & Angular
CSS Transitions and Animations
Train the Trainers Course
Software Quality Assurance
Version Control Systems
JavaScript Frameworks & AngularJS
Lean .NET stack for building modern web apps
CSS Transitions and Animations
MIS Professor Sandvig MIS 424 Professor Sandvig
Presentation transcript:

Caching Data in ASP.NET MVC Output Cache and Data Cache ASP.NET MVC SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents What is Caching and How It Works? OutputCache in ASP.NET Client and Server Caching Configuring the Caching Partial Page Caching Custom Data Caching Using HtpContext.Cache

What is Caching and How It Works? Caching Data to Boost Performance

What is Caching? Caching data == storing data in RAM or disk so future requests for that data can be served faster The data stored in the cache is the result of an earlier computation Where do we use caching? CPU caches pieces of computer memory for faster processing Hard disks cache data blocks to speed up disk operations Databases cache data tables to speed up queries Web browsers cache static resources like images

How the Cache Works in Web Apps? Web Browser Web Server Database HDD Browser Cache Server Cache DB Cache HDD Cache

Caching: Benefits and Costs Benefits of caching Improved performance Speed – reduced response time and page load time Efficiency – reduced infrastructure usage CPU time, database utilization, network bandwidth Costs of caching Staleness (out-of-date) Need to check and refresh data

Caching the Output of an Action OutputCache in ASP.NET Caching the Output of an Action

No Cache – Example public class TimeController : Controller { public ActionResult Index() return View(); } @{ ViewBag.Title = "Caching Demo"; } <h2>The time is @DateTime.Now</h2>

Caching for 10 Seconds – Example public class TimeController : Controller { [OutputCache(Duration = 10, VaryByParam = "none")] public ActionResult Index() return View(); }

VaryByParam – Example public class TimeController : Controller { [OutputCache(Duration = 3600, VaryByParam = "id")] public ActionResult IndexByParam() return View(); } @{ ViewBag.Title = "VaryByParam"; } <h2>The time is @DateTime.Now</h2>

Cache Location Any (default) – the content is cached in three locations: the web server, any proxy servers, and the Web browser Client – content is cached on the Web browser Server – content is cached on the Web server ServerAndClient – cached at the Web server + Web browser Downstream – cached on the Web server + proxy servers None – not cached anywhere

Cache Location Explained Value Cache-Control header Expires header? Cached on the server? Any public Yes Client private No Downstream Server no-cache None

Cache Location – Example public class TimeController : Controller { [OutputCache(Duration=3600, VaryByParam="none", Location=OutputCacheLocation.Client)] public ActionResult ClientCache() return View(); } @{ ViewBag.Title = "Client Cache"; } <h2>The time is @DateTime.Now</h2>

[Crtl+F5] / [Ctrl+Refresh] Browsers and Cache Click on a link  loads the content again No HTTP request for client-cached resources [F5] / [Refresh]  requests the resource with the If- Modified-Since header [F5] / [Refresh]  requests the resource with no cache [Crtl+F5] / [Ctrl+Refresh]

Invalidate the OutputCache Invalidate (remove) the cache for certain controller action Only possible for server-side caching! [OutputCache(Duration=3600, Location=OutputCacheLocation.Server)] public ActionResult ServerCache() { return View(); } public ActionResult ClearServerCache() { var urlToRemove = Url.Action("ServerCache", "Time"); Response.RemoveOutputCacheItem(urlToRemove); return RedirectToAction("ServerCache"); }

Cache Profiles in Web.config <system.web> <caching> <outputCacheSettings> <outputCacheProfiles> <add name="Profile15Sec" duration="15" varyByParam="none" location="Any" /> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web> [OutputCache(CacheProfile = "Profile15Sec")] public ActionResult Profile15Sec() { return View(); }

Caching only a Part of Your Page Partial Page Caching Caching only a Part of Your Page

Partial Page Caching Most pages consist of many pieces (divs / widgets) E.g. header, footer, sidebar, news section, other widgets … To boost performance Cache the widgets that are rarely updated Instead of caching the entire page Example – a discussion forum Cache the header, footer, top posts, top users, etc. Do not cache the questions / answers / comments

Partial Page Caching in ASP.NET MVC TimeController.cs ViewWithPartial.cshtml public ActionResult ViewWithPartial() { return View(); } [OutputCache(Duration = 10)] [ChildActionOnly] public PartialViewResult PartialView() { return PartialView("_PartialView"); } @{ ViewBag.Title = "View with Partial"; } <h2>Main view: @DateTime.Now</h2> @Html.Action("PartialView") _PartialView.cshtml <h3>I am a partial view and my time is @DateTime.Now</h3>

Using the Cache Object in ASP.NET CUSTOM CUSTOM Custom Data Caching Using the Cache Object in ASP.NET

Data Caching in ASP.NET You have a Cache object out of the box It keeps cached data Expires by a certain configuration Can also be invalidated manually public ActionResult DataCache() { if (this.HttpContext.Cache["time"] == null) this.HttpContext.Cache["time"] = DateTime.Now; } this.ViewBag.Time = this.HttpContext.Cache["time"]; return View();

Manually Invalidate the Data Cache Items can be removed from the data cache: Or can be scheduled for automatic removal (expiration): public ActionResult InvalidateCache() { this.HttpContext.Cache.Remove("time"); return this.RedirectToAction("DataCache"); } this.HttpContext.Cache.Insert("time", DateTime.Now, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));

Configuring the Data Cache Expiration Example of setting cache entry parameters: if (this.HttpContext.Cache["time"] == null) { this.HttpContext.Cache.Insert( "time", // key DateTime.Now, // value null, // cache dependencies DateTime.Now.AddSeconds(10), // absolute expiration TimeSpan.Zero, // sliding expiration CacheItemPriority.Default, // priority null); // callback delegate }

Cache Dependencies Cache dependencies can ensure that data is not stale Cache entry can be flushed when: A file changes A directory changes Another cache entry is removed Something in the database changes E.g. SQL Server cache dependencies

Cache Dependencies – Example public class FilesController : Controller { public ActionResult Index() if (this.HttpContext.Cache["files"] == null) var folder = Server.MapPath("~/Images"); var files = Directory.EnumerateFiles(folder); this.HttpContext.Cache.Insert("files", files, new CacheDependency(folder)); } this.ViewBag.Files = this.HttpContext.Cache["files"]; return View();

Cache Dependencies – Example (2) @{ ViewBag.Title = "List of files in '/Images' folder"; } <h2>@ViewBag.Title</h2> <ul> @foreach (var file in ViewBag.Files) { <li>@file</li> } </ul>

Summary Caching dramatically boosts performance and saves resources Client-side caching (in the Web browser) is most efficient OutputCache is ASP.NET MVC configures caching Client side (bowser) caching and server-side caching Partial page caching caches the areas of the site that change rarely Caching can be controlled manually Use HttpContext.Cache object

Caching Data in ASP.NET MVC https://softuni.bg/trainings/1230/asp-net-mvc-october-2015

SoftUni Diamond Partners

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "ASP.NET MVC" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.