Skip to content

Commit

Permalink
Switched to in-memory Db for a more real-word scenario
Browse files Browse the repository at this point in the history
  • Loading branch information
EdCharbeneau committed Jan 10, 2020
1 parent 3f919ab commit 156fdd7
Show file tree
Hide file tree
Showing 8 changed files with 188 additions and 16 deletions.
2 changes: 1 addition & 1 deletion BlazorPro.Spinkit.sln
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CsbSample", "samples\CsbSam
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorPro.Spinkit.Tests", "tests\BlazorPro.Spinkit.Tests\BlazorPro.Spinkit.Tests.csproj", "{C90B6DB7-516A-4051-9029-E4CC4CC5575A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SsbSample", "samples\SsbSample\SsbSample.csproj", "{545B7476-5A55-40A7-9EC5-E93D9475655F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SsbSample", "samples\SsbSample\SsbSample.csproj", "{545B7476-5A55-40A7-9EC5-E93D9475655F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
18 changes: 18 additions & 0 deletions samples/SsbSample/Data/WeatherDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SsbSample.Data
{
public class WeatherDbContext : DbContext
{
public WeatherDbContext() { }
public WeatherDbContext(DbContextOptions<WeatherDbContext> options)
: base(options) { }

public DbSet<WeatherForecast> WeatherForecasts { get; set; }

}
}
1 change: 1 addition & 0 deletions samples/SsbSample/Data/WeatherForecast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace SsbSample.Data
{
public class WeatherForecast
{
public int Id { get; set; }
public DateTime Date { get; set; }

public int TemperatureC { get; set; }
Expand Down
21 changes: 9 additions & 12 deletions samples/SsbSample/Data/WeatherForecastService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
Expand All @@ -6,21 +7,17 @@ namespace SsbSample.Data
{
public class WeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly WeatherDbContext dbContext;
public WeatherForecastService(WeatherDbContext dbContext) => this.dbContext = dbContext;

public async Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
{
await Task.Delay(3000);
var rng = new Random();
return await Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray());
return await dbContext.WeatherForecasts.ToArrayAsync();
}

public WeatherForecast[] GetForecast(DateTime startDate)
{
return dbContext.WeatherForecasts.ToArray();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@page "/fetchdata"
@page "/fetchdata2"
@using SsbSample.Data
@inject WeatherForecastService WeatherService

Expand Down
124 changes: 124 additions & 0 deletions samples/SsbSample/Pages/FetchDataSync.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
@page "/fetchdata"
@using SsbSample.Data
@inject WeatherForecastService WeatherService

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>
<p>
The &lt;SpinLoader&gt; component supports three template regions:
<ul>
<li>LoadingTemplate (optional) - content to display while the IsLoading property is <b>true</b>.</li>
<li>ContentTemplate - content to display when the IsLoading is <b>false</b></li>
<li>FaultedTemplate - content to display when IsFaulted is <b>true</b> and IsLoading is <b>false</b></li>
</ul>
</p>
<div class="form-row align-items-center">
<div class="col-auto">
<div class="form-check mb-2">
<input id="forceException" type="checkbox" @bind="forceException" class="form-check-input" />
<label class="form-check-label" for="forceException">Force exception</label>
</div>
</div>
<div class="col-auto">
<button class="btn btn-primary mb-2" @onclick="LoadData">Retry</button>
</div>
</div>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
<SpinLoader IsLoading="isLoading" IsFaulted="isFaulted">
<LoadingTemplate>
<tr>
<td colspan="4" style="vertical-align: middle;background-color: rgb(0, 0, 0, .2); height:300px;">
<Circle Color="#e67e22" Size="60px" Center="true" />
</td>
</tr>
</LoadingTemplate>
<ContentTemplate>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</ContentTemplate>
<FaultedContentTemplate>
<tr>
<td colspan="4">
<div class="alert alert-danger">Fail</div>
</td>
</tr>
</FaultedContentTemplate>
</SpinLoader>
</tbody>
</table>

@code {

WeatherForecast[] forecasts;
bool isFaulted = false;
bool isLoading = true;
int delay = 2000;
bool forceException = false;

protected override async Task OnInitializedAsync()
{
await LoadData();
}

async Task LoadData()
{
await TryLoadingData(
onSuccess: SuccessPath,
onFaulted: FaultedPath
);
}

void SuccessPath(WeatherForecast[] data)
{
// do work
forecasts = data;
}

void FaultedPath(Exception e)
{
// log message, don't share it with the user
var fakeLog = e.Message;
}

async Task TryLoadingData(Action<WeatherForecast[]> onSuccess, Action<Exception> onFaulted)
{
isLoading = true;
try
{
if (forceException)
{
throw new NotSupportedException();
}
var data = await Task.Run(() => WeatherService.GetForecast(DateTime.Now));
isFaulted = false;
onSuccess(data);
}
catch (Exception e)
{
isFaulted = true;
onFaulted(e);
}
finally
{
isLoading = false;
}
}

}
4 changes: 4 additions & 0 deletions samples/SsbSample/SsbSample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\BlazorPro.Spinkit\BlazorPro.Spinkit.csproj" />
</ItemGroup>
Expand Down
32 changes: 30 additions & 2 deletions samples/SsbSample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand All @@ -28,12 +29,39 @@ public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddScoped<WeatherForecastService>();
services.AddDbContext<WeatherDbContext>(opt =>
opt.UseInMemoryDatabase(databaseName: "SampleData")
);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
/* Inject the service provider */ IServiceProvider serviceProvider)
{
string[] summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var o = new DbContextOptionsBuilder<WeatherDbContext>().UseInMemoryDatabase(databaseName: "SampleData");

//Resolve and use the service
using (var dbContext = serviceProvider.GetService<WeatherDbContext>())
{
dbContext.Database.EnsureCreated();
var rng = new Random();

dbContext.WeatherForecasts.AddRange(
Enumerable.Range(1, 30000).Select(index => new WeatherForecast
{
Id = index,
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = summaries[rng.Next(summaries.Length)]
}));
dbContext.SaveChanges();
}

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand Down

0 comments on commit 156fdd7

Please sign in to comment.