Skip to content

Commit ea91fc1

Browse files
authored
Merge pull request #36 from Azure-Samples/addcache
Addcache
2 parents 3655d08 + ec69903 commit ea91fc1

File tree

79 files changed

+53758
-18949
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+53758
-18949
lines changed
File renamed without changes.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System.Diagnostics;
2+
using Microsoft.AspNetCore.Http.Extensions;
3+
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.AspNetCore.Mvc.Filters;
5+
6+
namespace DotNetCoreSqlDb
7+
{
8+
public class ActionTimerFilterAttribute : ActionFilterAttribute
9+
{
10+
readonly Stopwatch _stopwatch = new Stopwatch();
11+
12+
public override void OnActionExecuting(ActionExecutingContext context) => _stopwatch.Start();
13+
14+
public override void OnActionExecuted(ActionExecutedContext context)
15+
{
16+
_stopwatch.Stop();
17+
if (context.Result is ViewResult)
18+
{
19+
((ViewResult)context.Result).ViewData["TimeElapsed"] = _stopwatch.Elapsed;
20+
}
21+
_stopwatch.Reset();
22+
}
23+
}
24+
}

DotNetCoreSqlDb/CHANGELOG.md

Lines changed: 0 additions & 13 deletions
This file was deleted.

DotNetCoreSqlDb/Controllers/HomeController.cs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
1-
using System;
2-
using System.Collections.Generic;
1+
using Microsoft.AspNetCore.Mvc;
32
using System.Diagnostics;
4-
using System.Linq;
5-
using System.Threading.Tasks;
6-
using Microsoft.AspNetCore.Mvc;
73
using DotNetCoreSqlDb.Models;
84

95
namespace DotNetCoreSqlDb.Controllers
106
{
117
public class HomeController : Controller
128
{
9+
private readonly ILogger<HomeController> _logger;
10+
11+
public HomeController(ILogger<HomeController> logger)
12+
{
13+
_logger = logger;
14+
}
15+
1316
public IActionResult Index()
1417
{
1518
return View();
@@ -26,4 +29,4 @@ public IActionResult Error()
2629
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
2730
}
2831
}
29-
}
32+
}

DotNetCoreSqlDb/Controllers/TodosController.cs

Lines changed: 56 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,33 +5,42 @@
55
using Microsoft.AspNetCore.Mvc;
66
using Microsoft.AspNetCore.Mvc.Rendering;
77
using Microsoft.EntityFrameworkCore;
8+
using DotNetCoreSqlDb;
9+
using DotNetCoreSqlDb.Data;
810
using DotNetCoreSqlDb.Models;
11+
using Microsoft.Extensions.Caching.Distributed;
912

1013
namespace DotNetCoreSqlDb.Controllers
1114
{
15+
[ActionTimerFilter]
1216
public class TodosController : Controller
1317
{
1418
private readonly MyDatabaseContext _context;
19+
private readonly IDistributedCache _cache;
20+
private readonly string _TodoItemsCacheKey = "TodoItemsList";
1521

16-
public TodosController(MyDatabaseContext context)
22+
public TodosController(MyDatabaseContext context, IDistributedCache cache)
1723
{
1824
_context = context;
25+
_cache = cache;
1926
}
2027

2128
// GET: Todos
2229
public async Task<IActionResult> Index()
2330
{
2431
var todos = new List<Todo>();
32+
byte[]? TodoListByteArray;
2533

26-
// This allows the home page to load if migrations have not been run yet.
27-
try
28-
{
29-
todos = await _context.Todo.ToListAsync();
34+
TodoListByteArray = await _cache.GetAsync(_TodoItemsCacheKey);
35+
if (TodoListByteArray != null && TodoListByteArray.Length > 0)
36+
{
37+
todos = ConvertData<Todo>.ByteArrayToObjectList(TodoListByteArray);
3038
}
31-
catch (Exception e)
39+
else
3240
{
33-
34-
return View(todos);
41+
todos = await _context.Todo.ToListAsync();
42+
TodoListByteArray = ConvertData<Todo>.ObjectListToByteArray(todos);
43+
await _cache.SetAsync(_TodoItemsCacheKey, TodoListByteArray);
3544
}
3645

3746
return View(todos);
@@ -40,18 +49,35 @@ public async Task<IActionResult> Index()
4049
// GET: Todos/Details/5
4150
public async Task<IActionResult> Details(int? id)
4251
{
52+
byte[]? todoItemByteArray;
53+
Todo? todo;
54+
4355
if (id == null)
4456
{
4557
return NotFound();
4658
}
4759

48-
var todo = await _context.Todo
60+
todoItemByteArray = await _cache.GetAsync(GetTodoItemCacheKey(id));
61+
62+
if (todoItemByteArray != null && todoItemByteArray.Length > 0)
63+
{
64+
todo = ConvertData<Todo>.ByteArrayToObject(todoItemByteArray);
65+
}
66+
else
67+
{
68+
todo = await _context.Todo
4969
.FirstOrDefaultAsync(m => m.ID == id);
5070
if (todo == null)
5171
{
5272
return NotFound();
5373
}
5474

75+
todoItemByteArray = ConvertData<Todo>.ObjectToByteArray(todo);
76+
await _cache.SetAsync(GetTodoItemCacheKey(id), todoItemByteArray);
77+
}
78+
79+
80+
5581
return View(todo);
5682
}
5783

@@ -62,8 +88,8 @@ public IActionResult Create()
6288
}
6389

6490
// POST: Todos/Create
65-
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
66-
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
91+
// To protect from overposting attacks, enable the specific properties you want to bind to.
92+
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
6793
[HttpPost]
6894
[ValidateAntiForgeryToken]
6995
public async Task<IActionResult> Create([Bind("ID,Description,CreatedDate")] Todo todo)
@@ -72,6 +98,7 @@ public async Task<IActionResult> Create([Bind("ID,Description,CreatedDate")] Tod
7298
{
7399
_context.Add(todo);
74100
await _context.SaveChangesAsync();
101+
await _cache.RemoveAsync(_TodoItemsCacheKey);
75102
return RedirectToAction(nameof(Index));
76103
}
77104
return View(todo);
@@ -94,8 +121,8 @@ public async Task<IActionResult> Edit(int? id)
94121
}
95122

96123
// POST: Todos/Edit/5
97-
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
98-
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
124+
// To protect from overposting attacks, enable the specific properties you want to bind to.
125+
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
99126
[HttpPost]
100127
[ValidateAntiForgeryToken]
101128
public async Task<IActionResult> Edit(int id, [Bind("ID,Description,CreatedDate")] Todo todo)
@@ -111,6 +138,8 @@ public async Task<IActionResult> Edit(int id, [Bind("ID,Description,CreatedDate"
111138
{
112139
_context.Update(todo);
113140
await _context.SaveChangesAsync();
141+
await _cache.RemoveAsync(GetTodoItemCacheKey(todo.ID));
142+
await _cache.RemoveAsync(_TodoItemsCacheKey);
114143
}
115144
catch (DbUpdateConcurrencyException)
116145
{
@@ -152,14 +181,26 @@ public async Task<IActionResult> Delete(int? id)
152181
public async Task<IActionResult> DeleteConfirmed(int id)
153182
{
154183
var todo = await _context.Todo.FindAsync(id);
155-
_context.Todo.Remove(todo);
156-
await _context.SaveChangesAsync();
184+
if (todo != null)
185+
{
186+
_context.Todo.Remove(todo);
187+
await _context.SaveChangesAsync();
188+
await _cache.RemoveAsync(GetTodoItemCacheKey(todo.ID));
189+
await _cache.RemoveAsync(_TodoItemsCacheKey);
190+
}
157191
return RedirectToAction(nameof(Index));
158192
}
159193

160194
private bool TodoExists(int id)
161195
{
162196
return _context.Todo.Any(e => e.ID == id);
163197
}
198+
199+
private string GetTodoItemCacheKey(int? id)
200+
{
201+
return _TodoItemsCacheKey+"_&_"+id;
202+
}
164203
}
204+
205+
165206
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using System.Collections.Generic;
2+
using System.Text.Json;
3+
4+
namespace DotNetCoreSqlDb.Data
5+
{
6+
public static class ConvertData<T>
7+
{
8+
public static List<T> ByteArrayToObjectList(byte[] inputByteArray)
9+
{
10+
var deserializedList = JsonSerializer.Deserialize<List<T>>(inputByteArray);
11+
if(deserializedList == null)
12+
{
13+
throw new Exception();
14+
}
15+
return deserializedList;
16+
}
17+
18+
public static byte[] ObjectListToByteArray(List<T> inputList)
19+
{
20+
var bytes = JsonSerializer.SerializeToUtf8Bytes(inputList);
21+
22+
return bytes;
23+
}
24+
25+
public static T ByteArrayToObject(byte[] inputByteArray)
26+
{
27+
var deserializedList = JsonSerializer.Deserialize<T>(inputByteArray);
28+
if (deserializedList == null)
29+
{
30+
throw new Exception();
31+
}
32+
return deserializedList;
33+
}
34+
35+
public static byte[] ObjectToByteArray(T input)
36+
{
37+
var bytes = JsonSerializer.SerializeToUtf8Bytes(input);
38+
39+
return bytes;
40+
}
41+
42+
}
43+
}

DotNetCoreSqlDb/Data/MyDatabaseContext.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
using System.Linq;
44
using System.Threading.Tasks;
55
using Microsoft.EntityFrameworkCore;
6+
using DotNetCoreSqlDb.Models;
67

7-
namespace DotNetCoreSqlDb.Models
8+
namespace DotNetCoreSqlDb.Data
89
{
910
public class MyDatabaseContext : DbContext
1011
{
@@ -13,6 +14,6 @@ public MyDatabaseContext (DbContextOptions<MyDatabaseContext> options)
1314
{
1415
}
1516

16-
public DbSet<DotNetCoreSqlDb.Models.Todo> Todo { get; set; }
17+
public DbSet<DotNetCoreSqlDb.Models.Todo> Todo { get; set; } = default!;
1718
}
1819
}
Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1-
<Project Sdk="Microsoft.NET.Sdk.Web">
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>net6.0</TargetFramework>
4+
<TargetFramework>net7.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
57
</PropertyGroup>
68

7-
89
<ItemGroup>
9-
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0" />
10-
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
11-
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0">
10+
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" />
11+
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
1212
<PrivateAssets>all</PrivateAssets>
1313
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
1414
</PackageReference>
15-
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="6.0.0" />
15+
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="7.0.5" />
16+
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="7.0.5" />
17+
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" />
1618
</ItemGroup>
1719

1820
</Project>

DotNetCoreSqlDb/Migrations/20221219160330_InitialCreate.Designer.cs renamed to DotNetCoreSqlDb/Migrations/20230509140701_InitialCreate.Designer.cs

Lines changed: 6 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

DotNetCoreSqlDb/Migrations/20221219160330_InitialCreate.cs renamed to DotNetCoreSqlDb/Migrations/20230509140701_InitialCreate.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55

66
namespace DotNetCoreSqlDb.Migrations
77
{
8+
/// <inheritdoc />
89
public partial class InitialCreate : Migration
910
{
11+
/// <inheritdoc />
1012
protected override void Up(MigrationBuilder migrationBuilder)
1113
{
1214
migrationBuilder.CreateTable(
@@ -24,6 +26,7 @@ protected override void Up(MigrationBuilder migrationBuilder)
2426
});
2527
}
2628

29+
/// <inheritdoc />
2730
protected override void Down(MigrationBuilder migrationBuilder)
2831
{
2932
migrationBuilder.DropTable(

0 commit comments

Comments
 (0)