nlog event context custom variables log error - c#

I have a simple setup with Nlog, its working fine when just passing through normal parameters like the message, but when i pass a LogEventInfo object like this:
//inside a class
private static Logger _logger = LogManager.GetLogger("MyLogs");
//in a method
LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "LogName", "some message");
logEvent.Properties.Add("httpMethod", "GET");
_logger.Warn(logEvent);
I am receiving the following error:
[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +52
System.Collections.Generic.Enumerator.MoveNext() +10900893
NLog.Targets.Target.MergeEventProperties(LogEventInfo logEvent) +312
NLog.Targets.Target.Write(AsyncLogEventInfo logEvent) +74
[NLogRuntimeException: Exception occurred in NLog]
NLog.<>c__DisplayClass1.<Write>b__0(Exception ex) +150
NLog.Internal.SingleCallContinuation.Function(Exception exception) +153
NLog.Targets.Target.Write(AsyncLogEventInfo logEvent) +189
NLog.Targets.Target.WriteAsyncLogEvent(AsyncLogEventInfo logEvent) +364
NLog.LoggerImpl.WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException) +341
NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) +351
NLog.Logger.WriteToTargets(LogLevel level, IFormatProvider formatProvider, T value) +136
NLog.Logger.Warn(T value) +106
proj.Infrastructure.Logging.LogResponse(String message, IOwinContext context, String flow, String action) in c:\Sites\proj\Infrastructure\Logging.cs:45
proj.<Validate>d__0.MoveNext() in c:\Sites\proj\myclass.cs:40
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointAsync>d__1e.MoveNext() +1049
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Microsoft.Owin.Security.OAuth.<InvokeAsync>d__0.MoveNext() +1735
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +664
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is the nlog configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
internalLogFile="c:\log.txt"
internalLogLevel="Trace"
throwExceptions="true">
<targets>
<target xsi:type="File" name="textFile"
fileName="${basedir}/logs/${shortdate}/file.txt" layout="${message} ${event-context:item=httpMethod}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="textFile" />
</rules>
</nlog>
I have had a search, and cant find anything related. The nlog version i am using is: 3.1.0.0
Anyone have any ideas?

In this case you should use void Log(LogEventInfo logEvent) method.
_logger.Log(logEvent);
Source: https://github.com/NLog/NLog/wiki/EventContext-Layout-Renderer
But if you want know why this happen, you can follow by link:
https://github.com/NLog/NLog/commit/02e7eff1c5606ea4a4aa4dffc3114adf82791bd6

Related

OpenSolutionAsync - Field not found: 'Microsoft.Build.Utilities.ChangeWaves.Wave16_8' on .NET Framework 4.8 / 4.7.2

This code works fine on .NET 6,
but when I want to run it on .NET Framework 4.8, then that's what I receive
System.MissingFieldException: Field not found: 'Microsoft.Build.Utilities.ChangeWaves.Wave16_8'.
at Microsoft.Build.Evaluation.Expander`2.IsTruncationEnabled(ExpanderOptions options)
at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertiesLeaveTypedAndEscaped(String expression, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem)
at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertiesLeaveEscaped(String expression, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem)
at Microsoft.Build.Evaluation.Expander`2.ExpandIntoStringLeaveEscaped(String expression, ExpanderOptions options, IElementLocation elementLocation)
at Microsoft.Build.Evaluation.ToolsetReader.ExpandPropertyUnescaped(ToolsetPropertyDefinition property, Expander`2 expander)
at Microsoft.Build.Evaluation.ToolsetReader.EvaluateAndSetProperty(ToolsetPropertyDefinition property, PropertyDictionary`1 properties, PropertyDictionary`1 globalProperties, PropertyDictionary`1 initialProperties, Boolean accumulateProperties, String& toolsPath, String& binPath, Expander`2& expander)
at Microsoft.Build.Evaluation.ToolsetReader.ReadToolset(ToolsetPropertyDefinition toolsVersion, PropertyDictionary`1 globalProperties, PropertyDictionary`1 initialProperties, Boolean accumulateProperties)
at Microsoft.Build.Evaluation.ToolsetReader.ReadEachToolset(Dictionary`2 toolsets, PropertyDictionary`1 globalProperties, PropertyDictionary`1 initialProperties, Boolean accumulateProperties)
at Microsoft.Build.Evaluation.ToolsetReader.ReadToolsets(Dictionary`2 toolsets, PropertyDictionary`1 globalProperties, PropertyDictionary`1 initialProperties, Boolean accumulateProperties, String& msBuildOverrideTasksPath, String& defaultOverrideToolsVersion)
at Microsoft.Build.Evaluation.ToolsetReader.ReadAllToolsets(Dictionary`2 toolsets, ToolsetRegistryReader registryReader, ToolsetConfigurationReader configurationReader, PropertyDictionary`1 environmentProperties, PropertyDictionary`1 globalProperties, ToolsetDefinitionLocations locations)
at Microsoft.Build.Evaluation.ProjectCollection.InitializeToolsetCollection(ToolsetRegistryReader registryReader, ToolsetConfigurationReader configReader)
at Microsoft.Build.Evaluation.ProjectCollection..ctor(IDictionary`2 globalProperties, IEnumerable`1 loggers, IEnumerable`1 remoteLoggers, ToolsetDefinitionLocations toolsetDefinitionLocations, Int32 maxNodeCount, Boolean onlyLogCriticalEvents, Boolean loadProjectsReadOnly)
at Microsoft.CodeAnalysis.MSBuild.Build.ProjectBuildManager.StartBatchBuild(IDictionary`2 globalProperties) at /_/src/Workspaces/Core/MSBuild/MSBuild/Build/ProjectBuildManager.cs:line 161
at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Worker.<LoadAsync>d__19.MoveNext() at /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs:line 134
--- End of the stack trace from the previous location where the exception occurred ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.<LoadSolutionInfoAsync>d__22.MoveNext() at /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.cs:line 218
--- End of the stack trace from the previous location where the exception occurred ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.<OpenSolutionAsync>d__24.MoveNext() at /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildWorkspace.cs:line 204
--- End of the stack trace from the previous location where the exception occurred ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Here's the code
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.IO;
...
MSBuildLocator.RegisterDefaults();
var msWorkspace = MSBuildWorkspace.Create();
var solution = await msWorkspace.OpenSolutionAsync(pathToSln); <--- fails here
...
Of course I have:
Here are my other nugets:
Does anyone have an idea what I may be missing?
I needed to add Microsoft.Build nuget

Map IReadOnlyDictionary EfCore

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
});
}

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.

WebAPI: Unable to load one or more of the requested types

I'm developing an application using Silverlight. I've created WebAPI project in my solution:
BusinessApplication8
BusinessApplication8.Web
BusinessApplication8.WebAPI
First one is Silverlight project, second one contains my EDMX file. In my WebAPI project I'm using my DbContext like this:
public IEnumerable <object> Get()
{
var database = new DABIREntities();
var query = database.noe_nameh.Take(1).Select(item = > new {
Id = item.uid,
Description = item.sharh
}).ToList();
return query;
}
Everything works fine in local host and I get result in the browser. When I publish my WebAPI project and Call that GET method via URL I'm getting this error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
</ExceptionMessage>
<ExceptionType>System.Reflection.ReflectionTypeLoadException</ExceptionType>
<StackTrace>
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) at System.Reflection.RuntimeModule.GetTypes() at System.Reflection.Assembly.GetTypes() at
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly() at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load() at
System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) at
System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection
edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors) at
System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies,
EdmItemCollection edmItemCollection, Action`1 logLoadMessage) at System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type type, EdmItemCollection
edmItemCollection) at System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly) at
System.Data.Objects.ObjectContext.GetTypeUsage(Type entityCLRType) at System.Data.Objects.ObjectContext.CreateObjectSet[TEntity](String entitySetName) at
BusinessApplication8.Web.DABIREntities.get_noe_nameh() at BusinessApplication8.WebAPI.Controllers.SearchController.Get() at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken
cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at
System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at
System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
</Error>
Any Idea?
Finally I solved my problem. First of all I changed my API method to this:
public IEnumerable<object> Get()
{
try
{
var database = new DABIREntities();
var query = database.noe_nameh.Take(1).Select(item => new
{
Id = item.uid,
Description = item.sharh
}).ToList();
return query;
}
catch (ReflectionTypeLoadException exception)
{
return exception.LoaderExceptions.Select(item => item.Message).ToList();
}
}
That helped me to figure out my exact exceptions. We should set Copy to Local to below dll:
System.ServiceModel
System.ServiceModel.DomainServices.EntityFramework
System.ServiceModel.DomainServices.Hosting
System.ServiceModel.DomainServices.Server

Invoking hub method from signalr .net client throws exception

I've been trying to call a method on my hub from a signalr .Net client however it throws the following exception:
[ArgumentNullException: Value cannot be null.
Parameter name: s]
System.IO.StringReader..ctor(String s) +10894409
Microsoft.AspNet.SignalR.Json.JsonSerializerExtensions.Parse(JsonSerializer serializer, String json) +63
Microsoft.AspNet.SignalR.Hubs.HubRequestParser.Parse(String data, JsonSerializer serializer) +19
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReceived(IRequest request, String connectionId, String data) +40
Microsoft.AspNet.SignalR.<>c__DisplayClassc.<ProcessRequest>b__7() +34
Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(Func`1 func) +28
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.AspNet.SignalR.Transports.<ProcessSendRequest>d__10.MoveNext() +364
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Mapping.<Invoke>d__0.MoveNext() +386
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is when I try to invoke the method on a remote host, the weird thing when developing it it actually does work locally...
Here is the code of the hub:
public void UpdateLocalPlayerName(string name)
{
...
foreach (var connection in websiteConnections)
{
Clients.Client(connection.ConnectionID).UpdateLocalPlayerName(Context.ConnectionId, name);
}
}
And here is how I try to invoke it with the .Net client
public void UpdateLocalPlayerName(string name)
{
MainHubProxy.Invoke<string>("UpdateLocalPlayerName", name);
}
I am using 2.0.3.0 version of the .Net client and the server runs IIS8...
Any idea what causes this?
Seems to be I had www. infront of the server's url I was connecting to, guess the routing prevented the arguments from being passed correctly. Changed the url to the url without www and it worked.

Categories