Skip to content

Commit

Permalink
Hot Reload (#7)
Browse files Browse the repository at this point in the history
<!-- Provide a general summary of your changes in the Title above -->
<!-- Apply the label "bug" or "enhancement" as applicable. -->

## Description / Motivation
<!-- Describe your changes in detail -->
<!-- Why is this change required? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here. -->

- Changes using .env.template instead of .env directly to prevent
accidents with checking in code and no permanent "local changes"
- Adds hot reload capability to head container
- Fixes NuGet warnings by introducing package source mapping and removed
deprecated v2
- Adds "Not Found" example support
- Adds missing "Error" view and action
- Adds PR template
- Removes `AddSystemTextJson` to ensure proper (de)serialization

## Terms
<!-- Place an X in the [] to check. -->

<!-- The Code of Conduct helps create a safe space for everyone. We
require that everyone agrees to it. -->
- [X] I agree to follow this project's [Code of
Conduct](CODE_OF_CONDUCT.md).

---------

Co-authored-by: Ivan Lieckens <[email protected]>
  • Loading branch information
sc-ivanlieckens and IvanLieckens authored Sep 3, 2024
1 parent 55775cf commit 9ee5314
Show file tree
Hide file tree
Showing 14 changed files with 99 additions and 49 deletions.
4 changes: 3 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# folders
.git
.github
.gitignore
.vs
.config
Expand All @@ -18,4 +19,5 @@ docker-compose*
*.ps1
**/*.yml
**/*.module.json
sitecore.json
sitecore.json
xmcloud.build.json
14 changes: 14 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!-- Provide a general summary of your changes in the Title above -->
<!-- Apply the label "bug" or "enhancement" as applicable. -->

## Description / Motivation
<!-- Describe your changes in detail -->
<!-- Why is this change required? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here. -->


## Terms
<!-- Place an X in the [] to check. -->

<!-- The Code of Conduct helps create a safe space for everyone. We require that everyone agrees to it. -->
- [ ] I agree to follow this project's [Code of Conduct](CODE_OF_CONDUCT.md).
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@
*.itempackage
*.sicpackage

# IDE Settings
.vscode

#Ignore thumbnails created by Windows
Thumbs.db

#Ignore files built by Visual Studio
*.obj
*.exe
Expand Down
31 changes: 22 additions & 9 deletions headapps/aspnet-core-starter/Controllers/DefaultController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,51 @@ namespace Sitecore.AspNetCore.Starter.Controllers;

public class DefaultController : Controller
{
private SitecoreSettings? settings;
private readonly ILogger<DefaultController> logger;
private readonly SitecoreSettings? _settings;
private readonly ILogger<DefaultController> _logger;

public DefaultController(ILogger<DefaultController> logger, IConfiguration configuration)
{
settings = configuration.GetSection(SitecoreSettings.Key).Get<SitecoreSettings>();
ArgumentNullException.ThrowIfNull(settings);
this.logger = logger;
_settings = configuration.GetSection(SitecoreSettings.Key).Get<SitecoreSettings>();
ArgumentNullException.ThrowIfNull(_settings);
_logger = logger;
}

[UseSitecoreRendering]
public IActionResult Index(Layout model)
{
var request = HttpContext.GetSitecoreRenderingContext();
IActionResult result = Empty;
ISitecoreRenderingContext? request = HttpContext.GetSitecoreRenderingContext();
if ((request?.Response?.HasErrors ?? false) && !IsPageEditingRequest(request))
{
foreach (SitecoreLayoutServiceClientException error in request.Response.Errors)
{
switch (error)
{
case ItemNotFoundSitecoreLayoutServiceClientException:
result = View("NotFound");
break;
default:
logger.LogError(error, error.Message);
_logger.LogError(error, "{Message}", error.Message);
throw error;
}
}
}
else
{
result = View(model);
}

return View(model);
return result;
}

public IActionResult Error()
{
return View();
}

private bool IsPageEditingRequest(ISitecoreRenderingContext request)
{
return request.Controller?.HttpContext.Request.Path == (settings?.EditingPath ?? string.Empty);
return request.Controller?.HttpContext.Request.Path == (_settings?.EditingPath ?? string.Empty);
}
}
13 changes: 6 additions & 7 deletions headapps/aspnet-core-starter/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@
using Sitecore.AspNetCore.Starter.Extensions;
using System.Globalization;

var builder = WebApplication.CreateBuilder(args);
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

var sitecoreSettings = builder.Configuration.GetSection(SitecoreSettings.Key).Get<SitecoreSettings>();
SitecoreSettings? sitecoreSettings = builder.Configuration.GetSection(SitecoreSettings.Key).Get<SitecoreSettings>();
ArgumentNullException.ThrowIfNull(sitecoreSettings);

builder.Services.AddRouting()
.AddLocalization()
.AddMvc();

builder.Services.AddSitecoreLayoutService()
.AddSystemTextJson()
.AddGraphQlHandler("default", sitecoreSettings.DefaultSiteName!, sitecoreSettings.ExperienceEdgeToken!, sitecoreSettings.LayoutServiceUri!)
.AsDefaultHandler();

Expand All @@ -24,7 +23,7 @@
.ForwardHeaders()
.WithExperienceEditor(options => { options.JssEditingSecret = sitecoreSettings.EditingSecret ?? string.Empty; });

var app = builder.Build();
WebApplication app = builder.Build();

if (!app.Environment.IsDevelopment())
{
Expand All @@ -44,12 +43,12 @@
app.UseRouting();
app.UseStaticFiles();

var DefaultLanguage = "en";
const string defaultLanguage = "en";
app.UseRequestLocalization(options =>
{
// If you add languages in Sitecore which this site / Rendering Host should support, add them here.
List<CultureInfo> supportedCultures = [new CultureInfo(DefaultLanguage)];
options.DefaultRequestCulture = new RequestCulture(DefaultLanguage, DefaultLanguage);
List<CultureInfo> supportedCultures = [new CultureInfo(defaultLanguage)];
options.DefaultRequestCulture = new RequestCulture(defaultLanguage, defaultLanguage);
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.UseSitecoreRequestLocalization();
Expand Down
1 change: 1 addition & 0 deletions headapps/aspnet-core-starter/Views/Default/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Error</h1>
1 change: 1 addition & 0 deletions headapps/aspnet-core-starter/Views/Default/NotFound.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Page not found</h1>
4 changes: 2 additions & 2 deletions headapps/aspnet-core-starter/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
@model Layout
@model Layout?

<!DOCTYPE html>
<html lang="en">
<head>
<title>@Model.DisplayName</title>
<title>@Model?.DisplayName</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<link rel="stylesheet" href="/styles/bootstrap-5.1.3.min.css">
Expand Down
File renamed without changes.
2 changes: 2 additions & 0 deletions local-containers/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Dangerous file, never commit
.env
12 changes: 9 additions & 3 deletions local-containers/docker-compose.override.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@ services:
context: ../
dockerfile: ./local-containers/docker/build/aspnet-core-starter/Dockerfile
args:
BUILD_IMAGE: ${NETCORE_BUILD_IMAGE}-${EXTERNAL_IMAGE_TAG_SUFFIX}
RUNTIME_IMAGE: ${NETCORE_RUNTIME_IMAGE}-${EXTERNAL_IMAGE_TAG_SUFFIX}
ENTRYPOINT_ASSEMBLY: aspnet-core-starter.dll
BASE_IMAGE: ${NETCORE_BUILD_IMAGE}-${EXTERNAL_IMAGE_TAG_SUFFIX}
PROJECT_FILE: ./headapps/aspnet-core-starter/aspnet-core-starter.csproj
environment:
ASPNETCORE_ENVIRONMENT: "Development"
ASPNETCORE_URLS: "http://*:80"
DOTNET_WATCH_RESTART_ON_RUDE_EDIT: true
DOTNET_WATCH_SUPPRESS_LAUNCH_BROWSER: true
MVP_RENDERING_EDITING_HOST_URI: "http://aspnet-core-starter"
Sitecore__InstanceUri: "http://cm"
Sitecore__LayoutServicePath: "/sitecore/api/graph/edge/"
Expand All @@ -44,6 +45,11 @@ services:
Sitecore__DefaultSiteName: ${SITE_NAME}
ports:
- "80:80"
command: ["dotnet", "watch", "run", -v, "--urls", "http://*:80"]
volumes:
- .\..\headapps\aspnet-core-starter:c:\app
- c:\app\obj
- c:\app\bin
depends_on:
- cm
labels:
Expand Down
26 changes: 9 additions & 17 deletions local-containers/docker/build/aspnet-core-starter/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
ARG BUILD_IMAGE
ARG RUNTIME_IMAGE

FROM ${BUILD_IMAGE} AS build
WORKDIR /source
ARG BASE_IMAGE
FROM ${BASE_IMAGE}
ARG PROJECT_FILE
WORKDIR /app

COPY ./headapps ./
COPY ./nuget.config ./
RUN dotnet restore
RUN dotnet publish -c Debug -o /app --no-restore
COPY ${PROJECT_FILE} .
COPY ./headapps/Directory.Packages.props ./../
COPY ./nuget.config ./../

FROM ${RUNTIME_IMAGE}
ARG ENTRYPOINT_ASSEMBLY
ENV ENTRYPOINT_ASSEMBLY="${ENTRYPOINT_ASSEMBLY}"
COPY ./headapps/aspnet-core-starter ./

WORKDIR /app
COPY --from=build /app ./
EXPOSE 80
EXPOSE 443
ENTRYPOINT dotnet %ENTRYPOINT_ASSEMBLY%
CMD ["dotnet", "watch", "run", -v, "--urls", "http://*:80"]
26 changes: 17 additions & 9 deletions local-containers/scripts/init.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[CmdletBinding(DefaultParameterSetName = "no-arguments")]
Param (
[Parameter(HelpMessage = "Enables initialization of values in the .env file, which may be placed in source control.",
[Parameter(HelpMessage = "Enables initialization of values in the .env file.",
ParameterSetName = "env-init")]
[switch]$InitEnv,

Expand Down Expand Up @@ -64,6 +64,14 @@ Write-Host "Importing SitecoreDockerTools..." -ForegroundColor Green
Import-Module SitecoreDockerTools -RequiredVersion $dockerToolsVersion
Write-SitecoreDockerWelcome

##################
# Create .env file
##################
if ($InitEnv) {
Write-Host "Creating .env file." -ForegroundColor Green
Copy-Item "..\.env.template" "..\.env" -Force
}

##################################
# Configure TLS/HTTPS certificates
##################################
Expand Down Expand Up @@ -111,24 +119,24 @@ Add-HostsEntry "www.aspnetcore-starter.localhost"
################################
# Generate Sitecore Api Key
################################

$sitecoreApiKey = (New-Guid).Guid
Set-EnvFileVariable "SITECORE_API_KEY_ASPNETCORE_STARTER" -Value $sitecoreApiKey -Path $envFileLocation
if ($InitEnv) {
$sitecoreApiKey = (New-Guid).Guid
Set-EnvFileVariable "SITECORE_API_KEY_ASPNETCORE_STARTER" -Value $sitecoreApiKey -Path $envFileLocation
}

################################
# Generate EDITING_SECRET
################################
$editingSecret = Get-SitecoreRandomString 64 -DisallowSpecial
Set-EnvFileVariable "EDITING_SECRET" -Value $editingSecret -Path $envFileLocation
if ($InitEnv) {
$editingSecret = Get-SitecoreRandomString 64 -DisallowSpecial
Set-EnvFileVariable "EDITING_SECRET" -Value $editingSecret -Path $envFileLocation
}

###############################
# Populate the environment file
###############################

if ($InitEnv) {



Write-Host "Populating required .env file values..." -ForegroundColor Green

# HOST_LICENSE_FOLDER
Expand Down
10 changes: 9 additions & 1 deletion nuget.config
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,18 @@
<clear />
<add key="Nuget" value="https://api.nuget.org/v3/index.json" />
<add key="Sitecore" value="https://nuget.sitecore.com/resources/v3/index.json" />
<add key="SitecoreGallery" value="https://nuget.sitecore.com/resources/v2/" />
</packageSources>

<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>

<packageSourceMapping>
<packageSource key="Nuget">
<package pattern="*" />
</packageSource>
<packageSource key="Sitecore">
<package pattern="Sitecore.*" />
</packageSource>
</packageSourceMapping>
</configuration>

0 comments on commit 9ee5314

Please sign in to comment.