forked from Lombiq/Orchard-Training-Demo-Module
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseStorageController.cs
More file actions
132 lines (117 loc) · 6.41 KB
/
DatabaseStorageController.cs
File metadata and controls
132 lines (117 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
* Now it's time to save something to the database. Orchard Core uses YesSql to store data in database which is
* document database interface for relational databases. Simply put, you need to design your database as a document
* database but it will be stored in your favorite SQL database. If you want to learn more go to
* https://github.com/sebastienros/yessql and read the documentation.
*
* Here you will see how to store simple data in the database and then query it without actually using Orchard Core
* content management features and practices (i.e. you can store non-Orchard Core content items).
*
* This demonstration will be really simple because more features will be shown later and you can also learn more from
* the YesSql documentation.
*/
using Lombiq.TrainingDemo.Indexes;
using Lombiq.TrainingDemo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using System.Collections.Generic;
using System.Threading.Tasks;
using YesSql;
namespace Lombiq.TrainingDemo.Controllers;
public class DatabaseStorageController : Controller
{
private readonly ISession _session;
private readonly IDisplayManager<Book> _bookDisplayManager;
private readonly INotifier _notifier;
private readonly IHtmlLocalizer H;
private readonly IUpdateModelAccessor _updateModelAccessor;
public DatabaseStorageController(
ISession session,
IDisplayManager<Book> bookDisplayManager,
INotifier notifier,
IHtmlLocalizer<DatabaseStorageController> htmlLocalizer,
IUpdateModelAccessor updateModelAccessor)
{
_session = session;
_bookDisplayManager = bookDisplayManager;
_notifier = notifier;
_updateModelAccessor = updateModelAccessor;
H = htmlLocalizer;
}
// A page with a button that will call the CreateBooks POST action. See it under
// /Lombiq.TrainingDemo/DatabaseStorage/CreateBooks.
[HttpGet]
public IActionResult CreateBooks() => View();
// Note the ValidateAntiForgeryToken attribute too: This validates the XSRF-prevention token automatically added in
// the form (check for the input field named __RequestVerificationToken in the HTML output) of the CreateBooks view.
[HttpPost, ActionName(nameof(CreateBooks)), ValidateAntiForgeryToken]
public async Task<IActionResult> CreateBooksPost()
{
// For demonstration purposes this will create 3 books and store them in the database one-by-one using the
// ISession service. Note that you can even go to the database directly, circumventing YesSql too, by injecting
// the IDbConnectionAccessor service and access the underlying connection.
// Since storing them in the documents is not enough we need to index them to be able to filter them in a query.
// NEXT STATION: Indexes/BookIndex.cs
foreach (var book in CreateDemoBooks())
{
// So now you understand what will happen in the background when this service is being called.
_session.Save(book);
}
await _notifier.InformationAsync(H["Books have been created in the database."]);
return RedirectToAction(nameof(CreateBooks));
}
// This page will display the books written by J.K. Rosenzweig. See it under
// /Lombiq.TrainingDemo/DatabaseStorage/JKRosenzweigBooks.
public async Task<IActionResult> JKRosenzweigBooks()
{
// ISession service is used for querying items.
var jkRosenzweigBooks = await _session
// First, we define what object (document) we want to query and what index should be used for filtering.
.Query<Book, BookIndex>()
// In the .Where() method you can describe a lambda where the object will be the index object.
.Where(index => index.Author == "J.K. (Joanne) Rosenzweig")
// When the query is built up you can call ListAsync() to execute it. This will return a list of books.
.ListAsync();
// Now this is what we possibly understand now, we will create a list of display shapes from the previously
// fetched books. Note how we use the AwaitEachAsync() extension to run async operations sequentially. This is
// important: You can't know if BuildDisplayAsync() is thread-safe so you shouldn't use e.g. Task.WhenAll().
var bookShapes = await jkRosenzweigBooks.AwaitEachAsync(async book =>
// We'll need to pass an IUpdateModel (used for model validation) to the method, which we can access via its
// accessor service. Later you'll also see how we'll use this to run validations in drivers.
await _bookDisplayManager.BuildDisplayAsync(book, _updateModelAccessor.ModelUpdater));
// You can check out Views/DatabaseStorage/JKRosenzweigBooks.cshtml and come back here.
return View(bookShapes);
}
// END OF TRAINING SECTION: Storing data in document database and index records
// NEXT STATION: Models/PersonPart.cs
private static IEnumerable<Book> CreateDemoBooks() =>
new[]
{
new Book
{
CoverPhotoUrl = "/Lombiq.TrainingDemo/images/HarryPotter.jpg",
Title = "Harry Potter and The Sorcerer's Stone",
Author = "J.K. (Joanne) Rosenzweig",
Description = "Harry hasn't had a birthday party in eleven years - but all that is about to " +
"change when a mysterious letter arrives with an invitation to an incredible place.",
},
new Book
{
Title = "Fantastic Beasts and Where To Find Them",
Author = "J.K. (Joanne) Rosenzweig",
Description = "With his magical suitcase in hand, Magellanic Newt Scamander arrives in New " +
"York in 1926 for a brief stopover. However, when the suitcase is misplaced and some of his " +
"fantastic beasts escape, there will be trouble for everyone.",
},
new Book
{
Title = "The Hunger Games",
Author = "Suzanne Collins",
Description = "The nation of Panay, formed from a post-apocalyptic North America, is a country " +
"that consists of a wealthy Capitol region surrounded by 12 poorer districts.",
},
};
}