Skip to content

Commit 4fda318

Browse files
committed
Introduced AsyncHelper (#128)
1 parent 6a56955 commit 4fda318

File tree

8 files changed

+66
-32
lines changed

8 files changed

+66
-32
lines changed

samples/MusicStore/MusicStore.Web/Models/SampleData.cs

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,34 +17,33 @@ public static class SampleData
1717
const string defaultAdminUserName = "DefaultAdminUserName";
1818
const string defaultAdminPassword = "DefaultAdminPassword";
1919

20-
public static async Task InitializeMusicStoreDatabaseAsync(IServiceProvider serviceProvider, bool createUsers = true)
20+
public static void InitializeMusicStoreDatabase(IServiceProvider serviceProvider, bool createUsers = true)
2121
{
2222
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
2323
{
2424
var db = serviceScope.ServiceProvider.GetService<MusicStoreContext>();
2525

26-
if (await db.Database.EnsureCreatedAsync())
26+
if (db.Database.EnsureCreated())
2727
{
28-
await InsertTestData(serviceProvider);
28+
InsertTestData(serviceProvider);
2929
if (createUsers)
3030
{
31-
await CreateAdminUser(serviceProvider);
31+
CreateAdminUser(serviceProvider);
3232
}
3333
}
3434
}
3535
}
3636

37-
private static async Task InsertTestData(IServiceProvider serviceProvider)
37+
private static void InsertTestData(IServiceProvider serviceProvider)
3838
{
3939
var albums = GetAlbums(imgUrl, Genres, Artists);
4040

41-
await AddOrUpdateAsync(serviceProvider, g => g.GenreId, Genres.Select(genre => genre.Value));
42-
await AddOrUpdateAsync(serviceProvider, a => a.ArtistId, Artists.Select(artist => artist.Value));
43-
await AddOrUpdateAsync(serviceProvider, a => a.AlbumId, albums);
41+
AddOrUpdateAsync(serviceProvider, g => g.GenreId, Genres.Select(genre => genre.Value));
42+
AddOrUpdateAsync(serviceProvider, a => a.ArtistId, Artists.Select(artist => artist.Value));
43+
AddOrUpdateAsync(serviceProvider, a => a.AlbumId, albums);
4444
}
45-
46-
// TODO [EF] This may be replaced by a first class mechanism in EF
47-
private static async Task AddOrUpdateAsync<TEntity>(
45+
46+
private static void AddOrUpdateAsync<TEntity>(
4847
IServiceProvider serviceProvider,
4948
Func<TEntity, object> propertyToMatch, IEnumerable<TEntity> entities)
5049
where TEntity : class
@@ -67,7 +66,7 @@ private static async Task AddOrUpdateAsync<TEntity>(
6766
: EntityState.Added;
6867
}
6968

70-
await db.SaveChangesAsync();
69+
db.SaveChanges();
7170
}
7271
}
7372

@@ -76,7 +75,7 @@ private static async Task AddOrUpdateAsync<TEntity>(
7675
/// </summary>
7776
/// <param name="serviceProvider"></param>
7877
/// <returns></returns>
79-
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
78+
private static void CreateAdminUser(IServiceProvider serviceProvider)
8079
{
8180
var env = serviceProvider.GetService<IHostingEnvironment>();
8281

@@ -96,13 +95,13 @@ private static async Task CreateAdminUser(IServiceProvider serviceProvider)
9695
// await roleManager.CreateAsync(new IdentityRole(adminRole));
9796
//}
9897

99-
var user = await userManager.FindByNameAsync(configuration[defaultAdminUserName]);
98+
var user = userManager.FindByNameAsync(configuration[defaultAdminUserName]).GetAwaiter().GetResult();
10099
if (user == null)
101100
{
102101
user = new ApplicationUser { UserName = configuration[defaultAdminUserName] };
103-
await userManager.CreateAsync(user, configuration[defaultAdminPassword]);
102+
userManager.CreateAsync(user, configuration[defaultAdminPassword]).GetAwaiter().GetResult();
104103
//await userManager.AddToRoleAsync(user, adminRole);
105-
await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
104+
userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed")).GetAwaiter().GetResult();
106105
}
107106

108107
#if TESTING
@@ -112,10 +111,10 @@ private static async Task CreateAdminUser(IServiceProvider serviceProvider)
112111
for (int i = 0; i < 100; ++i)
113112
{
114113
var email = string.Format("User{0:D3}@example.com", i);
115-
var normalUser = await userManager.FindByEmailAsync(email);
114+
var normalUser = userManager.FindByEmailAsync(email).GetAwaiter().GetResult();
116115
if (normalUser == null)
117116
{
118-
await userManager.CreateAsync(new ApplicationUser { UserName = email, Email = email }, "Password~!1");
117+
userManager.CreateAsync(new ApplicationUser { UserName = email, Email = email }, "Password~!1").GetAwaiter().GetResult();
119118
}
120119
}
121120
}

samples/MusicStore/MusicStore.Web/StartupNtlmAuthentication.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
144144
});
145145

146146
//Populates the MusicStore sample data
147-
Task.Run(async () => await SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices, false)).Wait();
147+
SampleData.InitializeMusicStoreDatabase(app.ApplicationServices, false);
148148
}
149149
}
150150
}

samples/MusicStore/MusicStore.Web/StartupOpenIdConnect.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
152152
});
153153

154154
//Populates the MusicStore sample data
155-
Task.Run(async () => await SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices)).Wait();
155+
SampleData.InitializeMusicStoreDatabase(app.ApplicationServices, false);
156156
}
157157
}
158158
}

src/MyTested.AspNetCore.Mvc.Core/Builders/Actions/VoidActionResultTestBuilder.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ public IBaseTestBuilderWithInvokedAction ShouldReturnEmpty()
3232
/// <inheritdoc />
3333
public IShouldHaveTestBuilder<VoidActionResult> ShouldHave()
3434
{
35-
this.TestContext.ActionResult = VoidActionResult.Instance;
3635
return new ShouldHaveTestBuilder<VoidActionResult>(this.TestContext);
3736
}
3837

src/MyTested.AspNetCore.Mvc.Core/Builders/Controllers/ControllerActionCallBuilder.cs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using Microsoft.Extensions.DependencyInjection;
1515
using Utilities;
1616
using Utilities.Extensions;
17+
using Internal;
1718

1819
/// <content>
1920
/// Used for building the controller which will be tested.
@@ -45,11 +46,11 @@ public IActionResultTestBuilder<TActionResult> Calling<TActionResult>(Expression
4546

4647
try
4748
{
48-
actionResult = Task.Run(async () => await actionInfo.ActionResult).Result;
49+
actionResult = AsyncHelper.RunSync(() => actionInfo.ActionResult);
4950
}
50-
catch (AggregateException aggregateException)
51+
catch (Exception exception)
5152
{
52-
actionInfo.CaughtException = aggregateException;
53+
actionInfo.CaughtException = new AggregateException(exception);
5354
}
5455

5556
this.TestContext.Apply(actionInfo);
@@ -76,6 +77,7 @@ public IVoidActionResultTestBuilder Calling(Expression<Action<TController>> acti
7677
this.TestContext.ActionName = actionName;
7778
this.TestContext.ActionCall = actionCall;
7879
this.TestContext.CaughtException = caughtException;
80+
this.TestContext.ActionResult = VoidActionResult.Instance;
7981

8082
return new VoidActionResultTestBuilder(this.TestContext);
8183
}
@@ -87,14 +89,15 @@ public IVoidActionResultTestBuilder Calling(Expression<Func<TController, Task>>
8789

8890
try
8991
{
90-
Task.Run(async () => await actionInfo.ActionResult).Wait();
92+
AsyncHelper.RunSync(() => actionInfo.ActionResult);
9193
}
92-
catch (AggregateException aggregateException)
94+
catch (Exception exception)
9395
{
94-
actionInfo.CaughtException = aggregateException;
96+
actionInfo.CaughtException = new AggregateException(exception);
9597
}
9698

9799
this.TestContext.Apply(actionInfo);
100+
this.TestContext.ActionResult = VoidActionResult.Instance;
98101

99102
return new VoidActionResultTestBuilder(this.TestContext);
100103
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
namespace MyTested.AspNetCore.Mvc.Internal
2+
{
3+
using System;
4+
using System.Threading;
5+
using System.Threading.Tasks;
6+
7+
public class AsyncHelper
8+
{
9+
private static readonly TaskFactory taskFactory = new TaskFactory(
10+
CancellationToken.None,
11+
TaskCreationOptions.None,
12+
TaskContinuationOptions.None,
13+
TaskScheduler.Default);
14+
15+
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
16+
{
17+
return taskFactory
18+
.StartNew(func)
19+
.Unwrap()
20+
.GetAwaiter()
21+
.GetResult();
22+
}
23+
24+
public static void RunSync(Func<Task> func)
25+
{
26+
taskFactory
27+
.StartNew(func)
28+
.Unwrap()
29+
.GetAwaiter()
30+
.GetResult();
31+
}
32+
}
33+
}

src/MyTested.AspNetCore.Mvc.Core/Internal/Formatters/FormattersHelper.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public static TModel ReadFromStream<TModel>(Stream stream, string contentType, E
5454
return formatter;
5555
});
5656

57-
var result = Task.Run(async () => await inputFormatter.ReadAsync(inputFormatterContext)).Result.Model;
57+
var result = AsyncHelper.RunSync(() => inputFormatter.ReadAsync(inputFormatterContext)).Model;
5858

5959
try
6060
{
@@ -91,7 +91,7 @@ public static Stream WriteToStream<TBody>(TBody value, string contentType, Encod
9191
return formatter;
9292
});
9393

94-
Task.Run(async () => await outputFormatter.WriteAsync(outputFormatterCanWriteContext)).Wait();
94+
AsyncHelper.RunSync(() => outputFormatter.WriteAsync(outputFormatterCanWriteContext));
9595

9696
// copy memory stream because formatters close the original one
9797
return new MemoryStream(((MemoryStream)httpContext.Response.Body).ToArray());

src/MyTested.AspNetCore.Mvc.Core/Internal/Routes/InternalRouteResolver.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public static ResolvedRouteContext Resolve(IServiceProvider services, IRouter ro
8383

8484
try
8585
{
86-
Task.Run(async() => await modelBindingActionInvoker.InvokeAsync()).Wait();
86+
AsyncHelper.RunSync(() => modelBindingActionInvoker.InvokeAsync());
8787
}
8888
catch (Exception ex)
8989
{
@@ -116,8 +116,8 @@ public static RouteData ResolveRouteData(IRouter router, RouteContext routeConte
116116
{
117117
return null;
118118
}
119-
120-
Task.Run(async () => await router.RouteAsync(routeContext)).Wait();
119+
120+
AsyncHelper.RunSync(() => router.RouteAsync(routeContext));
121121

122122
var routeData = routeContext.RouteData;
123123
routeContext.HttpContext.SetRouteData(routeData);

0 commit comments

Comments
 (0)