Skip to content

Commit

Permalink
Merge pull request Azure-Samples#36 from Azure-Samples/addcache
Browse files Browse the repository at this point in the history
Addcache
  • Loading branch information
cephalin authored May 24, 2023
2 parents 3655d08 + ec69903 commit ea91fc1
Show file tree
Hide file tree
Showing 79 changed files with 53,758 additions and 18,949 deletions.
File renamed without changes.
24 changes: 24 additions & 0 deletions DotNetCoreSqlDb/ActionTimerFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DotNetCoreSqlDb
{
public class ActionTimerFilterAttribute : ActionFilterAttribute
{
readonly Stopwatch _stopwatch = new Stopwatch();

public override void OnActionExecuting(ActionExecutingContext context) => _stopwatch.Start();

public override void OnActionExecuted(ActionExecutedContext context)
{
_stopwatch.Stop();
if (context.Result is ViewResult)
{
((ViewResult)context.Result).ViewData["TimeElapsed"] = _stopwatch.Elapsed;
}
_stopwatch.Reset();
}
}
}
13 changes: 0 additions & 13 deletions DotNetCoreSqlDb/CHANGELOG.md

This file was deleted.

15 changes: 9 additions & 6 deletions DotNetCoreSqlDb/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DotNetCoreSqlDb.Models;

namespace DotNetCoreSqlDb.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult Index()
{
return View();
Expand All @@ -26,4 +29,4 @@ public IActionResult Error()
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
}
71 changes: 56 additions & 15 deletions DotNetCoreSqlDb/Controllers/TodosController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,42 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DotNetCoreSqlDb;
using DotNetCoreSqlDb.Data;
using DotNetCoreSqlDb.Models;
using Microsoft.Extensions.Caching.Distributed;

namespace DotNetCoreSqlDb.Controllers
{
[ActionTimerFilter]
public class TodosController : Controller
{
private readonly MyDatabaseContext _context;
private readonly IDistributedCache _cache;
private readonly string _TodoItemsCacheKey = "TodoItemsList";

public TodosController(MyDatabaseContext context)
public TodosController(MyDatabaseContext context, IDistributedCache cache)
{
_context = context;
_cache = cache;
}

// GET: Todos
public async Task<IActionResult> Index()
{
var todos = new List<Todo>();
byte[]? TodoListByteArray;

// This allows the home page to load if migrations have not been run yet.
try
{
todos = await _context.Todo.ToListAsync();
TodoListByteArray = await _cache.GetAsync(_TodoItemsCacheKey);
if (TodoListByteArray != null && TodoListByteArray.Length > 0)
{
todos = ConvertData<Todo>.ByteArrayToObjectList(TodoListByteArray);
}
catch (Exception e)
else
{

return View(todos);
todos = await _context.Todo.ToListAsync();
TodoListByteArray = ConvertData<Todo>.ObjectListToByteArray(todos);
await _cache.SetAsync(_TodoItemsCacheKey, TodoListByteArray);
}

return View(todos);
Expand All @@ -40,18 +49,35 @@ public async Task<IActionResult> Index()
// GET: Todos/Details/5
public async Task<IActionResult> Details(int? id)
{
byte[]? todoItemByteArray;
Todo? todo;

if (id == null)
{
return NotFound();
}

var todo = await _context.Todo
todoItemByteArray = await _cache.GetAsync(GetTodoItemCacheKey(id));

if (todoItemByteArray != null && todoItemByteArray.Length > 0)
{
todo = ConvertData<Todo>.ByteArrayToObject(todoItemByteArray);
}
else
{
todo = await _context.Todo
.FirstOrDefaultAsync(m => m.ID == id);
if (todo == null)
{
return NotFound();
}

todoItemByteArray = ConvertData<Todo>.ObjectToByteArray(todo);
await _cache.SetAsync(GetTodoItemCacheKey(id), todoItemByteArray);
}



return View(todo);
}

Expand All @@ -62,8 +88,8 @@ public IActionResult Create()
}

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

// POST: Todos/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Description,CreatedDate")] Todo todo)
Expand All @@ -111,6 +138,8 @@ public async Task<IActionResult> Edit(int id, [Bind("ID,Description,CreatedDate"
{
_context.Update(todo);
await _context.SaveChangesAsync();
await _cache.RemoveAsync(GetTodoItemCacheKey(todo.ID));
await _cache.RemoveAsync(_TodoItemsCacheKey);
}
catch (DbUpdateConcurrencyException)
{
Expand Down Expand Up @@ -152,14 +181,26 @@ public async Task<IActionResult> Delete(int? id)
public async Task<IActionResult> DeleteConfirmed(int id)
{
var todo = await _context.Todo.FindAsync(id);
_context.Todo.Remove(todo);
await _context.SaveChangesAsync();
if (todo != null)
{
_context.Todo.Remove(todo);
await _context.SaveChangesAsync();
await _cache.RemoveAsync(GetTodoItemCacheKey(todo.ID));
await _cache.RemoveAsync(_TodoItemsCacheKey);
}
return RedirectToAction(nameof(Index));
}

private bool TodoExists(int id)
{
return _context.Todo.Any(e => e.ID == id);
}

private string GetTodoItemCacheKey(int? id)
{
return _TodoItemsCacheKey+"_&_"+id;
}
}


}
43 changes: 43 additions & 0 deletions DotNetCoreSqlDb/Data/ConvertData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Collections.Generic;
using System.Text.Json;

namespace DotNetCoreSqlDb.Data
{
public static class ConvertData<T>
{
public static List<T> ByteArrayToObjectList(byte[] inputByteArray)
{
var deserializedList = JsonSerializer.Deserialize<List<T>>(inputByteArray);
if(deserializedList == null)
{
throw new Exception();
}
return deserializedList;
}

public static byte[] ObjectListToByteArray(List<T> inputList)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(inputList);

return bytes;
}

public static T ByteArrayToObject(byte[] inputByteArray)
{
var deserializedList = JsonSerializer.Deserialize<T>(inputByteArray);
if (deserializedList == null)
{
throw new Exception();
}
return deserializedList;
}

public static byte[] ObjectToByteArray(T input)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(input);

return bytes;
}

}
}
5 changes: 3 additions & 2 deletions DotNetCoreSqlDb/Data/MyDatabaseContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using DotNetCoreSqlDb.Models;

namespace DotNetCoreSqlDb.Models
namespace DotNetCoreSqlDb.Data
{
public class MyDatabaseContext : DbContext
{
Expand All @@ -13,6 +14,6 @@ public MyDatabaseContext (DbContextOptions<MyDatabaseContext> options)
{
}

public DbSet<DotNetCoreSqlDb.Models.Todo> Todo { get; set; }
public DbSet<DotNetCoreSqlDb.Models.Todo> Todo { get; set; } = default!;
}
}
16 changes: 9 additions & 7 deletions DotNetCoreSqlDb/DotNetCoreSqlDb.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>


<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="7.0.5" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="7.0.5" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" />
</ItemGroup>

</Project>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@

namespace DotNetCoreSqlDb.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
Expand All @@ -24,6 +26,7 @@ protected override void Up(MigrationBuilder migrationBuilder)
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
Expand Down
Loading

0 comments on commit ea91fc1

Please sign in to comment.