AdomdConnectionException: The connection string is not valid with pyadomd - python-3.x

I am trying to set up connection to the PowerBI service with the pyadomd library.
Here is the connection string:
"Provider=MSOLAP;Data Source=powerbi://api.powerbi.com/v1.0/myorg/workspace_name;User ID=user_email;Password=user_passw;Initial Catalog=dataset_name"
I get the error:
AdomdConnectionException: The connection string is not valid. ---> System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at Microsoft.AnalysisServices.AdomdClient.XmlaClient.GetInstancePort(ConnectionInfo connectionInfo)
--- End of inner exception stack trace ---
at Microsoft.AnalysisServices.AdomdClient.XmlaClient.GetInstancePort(ConnectionInfo connectionInfo)
at Microsoft.AnalysisServices.AdomdClient.XmlaClient.GetTcpClient(ConnectionInfo connectionInfo)
at Microsoft.AnalysisServices.AdomdClient.XmlaClient.OpenTcpConnection(ConnectionInfo connectionInfo)
at Microsoft.AnalysisServices.AdomdClient.XmlaClient.OpenConnection(ConnectionInfo connectionInfo, Boolean& isSessionTokenNeeded)
at Microsoft.AnalysisServices.AdomdClient.XmlaClient.Connect(ConnectionInfo connectionInfo, Boolean beginSession)
at Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Connect(Boolean toIXMLA)
at Microsoft.AnalysisServices.AdomdClient.AdomdConnection.ConnectToXMLA(Boolean createSession, Boolean isHTTP)
at Microsoft.AnalysisServices.AdomdClient.AdomdConnection.Open()
Does anyone know what is wrong?
I don't want to use the other library like "adodbapi" in this case as I have another unresolved error with it.

Related

Randomly NServiceBus MessageDeserializationException because of Newtonsoft JsonReaderException

We're experiencing randomly exceptions when deserializing commands. We have a send-only API that puts messages in a queue. The tries to consume the message but fails. It occurs randomly no matter what message type. Sometimes the backend can deserialize the message.
We set up NServiceBus to use NewtonSoft.Json (API uses 12.0.3 and Backend uses 12.0.1) with default settings. We don't make use of the unobtrusive mode since we declare our commands with ICommand. As transport we use Azure ServiceBus.
The most disturbing thing is: We have an almost exact same infrastructure in our staging environment (BETA) and everything works fine. When we reproduce the same message on both environments (BETA and PRODUCTION) the message can be deserialized on BETA with the same data whereas on PRODUCTION it can't. All headers and body data are equal, even the enclosed message types. Both environments use identical (binary same) binaries. Both environments run on nearly identical configured app services on Azure (e.g. net core 3.1, win 64-bit).
{
"AmqpMessage": null,
"Body": "{\"Email\":\"vofil69829#bbsaili.com\",\"AccountantId\":{\"Value\":\"75f61737-b9e8-40a3-a1c4-23d7bd61c527\"}}",
"MessageId": "d829e8ce-261f-4033-a294-f279c0390851",
"PartitionKey": null,
"TransactionPartitionKey": null,
"SessionId": null,
"ReplyToSessionId": null,
"TimeToLive": "10675199.02:48:05.4775807",
"CorrelationId": "2ca22dd7-396b-4950-acb6-ad4800ac9d65",
"Subject": null,
"To": null,
"ContentType": "application/json",
"ReplyTo": null,
"ScheduledEnqueueTime": "0001-01-01T00:00:00+00:00",
"ApplicationProperties": {
"NServiceBus.Transport.Encoding": "application/octect-stream",
"NServiceBus.MessageId": "2ca22dd7-396b-4950-acb6-ad4800ac9d65",
"NServiceBus.MessageIntent": "Send",
"NServiceBus.ConversationId": "97743453-c3ac-4e08-a1df-ad4800ac9d65",
"NServiceBus.CorrelationId": "2ca22dd7-396b-4950-acb6-ad4800ac9d65",
"NServiceBus.OriginatingMachine": "dw1sdwk00002R",
"NServiceBus.OriginatingEndpoint": "AwarenessCenter.Api",
"$.diagnostics.originating.hostid": "a5a720d14ccabd7a8ba708f5bc79b2a3",
"NServiceBus.ContentType": "application/json",
"NServiceBus.EnclosedMessageTypes": "AwarenessCenter.Domain.Users.Registration.InviteUserCommand, AwarenessCenter.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"NServiceBus.Version": "7.4.4",
"NServiceBus.TimeSent": "2021-06-15 10:28:28:288468 Z",
"Diagnostic-Id": "00-1d6433cf14ae654a84e290f66d5faf25-3b4885ae29c8fc4f-00",
"NServiceBus.ExceptionInfo.ExceptionType": "NServiceBus.MessageDeserializationException",
"NServiceBus.ExceptionInfo.InnerExceptionType": "Newtonsoft.Json.JsonReaderException",
"NServiceBus.ExceptionInfo.HelpLink": null,
"NServiceBus.ExceptionInfo.Message": "An error occurred while attempting to extract logical messages from incoming physical message 2ca22dd7-396b-4950-acb6-ad4800ac9d65",
"NServiceBus.ExceptionInfo.Source": "NServiceBus.Core",
"NServiceBus.ExceptionInfo.StackTrace": "NServiceBus.MessageDeserializationException: An error occurred while attempting to extract logical messages from incoming physical message 2ca22dd7-396b-4950-acb6-ad4800ac9d65\r\n ---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'AccountantId', line 1, position 50.\r\n at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)\r\n at Newtonsoft.Json.JsonTextReader.ReadAsString()\r\n at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n at NServiceBus.Newtonsoft.Json.JsonMessageSerializer.ReadObject(Stream stream, Boolean isArrayStream, Type type)\r\n at NServiceBus.Newtonsoft.Json.JsonMessageSerializer.DeserializeMultipleMessageTypes(Stream stream, IList`1 messageTypes, Boolean isArrayStream)\r\n at NServiceBus.Newtonsoft.Json.JsonMessageSerializer.Deserialize(Stream stream, IList`1 messageTypes)\r\n at NServiceBus.DeserializeMessageConnector.Extract(IncomingMessage physicalMessage) in /_/src/NServiceBus.Core/Pipeline/Incoming/DeserializeMessageConnector.cs:line 119\r\n at NServiceBus.DeserializeMessageConnector.ExtractWithExceptionHandling(IncomingMessage message) in /_/src/NServiceBus.Core/Pipeline/Incoming/DeserializeMessageConnector.cs:line 53\r\n --- End of inner exception stack trace ---\r\n at NServiceBus.DeserializeMessageConnector.ExtractWithExceptionHandling(IncomingMessage message) in /_/src/NServiceBus.Core/Pipeline/Incoming/DeserializeMessageConnector.cs:line 53\r\n at NServiceBus.DeserializeMessageConnector.Invoke(IIncomingPhysicalMessageContext context, Func`2 stage) in /_/src/NServiceBus.Core/Pipeline/Incoming/DeserializeMessageConnector.cs:line 29\r\n at NServiceBus.InvokeAuditPipelineBehavior.Invoke(IIncomingPhysicalMessageContext context, Func`2 next) in /_/src/NServiceBus.Core/Audit/InvokeAuditPipelineBehavior.cs:line 27\r\n at NServiceBus.ProcessingStatisticsBehavior.Invoke(IIncomingPhysicalMessageContext context, Func`2 next) in /_/src/NServiceBus.Core/Performance/Statistics/ProcessingStatisticsBehavior.cs:line 32\r\n at NServiceBus.TransportReceiveToPhysicalMessageConnector.Invoke(ITransportReceiveContext context, Func`2 next) in /_/src/NServiceBus.Core/Pipeline/Incoming/TransportReceiveToPhysicalMessageConnector.cs:line 61\r\n at NServiceBus.MainPipelineExecutor.Invoke(MessageContext messageContext) in /_/src/NServiceBus.Core/Pipeline/MainPipelineExecutor.cs:line 50\r\n at NServiceBus.Transport.AzureServiceBus.MessagePump.InnerProcessMessage(Task`1 receiveTask)",
"NServiceBus.TimeOfFailure": "2021-06-15 10:28:28:346039 Z",
"NServiceBus.ExceptionInfo.Data.Message ID": "2ca22dd7-396b-4950-acb6-ad4800ac9d65",
"NServiceBus.ExceptionInfo.Data.Transport message ID": "b6c3a3cf-84bf-4235-8551-35a1daf4bc5d",
"NServiceBus.FailedQ": "AwarenessCenter.Backend",
"NServiceBus.ProcessingMachine": "dw1sdwk00002R",
"NServiceBus.ProcessingEndpoint": "AwarenessCenter.Backend",
"$.diagnostics.hostid": "f0377aabcaf4cc26d4afb3e60b704550",
"$.diagnostics.hostdisplayname": "dw1sdwk00002R"
},
"LockToken": "00000000-0000-0000-0000-000000000000",
"DeliveryCount": 0,
"LockedUntil": "0001-01-01T00:00:00+00:00",
"SequenceNumber": 541,
"DeadLetterSource": null,
"PartitionId": 0,
"EnqueuedSequenceNumber": 0,
"EnqueuedTime": "2021-06-15T10:28:28.396+00:00",
"LockTokenGuid": "00000000-0000-0000-0000-000000000000",
"ExpiresAt": "9999-12-31T23:59:59.9999999+00:00",
"DeadLetterReason": null,
"DeadLetterErrorDescription": null
}
I suspect the serialization of the message is not done properly or the type serialized and deserialized are not identical. That what the exception is thrown by NServiceBus is hinting at (see NServiceBus.ExceptionInfo.StackTrace header for details. Specifically
An error occurred while attempting to extract logical messages from incoming physical message 2ca22dd7-396b-4950-acb6-ad4800ac9d65\r\n ---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'AccountantId', line 1, position 50
Based on the serialized payload
"{"Email":"vofil69829#bbsaili.com","AccountantId":{"Value":"75f61737-b9e8-40a3-a1c4-23d7bd61c527"}}"
looks like the AccountantId is not a simple type but rather a nested type since JSON translates into
{
"Email":"vofil69829#bbsaili.com",
"AccountantId":
{
"Value":"75f61737-b9e8-40a3-a1c4-23d7bd61c527"
}
}
Where I suspect on the receiving side the expectation is to see a message of the following type
class SomeContract
{
public string Email { get; set; }
public Guid AccountantId { get; set; }
}
So after we deployed a third time with the exact same codebasis the problem resolved by itself. We have no idea what caused the issue.

Azure Web App and Azure SQL connectionString error

I have taken the Connection String from my Azure SQL instance via the portal and pasted it into my web.config. If I test the connection string when I create the Publishing Profile it is fine. If I throw an exception in Global.asax to see my connection string like this:
throw new Exception(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
, it shows my correct one. However, I still get this error:
{
"Message": "An error has occurred.",
"ExceptionMessage": "Format of the initialization string does not conform to specification starting at index 0.",
"ExceptionType": "System.ArgumentException",
"StackTrace": " at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)\r\n at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)\r\n at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)\r\n at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)\r\n at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)\r\n at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)\r\n at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)\r\n at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c)\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext)\r\n at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)\r\n at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config)\r\n at System.Data.Entity.Internal.LazyInternalConnection.Initialize()\r\n at System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName()\r\n at System.Data.Entity.Internal.LazyInternalContext.get_ProviderName()\r\n at System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()\r\n at System.Data.Entity.Internal.InternalContext.Initialize()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path)\r\n at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)\r\n at ExpressoApi.Controllers.MenusController.GetMenus() in C:\\Users\\david\\Desktop\\ExpressoApi-master\\ExpressoApi\\Controllers\\MenusController.cs:line 17\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.<GetExecutor>b__3(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"
}
I've spent a couple of hours trying to fix this, I've made no progress.
I found the problem. Simply pasting the connection string into my web.config of my Azure App does nothing. I needed to add the connection string into my PUBLISHSETTINGS file and the re-publish. Then everything works.

Acumatica Rest API Returning Errors Differently In Code than Postman

This problem has been driving me nuts for hours and I can't figure out what's going on. For example's sake, I have created a test action on a custom page in my Acumatica installation.
This test action is as follows:
public PXAction<UsrPCMJob> testAction;
[PXUIField(DisplayName = "Test")]
[PXButton()]
public virtual void TestAction()
{
throw new PXException("This is just a test action!");
}
I have created a rest endpoint for this page and mapped the test action.
If I create the post in Postman, it works as expected:
{"entity":{"Job":{"value":"0228467"}},"parameters":null}
and I get the following as a response:
"exceptionMessage": "PX.Data.PXException: This is just a test action!
However, in code (PHP, using Guzzle for my request), even though my json body is the same:
{"entity":{"Job":{"value":"0228467"}},"parameters":null}
I get this error message:
{"message":"An error has occurred.","exceptionMessage":"PX.Data.PXException: Error #251: Failed to commit the Job row.\r\n at PX.Api.SyImportProcessor.SyStep.a(Object A_0, PXFilterRow[] A_1, PXFilterRow[] A_2)\r\n at PX.Api.SyImportProcessor.ExportTableHelper.ExportTable()","exceptionType":"PX.Api.ContractBased.OutcomeEntityHasErrorsException","stackTrace":" at System.Monads.ArgumentCheck.CheckNull[TSource](TSource source, Func`1 exceptionSource)\r\n at PX.Api.ContractBased.EntityService.GetOperationResult(EntityImpl entity, EntityExportContextBuilder entityExportContextBuilder, PXSYTable exportedKeys, List`1 errors) in F:\\Bld2\\AC-FULL60U3-JOB1\\sources\\NetTools\\PX.Api.ContractBased\\EntityService.cs:line 457\r\n at PX.Api.ContractBased.EntityService.Invoke(ISystemContract systemContract, String version, String name, EntityImpl entity, ActionImpl action, CbOperationContext operationContext) in F:\\Bld2\\AC-FULL60U3-JOB1\\sources\\NetTools\\PX.Api.ContractBased\\EntityService.cs:line 720\r\n at PX.Api.ContractBased.Soap.EntityGateBase.InvokeImpl(EntityImpl entity, ActionImpl action) in F:\\Bld2\\AC-FULL60U3-JOB1\\sources\\NetTools\\PX.Api.ContractBased\\Soap\\EntityGateBase.cs:line 144\r\n at PX.Api.ContractBased.Soap.EntityGateV2.PX.Api.ContractBased.IRestGate.Invoke(EntityImpl entity, ActionImpl action) in F:\\Bld2\\AC-FULL60U3-JOB1\\sources\\NetTools\\PX.Api.ContractBased\\Soap\\EntityGateV2.cs:line 357\r\n at PX.Api.ContractBased.Soap.WebApiSoapController.RestInvoke(EntityEndpoint endpoint, String objectName, String actionName, ActionInvocation invocation) in F:\\Bld2\\AC-FULL60U3-JOB1\\sources\\NetTools\\PX.Api.ContractBased\\Soap\\WebApiSoapController.cs:line 414\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}
My php guzzle client that I created works fine on other requests that use actions, but not for this test action or a few other actions.
Any help you can offer would be GREATLY appreciated. Thanks!

How to add formatProvider parameter to NLog.LogEventInfo.Create method?

I have following NLog 2.0 code to log exceptions:
Dim theEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Error, loggerName, message, ex)
After upgrading to NLog 4.1 I see following warning:
Function Create(logLevel As LogLevel, loggerName As String, message As String, exception As Exception) As LogEventInfo' is obsolete: 'use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message)'
... it asks me to add IFormatProvider formatProvider as parameter. What should I add there?
Dim theEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Error, loggerName, ex, ???, message)
You can safely use null, one from the System.Globalization.CultureInfo members (a good guide can be found here) or create your own custom format provider depending on your needs.
The current implementation (as of v.4.1.2 on GitHub) will simply use CultureInfo.CurrentCulture if the FormatProvider property is null.

MethodAccessException when calling nlog LogManager.GetCurrentClassLogger()

I'm getting an exception when I run a unit test on a controller in web project (ASP.NET web api). The exception is thrown when LogManager.GetCurrentClassLogger() of the controller is executed:
System.MethodAccessException: Attempt by method 'Castle.Proxies.ClaimsPrincipalProxy.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)' to access method 'Castle.DynamicProxy.Internal.TypeUtil.Sort(System.Reflection.MemberInfo[])' failed
It results in TypeInitializationException in LogManager.GetCurrentClassLogger().
here is the call stack:
at Castle.Proxies.ClaimsPrincipalProxy.GetObjectData(SerializationInfo, StreamingContext)
at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String& typeName, String& assemName, String[]& fieldNames, Object[]& fieldValues)
at System.AppDomain.get_Evidence()
at System.AppDomain.get_Evidence()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, ref String typeName)
at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, ref Object result, ref Object resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NLog.Config.XmlLoggingConfiguration.get_AppConfig()
at NLog.LogFactory.get_Configuration()
at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
at NLog.LogFactory.GetLogger(String name)
at NLog.LogManager.GetCurrentClassLogger()
Update:
The issue happens when the unit test project references NSubstitute. So, it seems like there some dangerous combination of Web API, NSubstitute and NLog.
Update 2:
Found what upsets Nlog in Controller.
Before calling controller method I set mocked principal for Thread.CurrentPrincipal:
var principal = Substitute.For<ClaimsPrincipal>();
principal.Identity.Returns(...);
Thread.CurrentPrincipal = principal;
How could this be fixed?
The Castle assembly may be marked with the AllowPartiallyTrustedCallersAttribute, and that uses the level 2 security transparency model.
Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.
Can you try annotating your unit test (and Class) with the following attribute - [SecuritySafeCritical]

Resources