Map IReadOnlyDictionary EfCore - c#

I have an entity that has a dictionary field that uses a backing field like this.
private Dictionary<string, string> _communicationEventProperties = new Dictionary<string, string>();
public IReadOnlyDictionary<string, string> CommunicationEventProperties => new ReadOnlyDictionary<string,string>(_communicationEventProperties);
I have properly mapped it to JSON in SQL using Fluent.
However, when I try to call my entity, I get the following error.
System.InvalidCastException: Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyDictionary`2[System.String,System.String]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'
It appears as though it does not map well between the types.
I do not know why it is not mapping/how to make it map properly.
I will also attach the whole stack trace:
[InvalidCastException: Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyDictionary`2[System.String,System.String]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'.]
lambda_method(Closure , MaterializationContext ) +1237
Microsoft.EntityFrameworkCore.Query.EntityLoadInfo.Materialize() +22
Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.GetEntity(IKey key, EntityLoadInfo entityLoadInfo, Boolean queryStateManager, Boolean throwOnNullKey) +201
Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.BufferedEntityShaper`1.Shape(QueryContext queryContext, ValueBuffer& valueBuffer) +198
Microsoft.EntityFrameworkCore.Query.Internal.<BufferlessMoveNext>d__12.MoveNext() +1121
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.<ExecuteAsync>d__7`2.MoveNext() +174
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.EntityFrameworkCore.Query.Internal.<MoveNext>d__11.MoveNext() +637
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.EntityFrameworkCore.Query.Internal.<MoveNext>d__3.MoveNext() +210
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Linq.<FirstOrDefault_>d__165`1.MoveNext() in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\First.cs:144
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.EntityFrameworkCore.Query.Internal.<MoveNext>d__3.MoveNext() +243
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Linq.<MoveNextCore>d__7.MoveNext() in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Select.cs:106
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Linq.<MoveNext>d__10.MoveNext() in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\AsyncIterator.cs:109
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.EntityFrameworkCore.Query.Internal.<MoveNext>d__5.MoveNext() +634
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.EntityFrameworkCore.Query.Internal.<ExecuteSingletonAsyncQuery>d__21`1.MoveNext() +447
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +29
Metis.Communications.Core.EFCore.Interactions.EmailCommunications.GetEmailCommunicationDetails.<<-ctor>g__EmailCommunicationExists|1>d.MoveNext() in C:\Users\ethalacker\source\repos\Metis\src\Communication\Metis.Communications.Core.EFCore\Interactions\EmailCommunications\GetEmailCommunicationDetails\GetEmailCommunicationDetailsValidator.cs:25
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
FluentValidation.Validators.<ValidateAsync>d__7.MoveNext() in /home/jskinner/code/FluentValidation/src/FluentValidation/Validators/PropertyValidator.cs:65
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +26
FluentValidation.Internal.<ValidateAsync>d__66.MoveNext() in /home/jskinner/code/FluentValidation/src/FluentValidation/Internal/PropertyRule.cs:396
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
FluentValidation.<ValidateAsync>d__14.MoveNext() in /home/jskinner/code/FluentValidation/src/FluentValidation/AbstractValidator.cs:146
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.ConfiguredTaskAwaiter.GetResult() +29
Metis.SharedKernel.Interactions.<IsValid>d__10.MoveNext() in C:\Users\ethalacker\source\repos\Metis\src\Shared\Metis.SharedKernel\Interactions\InteractionHandler.cs:77
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +29
Metis.SharedKernel.Interactions.<Handle>d__8.MoveNext() in C:\Users\ethalacker\source\repos\Metis\src\Shared\Metis.SharedKernel\Interactions\InteractionHandler.cs:41
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
MediatR.Pipeline.<Handle>d__2.MoveNext() +260
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
MediatR.Pipeline.<Handle>d__2.MoveNext() +733
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +29
Metis.Web.Pages.SiteConfiguration.Communications.EmailCommunications.EmailCommunicationDetails.<Page>d__3.MoveNext() in C:\Users\ethalacker\source\repos\Metis\src\Metis.Web\Pages\SiteConfiguration\Communications\EmailCommunications\EmailCommunicationDetails\EmailCommunicationDetailsController.cs:38
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +58
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.<>c__DisplayClass7_0.<InvokeEndHandler>b__0() +30
System.Web.StepInvoker.Invoke(Action executionStep) +100
System.Web.<>c__DisplayClass4_0.<Invoke>b__0() +17
Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule.OnExecuteRequestStep(HttpContextBase context, Action step) +64
System.Web.<>c__DisplayClass284_0.<OnExecuteRequestStep>b__0(Action nextStepAction) +54
System.Web.StepInvoker.Invoke(Action executionStep) +84
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +113
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +126

I had to create a special json converter and comparer. While doing the IReadOnlyDictionary, the same could be applied to IReadOnlyList. The class will take the type of the property and then try to deserialize it into the field type. I have hard coded special cases for IReadOnlyDictionary and IReadOnlyList. But it can also take in a type through an overload (HasJsonConversionWithSerializationType).
I also added some other examples for other use cases.
My Class Properties
private Dictionary<string, string> _communicationEventProperties = new Dictionary<string, string>();
public IReadOnlyDictionary<string, string> CommunicationEventProperties => new ReadOnlyDictionary<string,string>(_communicationEventProperties);
private List<TokenValue> _tokenValues = new List<TokenValue>();
public IReadOnlyList<TokenValue> TokenValues => _tokenValues.AsReadOnly();
private List<string> _cCAddresses = new List<string>();
public IReadOnlyList<string> CCAddresses => _cCAddresses.AsReadOnly();
public class TokenValue
{
public string Key { get; }
public string Value { get; }
public TokenValue(string key, string value)
{
// using Dawn. Else you can use a normal "?? throw new ArgumentNullException"
Key = Guard.Argument(key, nameof(Key)).NotNull().NotEmpty().MaxLength(250);
Value = value;
}
}
Config file
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Application.EFCore.Configurations
{
public class MyEntityConfiguration : IEntityTypeConfiguration<MyEntity>
{
public void Configure(EntityTypeBuilder<MyEntity> builder)
{
...
builder.Property(b => b.CommunicationEventProperties)
.HasJsonConversion();
builder.Property(b => b.TokenValues)
.HasJsonConversion();
builder.Property(b => b.CCAddresses)
.HasJsonConversion();
...
}
}
}
Json Conversion Class
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class BuilderExtensions
{
public static PropertyBuilder<TProperty> HasJsonConversion<TProperty>(this PropertyBuilder<TProperty> propertyBuilder) where TProperty : class
{
var serializationType = GetSerializationTypeByConvention<TProperty>();
return HasJsonConversionWithSerializationType(propertyBuilder, serializationType);
}
public static PropertyBuilder<TProperty> HasJsonConversionWithSerializationType<TProperty, TSerialization>(this PropertyBuilder<TProperty> propertyBuilder)
where TProperty : class
where TSerialization : TProperty
=> HasJsonConversionWithSerializationType(propertyBuilder, typeof(TSerialization));
public static PropertyBuilder<TProperty> HasJsonConversionWithSerializationType<TProperty>(this PropertyBuilder<TProperty> propertyBuilder, Type serializationType) where TProperty : class
{
Guard.Argument(serializationType, nameof(serializationType)).NotNull().Require(t => typeof(TProperty).IsAssignableFrom(t), t => $"Must be able to assign {nameof(serializationType)} '{t.FullName}' to <{nameof(TProperty)}> '{typeof(TProperty).FullName}'");
var converter = MakeConverter<TProperty>(serializationType);
var comparer = MakeComparer<TProperty>(serializationType);
propertyBuilder.HasConversion(converter);
propertyBuilder.Metadata.SetValueConverter(converter);
propertyBuilder.Metadata.SetValueComparer(comparer);
return propertyBuilder;
}
private static Type GetSerializationTypeByConvention<TProperty>() where TProperty : class
{
var typeIsReadOnlyDictionary = typeof(TProperty).IsGenericType && typeof(TProperty).GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>);
if (typeIsReadOnlyDictionary) return typeof(Dictionary<,>).MakeGenericType(typeof(TProperty).GetGenericArguments());
var typeIsReadOnlyList = typeof(TProperty).IsGenericType && typeof(TProperty).GetGenericTypeDefinition() == typeof(IReadOnlyList<>);
if (typeIsReadOnlyList) return typeof(List<>).MakeGenericType(typeof(TProperty).GetGenericArguments());
return typeof(TProperty);
}
private static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer<TProperty> MakeComparer<TProperty>(Type serializationType)
=> new Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer<TProperty>(
(l, r) => Serialize(l) == Serialize(r),
v => v == null ? 0 : Serialize(v).GetHashCode(),
v => Deserialize<TProperty>(Serialize(v), serializationType));
private static ValueConverter<TProperty, string> MakeConverter<TProperty>(Type serializationType)
=> new ValueConverter<TProperty, string>(
v => Serialize(v),
v => Deserialize<TProperty>(v, serializationType));
private static TProperty Deserialize<TProperty>(string v, Type serializationType)
{
if (v == null) return default;
return (TProperty)JsonConvert.DeserializeObject(v, serializationType);
}
private static string Serialize<TProperty>(TProperty v)
=> JsonConvert.SerializeObject(v
, Formatting.None
, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
}

Related

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream. (Entity Framework)

All of a sudden I've encountered an issue with the error 'The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.' I have looked at similar posts, but can't find a solution for me.
I suspect this is due to an issue with DB changes made using Entity Framework. Locally I made the changes using Code-First which worked fine. However, when posting to production I need to manually run the scripts for any required changes and that's worked many times before. I have managed to replicate the issue locally. I have shown below where the error is coming from and the relevant stack trace. Any suggestions?
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
[InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.]
System.IO.Compression.GZipDecoder.ReadHeader(InputBuffer input) +782
System.IO.Compression.Inflater.Decode() +158
System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length) +140
System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count) +89
System.Xml.XmlTextReaderImpl.InitStreamInput(Uri baseUri, String baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding) +295
System.Xml.XmlTextReaderImpl.FinishInitStream() +65
System.Xml.XmlReaderSettings.CreateReader(Stream input, Uri baseUri, String baseUriString, XmlParserContext inputContext) +118
System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options) +110
System.Data.Entity.Migrations.Edm.ModelCompressor.Decompress(Byte[] bytes) +110
System.Data.Entity.Migrations.History.HistoryRepository.GetLastModel(String& migrationId, String& productVersion, String contextKey) +1207
System.Data.Entity.Internal.InternalContext.QueryForModel(DatabaseExistenceState existenceState) +50
System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +74
System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +71
System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +155
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +75
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +482
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +177
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +272
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +38
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +69
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +21
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +66
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken) +209
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable`1 source, Expression`1 predicate) +172
Microsoft.AspNet.Identity.EntityFramework.<GetUserAggregateAsync>d__6c.MoveNext() +498
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +43
Microsoft.AspNet.Identity.Owin.<PasswordSignInAsync>d__29.MoveNext() +372
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +31
AngliaWeb.Controllers.<Login>d__11.MoveNext() in D:\Code\Anglia\AngliaWeb\AngliaWeb\Controllers\AccountController.cs:79
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +92
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +396
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +188
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +32
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +46
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +651
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +220
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +134
I managed to fix this issue by deleting every record from the MigrationHistory table.

"The remote name could not be resolved" error when calling a Web Service in ASP.NET MVC, but a virtually identical unit test succeeds

I am receiving a System.Net.WebException with the message "The remote name could not be resolved" when trying to do a call to a Web Service with HttpClient in ASP.NET MVC. Bafflingly enough, I have a console application and accompanying unit test that has virtually identical code that works perfectly.
Here's the factory method that creates the HttpClient:
public HttpClient GetHttpClient(bool acceptVersion = true, string acceptType = #"application/json")
{
// This line was required to make this run without exception for
// my unit test
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string key = "key"; // Obviously, abbreviated
var client = new HttpClient();
if (acceptVersion)
{
client.DefaultRequestHeaders.Add("Accept-version", "beta");
}
client.DefaultRequestHeaders.Add("AccessToken", key);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptType) { CharSet = "utf-8" });
client.BaseAddress = new Uri("API uri"); // Obviously, edited
return client;
}
My factory method is literally line-for-line identical for my working unit test.
Here's the ASP.NET code:
public static async Task<double> PercentOfUsersCurrentlyActive()
{
string json;
using (var client = (new ConnectionFactory()).GetHttpClient(false))
{
// The exception occurs on this line
HttpResponseMessage message = await client.GetAsync("users");
json = await message.Content.ReadAsStringAsync();
}
UserCollection collection = JsonConvert.DeserializeObject<UserCollection>(json);
int numActive = collection.content.Count(usr => usr.active);
double average = (double)((double)numActive / (double)collection.content.Count);
return average;
}
And my controller:
public class UserController : AsyncController
{
// GET: User
public async Task<ActionResult> Index()
{
// I get the exception on here
double user = await Reports.General_Classes.User.GetActiveUsers();
return View(user);
}
}
My stack trace is:
[WebException: The remote name could not be resolved: '...']
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) +606
System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) +64
[HttpRequestException: An error occurred while sending the request.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
Reports.General_Classes.<GetActiveUsers>d__36.MoveNext() in ...\User.cs:49
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Report_Retriever.Controllers.<Index>d__0.MoveNext() in ...\UserController.cs:17
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
And here's the working code from my DLL and unit test:
[TestMethod]
public async Task GetActiveUserTests()
{
double percent = await User.GetActiveUsers();
Assert.IsTrue(percent >= 0 && percent <= 1);
}
And here's the GetActiveUsers method from my console application DLL (which is essentially identical to the method I'm using above):
public static async Task<double> GetActiveUsers()
{
string json;
using (var client = UtilityMethods.GetHttpClient(false))
{
HttpResponseMessage message = await client.GetAsync("users");
json = await message.Content.ReadAsStringAsync();
}
UserCollection collection = JsonConvert.DeserializeObject<UserCollection>(json);
int numActive = collection.content.Count(usr => usr.active);
double average = (double)((double)numActive / (double)collection.content.Count);
return average;
}
As part of my research, I read the following Stack Overflow posts:
ASP.NET Exception: The remote name could not be resolved: 'apiconnector.com'
System.Net.WebException: The remote name could not be resolved:
In both of those cases, they could access the remote location from a browser but not programmatically. My case is somewhat different, though: I can perform calls against the API from a unit test, but not from an ASP.NET MVC application.
In this post, the original poster was able to access this locally but not from a server. Again, though, this doesn't exactly apply to my case because both are running locally within Visual Studio.
The result is the same no matter how many times I run them - i.e. the unit test always passes and the ASP.NET MVC call always fails.
My question, then, is why does the code work in a unit test but virtually identical code fails in ASP.NET MVC?

Entity Framework - all columns are invalid

This is the error I get when I attempt to register an account on my local ASP.NET MVC project. This all started when I tried to move the default account manager over to my main DbContext. It worked fine while it was still on "DefaultConnection."
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'UserName'.
Invalid column name 'UserName'.
Invalid column name 'Email'.
Invalid column name 'EmailConfirmed'.
Invalid column name 'PasswordHash'.
Invalid column name 'SecurityStamp'.
Invalid column name 'PhoneNumber'.
Invalid column name 'PhoneNumberConfirmed'.
Invalid column name 'TwoFactorEnabled'.
Invalid column name 'LockoutEndDateUtc'.
Invalid column name 'LockoutEnabled'.
Invalid column name 'AccessFailedCount'.
Invalid column name 'UserName'.
Source of the error is this statement from the default AccountController:
var result = await UserManager.CreateAsync(user, model.Password);
This is what my tables look like. I've been fiddling for a long time; IdentityUser was not always there, and now it seems it has "taken" AspNetUsers's column names... very odd.
This is my DbContext file
public class MainContext : IdentityDbContext<ApplicationUser>
{
public MainContext() : base("MainContext")
{
Database.SetInitializer(new DropCreateDatabaseAlways<MainContext>());
}
public DbSet<Story> Stories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating( modelBuilder );
modelBuilder.Entity<IdentityUser>().HasKey( t => t.Id );
modelBuilder.Entity<IdentityUserLogin>().HasKey( l => new {l.UserId, l.ProviderKey, l.LoginProvider} );
modelBuilder.Entity<IdentityRole>().HasKey( r => r.Id );
modelBuilder.Entity<IdentityUserRole>().HasKey( r => new { r.RoleId, r.UserId } );
}
public DbSet<ViewModels.StoryDetailsVm> StoryViewModels { get; set; }
public DbSet<ViewModels.StoryEditVm> StoryEditVMs { get; set; }
}
This is my IdentityModels file
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MainContext", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
I've been trying to solve this for 6 hours. Would greatly appreciate any help I can get. Apologies for all this code, I have no idea where the problem lies.
Stack trace
[SqlException (0x80131904): Invalid column name 'UserName'.
Invalid column name 'UserName'.
Invalid column name 'Email'.
Invalid column name 'EmailConfirmed'.
Invalid column name 'PasswordHash'.
Invalid column name 'SecurityStamp'.
Invalid column name 'PhoneNumber'.
Invalid column name 'PhoneNumberConfirmed'.
Invalid column name 'TwoFactorEnabled'.
Invalid column name 'LockoutEndDateUtc'.
Invalid column name 'LockoutEnabled'.
Invalid column name 'AccessFailedCount'.
Invalid column name 'UserName'.]
System.Data.SqlClient.<>c.<ExecuteDbDataReaderAsync>b__167_0(Task`1 result) +870314
System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke() +77
System.Threading.Tasks.Task.Execute() +49
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Core.EntityClient.Internal.<ExecuteStoreCommandsAsync>d__c.MoveNext() +249
[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
System.Data.Entity.Core.EntityClient.Internal.<ExecuteStoreCommandsAsync>d__c.MoveNext() +334
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Core.Objects.Internal.<ExecuteAsync>d__0`1.MoveNext() +1515
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Utilities.CultureAwaiter`1.GetResult() +59
System.Data.Entity.Core.Objects.<ExecuteInTransactionAsync>d__3d`1.MoveNext() +862
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__9`1.MoveNext() +358
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Utilities.CultureAwaiter`1.GetResult() +59
System.Data.Entity.Core.Objects.<GetResultsAsync>d__e.MoveNext() +632
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Utilities.CultureAwaiter`1.GetResult() +59
System.Data.Entity.Internal.<FirstMoveNextAsync>d__0.MoveNext() +261
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Infrastructure.<FirstOrDefaultAsync>d__25`1.MoveNext() +349
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +75
Microsoft.AspNet.Identity.EntityFramework.<GetUserAggregateAsync>d__6c.MoveNext() +682
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +75
Microsoft.AspNet.Identity.<ValidateUserName>d__4.MoveNext() +607
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
Microsoft.AspNet.Identity.CultureAwaiter.GetResult() +44
Microsoft.AspNet.Identity.<ValidateAsync>d__0.MoveNext() +235
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +75
Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +422
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +75
Microsoft.AspNet.Identity.<CreateAsync>d__d.MoveNext() +475
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
fcon.Controllers.<Register>d__15.MoveNext() in C:\Users\G\Documents\Visual Studio 2015\Projects\fcon\fcon\Controllers\AccountController.cs:157
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +42
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +73
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +37
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +68
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +69
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +230
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +68
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +42
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +124
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +32
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +26
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +24
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +29
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +23
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
Keywords for Google: DropCreateDatabaseAlways Manually Delete Database Old Model
I found the actual solution. This is one of the most infuriating bugs ever. Entity seems to leave behind a shadow copy of a manually-deleted database. The fact that my columns would simply not behave puzzled me greatly -- since I had DropCreateDatabaseAlways enabled -- and I highly suspect it was because Entity was referring to the shadow copy all the time.
This is the same reason why this bug occurs. Entity can't attach to a database with the same name and in the same location as an old databsae if the old one has been deleted -- because the old one is still there.
The solution: Download SSMS, find the shadow copy, and erase it. If you manually delete the database even once, then there is room for complications.

ArgumentNullException on await SignInManager.ExternalSignInAsync(loginInfo, true);

I'm using facebook authentication with ASP.NET Identity. I can authenticate with facebook just fine, but when I call SignInManager.ExternalSignInAsync(), I get an ArgumentNullException when it adds claims to the identity. Here's the stack trace:
[ArgumentNullException: Value cannot be null.
Parameter name: value]
System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue) +10798181
System.Security.Claims.Claim..ctor(String type, String value) +34
Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +759
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.AspNet.Identity.Owin.<SignInAsync>d__2.MoveNext() +199
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.AspNet.Identity.CultureAwaiter.GetResult() +23
Microsoft.AspNet.Identity.Owin.<SignInOrTwoFactor>d__23.MoveNext() +1279
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.AspNet.Identity.Owin.<ExternalSignInAsync>d__1d.MoveNext() +794
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
SteamAchievements.Web.Controllers.<ExternalLoginCallback>d__2.MoveNext() in C:\projects\facebooksteamachievements\SteamAchievements.Web\Controllers\AccountController.cs:48
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +84
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
As far as I can tell, I've configured everything correctly. And the best part is, none of the claims have a null type or name. Here's my configuration in StartUp.Auth:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/Account/Login"),
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
if (!string.IsNullOrEmpty(Settings.Default.FacebookAppId))
{
var options = new FacebookAuthenticationOptions
{
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim("AccessToken", context.AccessToken));
return Task.FromResult(0);
}
},
AppId = Settings.Default.FacebookAppId,
AppSecret = Settings.Default.FacebookAppSecret
};
app.UseFacebookAuthentication(options);
}
And here's the ExternalLoginCallback action. It's pretty simple. If the external login succeeded, it creates a user if one does not exist and adds a login if it doesn't exist.
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var user = await UserManager.FindByNameAsync(loginInfo.Login.ProviderKey);
if (user == null)
{
long facebookId = Convert.ToInt64(loginInfo.Login.ProviderKey);
user = new steam_User {UserName = loginInfo.Login.ProviderKey, FacebookUserId = facebookId};
var createResult = await UserManager.CreateAsync(user);
if (!createResult.Succeeded)
{
AddErrors(createResult);
return View("ExternalLoginFailure");
}
}
var logins = await UserManager.GetLoginsAsync(user.Id);
if (!logins.Any())
{
var addResult = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
if (!addResult.Succeeded)
{
AddErrors(addResult);
return View("ExternalLoginFailure");
}
}
// here's where the exception is thrown
await SignInManager.ExternalSignInAsync(loginInfo, true);
return RedirectToLocal("~/");
}
It would be great if I could step into ExternalSignInAsync(), but I can't. Figuring out how to do that would be a great start.
What am I missing?
If more source code helps, the project is open source and can be found on GitHub.
Update
Here's a better workaround. I implemented ClaimsIdentityFactory, and my implementation doesn't throw ArgumentNullException.
private class ApplicationIdentityFactory : ClaimsIdentityFactory<steam_User, int>
{
public async override Task<ClaimsIdentity> CreateAsync(UserManager<steam_User, int> manager, steam_User user, string authenticationType)
{
var claims = new[]
{
new Claim(UserIdClaimType, user.Id.ToString()),
new Claim(UserNameClaimType, user.UserName)
};
var identity = new ClaimsIdentity(claims, authenticationType, UserNameClaimType, RoleClaimType);
if (manager.SupportsUserRole)
{
var roles = await manager.GetRolesAsync(user.Id);
identity.AddClaims(roles.Select(r => new Claim(RoleClaimType, r)));
}
if (manager.SupportsUserClaim)
{
identity.AddClaims(await manager.GetClaimsAsync(user.Id));
}
return identity;
}
}
Here's my workaround. I don't like it, but it works. If ExternalSignInAsync fails, it will fall back on creating an auth cookie with the FormsAuthentication api.
try
{
await SignInManager.ExternalSignInAsync(loginInfo, true);
}
catch (Exception)
{
// For now, here's my work around
FormsAuthentication.SetAuthCookie(user.UserName, true);
}

Getting "A task was cancelled" while trying to create a document in DocumentDB [duplicate]

This question already has answers here:
Want to understand async
(3 answers)
Closed 2 years ago.
When I try to create a document in my DocumentDB database using the following code, the code hangs where I call CreateDocumentAsync() and eventually gives me "A task was cancelled" error.
Any idea why?
public static async Task<Employee> CreateEmployee(Employee emp)
{
try
{
using (client = new DocumentClient(new Uri(endPointUrl), authorizationKey))
{
//Get the database
var database = await GetDatabaseAsync();
//Get the Document Collection
var collection = await GetCollectionAsync(database.SelfLink, "Employees");
await client.CreateDocumentAsync(collection.SelfLink, emp);
// Do something else with employee
}
}
catch
{
// Handle error
}
return emp;
}
P.S. For brevity, I didn't include the code for GetDatabaseAsync() and GetCollectionsAsync() sections. Please note that the employee document IS created in my database. So, this code clearly connects to the DocumentDB database, finds the collection and creates the document.
Just not sure why it hangs and eventually returns the error.
***** Update ******
Here's the error details:
A task was canceled.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Threading.Tasks.TaskCanceledException: A task was canceled.
Source Error:
HttpResponseMessage response = await client.PostAsJsonAsync("api/hr/register", employee);
Stack Trace:
[TaskCanceledException: A task was canceled.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +10915395
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
ConsumerWebApi.Controllers.<Index>d__0.MoveNext() in c:\Users\Sam\Documents\Visual Studio 2013\Projects\ConsumerWebApi\ConsumerWebApi\Controllers\HomeController.cs:36
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +10915367
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +135
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +135
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +132
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +138
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +138
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +138
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
I had a similar error thrown using one of DocumentClients async functions. I used await correctly for each call but then I found that this was caused by a proxy server interfering with the traffic. So for those working from inside a company network - consider checking this.
Just try client.
Timeout = TimeSpan.FromSeconds(240);

Categories