Dataverse.ServiceClient fails to connect to Dynamics with "Failed to lookup current organization data" - dynamics-crm

I have a problem with my .NET Core 3.1 application that connects to Dynamics. The error occurs when connecting to dynamics using the ServiceClient class, but it does not happen all the time and is not random. I am having trouble pinpointing the cause of the issue.
This is the error message I get when the application tries to connect:
2023-01-16T07:22:43.189 [Error] Executed 'CreateCustomerTimelineHttpTrigger' (Failed, Id=a36dba87-30c3-4dab-93b3-7a00aeba4de3, Duration=2346ms)Microsoft.PowerPlatform.Dataverse.Client.Utils.DataverseConnectionException : Failed to connect to Dataverse
---> System.AggregateException : One or more errors occurred. (Exception - Fault While initializing client - RefreshInstanceDetails)
---> Exception - Fault While initializing client - RefreshInstanceDetails
---> Exception - Failed to lookup current organization data
---> A proxy type with the name msdyncrm_GetReactions has been defined by another assembly.
Current type: CrmEarlyBound.msdyncrm_GetReactionsResponse, CEP.CustomerTimeline.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, Existing type: CrmEarlyBound.msdyncrm_GetReactionsResponse, CEP.CustomerTimeline.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null (Parameter 'msdyncrm_GetReactions')
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)at System.Threading.Tasks.Task`1.get_Result()
at Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.GetCachedService(ConnectionService& ConnectionObject)
at Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.IntilizeService(ConnectionService& ConnectionObject)
at Microsoft.PowerPlatform.Dataverse.Client.ServiceClient.CreateServiceConnection(Object externalOrgServiceProxy,AuthenticationType requestedAuthType,String hostName,String port,String orgName,NetworkCredential credential,String userId,SecureString password,String domain,String Geo,String claimsHomeRealm,Boolean useSsl,Boolean useUniqueInstance,OrganizationDetail orgDetail,String clientId,Uri redirectUri,PromptBehavior promptBehavior,OrganizationWebProxyClientAsync externalOrgWebProxyClient,String certificateThumbPrint,StoreName certificateStoreName,X509Certificate2 certificate,Uri instanceUrl,Boolean isCloned,Boolean useDefaultCreds,Version incomingOrgVersion,ILogger externalLogger,String tokenCacheStorePath)
---> (Inner Exception #0) Microsoft.PowerPlatform.Dataverse.Client.Utils.DataverseConnectionException : Exception - Fault While initializing client - RefreshInstanceDetails
---> Microsoft.PowerPlatform.Dataverse.Client.Utils.DataverseOperationException : Exception - Failed to lookup current organization data
---> System.ArgumentException : A proxy type with the name msdyncrm_GetReactions has been defined by another assembly. Current type: CrmEarlyBound.msdyncrm_GetReactionsResponse, CEP.CustomerTimeline.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, Existing type: CrmEarlyBound.msdyncrm_GetReactionsResponse, CEP.CustomerTimeline.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null (Parameter 'msdyncrm_GetReactions')
at Microsoft.Xrm.Sdk.AppDomainBasedKnownProxyTypesProvider.AddTypeMapping(Assembly assembly,Type type,String proxyName)
at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.LoadKnownTypes(Assembly assembly)
at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.RegisterAssembly(Assembly assembly)at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.InitializeLoadedAssemblies()
at Microsoft.Xrm.Sdk.AppDomainBasedKnownProxyTypesProvider..ctor()
at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.GetInstance(Boolean supportIndividualAssemblies)
at Microsoft.Xrm.Sdk.ProxySerializationSurrogate.System.Runtime.Serialization.ISerializationSurrogateProvider.GetObjectToSerialize(Object obj,Type targetType)
at System.Runtime.Serialization.DataContractSerializer.SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider,Object oldObj,Type surrogatedDeclaredType,Type& objType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer,Object graph,DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer,Object graph,DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer,Object graph,DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer,Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer,PartInfo part,Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer,PartInfo part,Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameters(XmlDictionaryWriter writer,PartInfo[] parts,Object[] parameters)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer,MessageVersion version,String action,MessageDescription messageDescription,Object returnValue,Object[] parameters,Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer,MessageVersion version,Object[] parameters,Object returnValue,Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message,BufferManager bufferManager,Int32 initialOffset,Int32 maxSizeQuota)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessageAsync(Message message,Int32 maxMessageSize,BufferManager bufferManager,Int32 messageOffset)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message,Int32 maxMessageSize,BufferManager bufferManager,Int32 messageOffset)
at System.ServiceModel.Channels.BufferedMessageContent.EnsureMessageEncoded()
at System.ServiceModel.Channels.BufferedMessageContent.TryComputeLength(Int64& length)
at System.Net.Http.HttpContent.GetComputedOrBufferLength()
at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
at System.Net.Http.SocketsHttpHandler.ValidateAndNormalizeRequest(HttpRequestMessage request)
at System.Net.Http.SocketsHttpHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
at async System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at async System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask,HttpRequestMessage request,CancellationTokenSource cts,Boolean disposeCts)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync[TChannel](Message message,TimeoutHelper timeoutHelper)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async System.ServiceModel.Channels.RequestChannel.RequestAsync(??)at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async System.ServiceModel.Channels.RequestChannel.RequestAsyncInternal(Message message,TimeSpan timeout)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.TaskHelpers.WaitForCompletionNoSpin[TResult](Task`1 task)at System.ServiceModel.Channels.RequestChannel.Request(Message message,TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message,TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action,Boolean oneway,ProxyOperationRuntime operation,Object[] ins,Object[] outs,TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(MethodCall methodCall,ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(MethodInfo targetMethod,Object[] args)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Reflection.DispatchProxyGenerator.Invoke(Object[] args)
at generatedProxy_1.Execute(OrganizationRequest )
at Microsoft.PowerPlatform.Dataverse.Client.Connector.OrganizationWebProxyClientAsync.<>c__DisplayClass52_0.<ExecuteCore>b__0()
at Microsoft.PowerPlatform.Dataverse.Client.Connector.WebProxyClientAsync`1.ExecuteAction[TResult](Func`1 action)
at Microsoft.PowerPlatform.Dataverse.Client.Connector.OrganizationWebProxyClientAsync.ExecuteCore(OrganizationRequest request)
at Microsoft.PowerPlatform.Dataverse.Client.Connector.OrganizationWebProxyClientAsync.Execute(OrganizationRequest request)
at async Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.RefreshInstanceDetails(IOrganizationService dvService,Uri uriOfInstance)
End of inner exception
at async Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.RefreshInstanceDetails(IOrganizationService dvService,Uri uriOfInstance)
End of inner exception
at async Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.RefreshInstanceDetails(IOrganizationService dvService,Uri uriOfInstance)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.DoDirectLoginAsync(Boolean IsOnPrem)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.PowerPlatform.Dataverse.Client.ConnectionService.InitServiceAsync()<---
End of inner exception
at Microsoft.PowerPlatform.Dataverse.Client.ServiceClient.CreateServiceConnection(Object externalOrgServiceProxy,AuthenticationType requestedAuthType,String hostName,String port,String orgName,NetworkCredential credential,String userId,SecureString password,String domain,String Geo,String claimsHomeRealm,Boolean useSsl,Boolean useUniqueInstance,OrganizationDetail orgDetail,String clientId,Uri redirectUri,PromptBehavior promptBehavior,OrganizationWebProxyClientAsync externalOrgWebProxyClient,String certificateThumbPrint,StoreName certificateStoreName,X509Certificate2 certificate,Uri instanceUrl,Boolean isCloned,Boolean useDefaultCreds,Version incomingOrgVersion,ILogger externalLogger,String tokenCacheStorePath)
at Microsoft.PowerPlatform.Dataverse.Client.ServiceClient..ctor(Uri instanceUrl,String clientId,String clientSecret,Boolean useUniqueInstance,ILogger logger)
at CEP.CustomerTimeline.API.Repositories.DynamicsRepository..ctor(IOptions`1 options)
at D:\a\1\s\CEP.CustomerTimeline.API\Repositories\DynamicsRepository.cs : 19at lambda_method(Closure )at DryIoc.Scope.TryGetOrAdd(ImMap`1 items,Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7856at DryIoc.Scope.GetOrAdd(Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7841at lambda_method(Closure )
at DryIoc.Scope.TryGetOrAdd(ImMap`1 items,Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7856at DryIoc.Scope.GetOrAdd(Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7841at lambda_method(Closure )
at DryIoc.Scope.TryGetOrAdd(ImMap`1 items,Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7856at DryIoc.Scope.GetOrAdd(Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7841at lambda_method(Closure )
at DryIoc.Scope.TryGetOrAdd(ImMap`1 items,Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7856
at DryIoc.Scope.GetOrAdd(Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7841at lambda_method(Closure )
at DryIoc.Scope.TryGetOrAdd(ImMap`1 items,Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7856at DryIoc.Scope.GetOrAdd(Int32 id,CreateScopedValue createValue,Int32 disposalOrder)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 7841at lambda_method(Closure ,IResolverContext )
at DryIoc.Container.ResolveAndCacheDefaultFactoryDelegate(Type serviceType,IfUnresolved ifUnresolved)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 225at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType,IfUnresolved ifUnresolved)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\DryIoc\Container.cs : 196
at Microsoft.Azure.WebJobs.Script.WebHost.DependencyInjection.ScopedServiceProvider.GetService(Type serviceType)
at D:\a\_work\1\s\src\WebJobs.Script.WebHost\DependencyInjection\ScopedServiceProvider.cs : 25
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)at lambda_method(Closure ,IServiceProvider ,Object[] )
at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance[T](IServiceProvider serviceProvider) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.cs : 42
at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance[T](IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.cs : 32
at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory`1.<>c__DisplayClass1_1.<.ctor>b__0(IFunctionInstanceEx i)
at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 20
at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory`1.Create(IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 26
at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.CreateInstance(IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs : 44
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.Initialize() at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 793
at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 104
I have seen posts regarding this error when using .NET Framework NuGets, the solution from them are either not applicable or have not worked. I am no expert when it comes to dynamics, my main focus are on integrations so I am at a loss here.
The error occurs when the applications FunctionStartup is running and the repository class, with the connection, is initiated. The connection is done with a scoped lifetime and the same connection is used for all operations towards Dyncamics (I have tried to use one connection per entity as well).
Observations I have made so far:
The earlybound seems to have something to do with the issue, since if I move over to latebound and delete the earlybound files, the issue dissapears. But I have other solutions using the earlybound in combination with ServiceClient that is working fine
The issue seems to be related with the dynamics instance that it connects to as well, as it does not happen for our DEV environment, but occurs in SIT
Removing the type that is causing the issue causes the same error but for a different type
It works locally, it is not until I deploy it to my function app that the crash occurs
A simple restart of the function app will resolve the issue
My reflection is that the earlybound is conflicting with some other component as removing it removes the issue. It is the unknown component that I am looking for and part of me is looking towards dynamics, as it works in one environment and not the other and it is always the same environment it works for.
Any help or insight into this would be greatly appreciated. Please let me know if there are further questions on this.
Thank you!

---> A proxy type with the name msdyncrm_GetReactions has been defined by another assembly.
You are correct, that this is the relevant part of the error.
That that you're not seeing it locally, and or you're not seeing it on the restart of a function indicates that you're dynamically loading a lib during runtime. ( are you? )
if so that lib has the same types as the root function has + the assembly attribute
[assembly: Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute()]
That attribute causes the client to attempt to load the types of that assembly into the type mapper used by the client.
its only usefull if your using Linq operations based on the organization service context.
if your not using linq, the easiest way to fix this is to remove the assembly attribute above.

Related

Error on Open Kb Genexus 17 in Genexus 18

========== Preserve Knowledge Base style based on themes started ==========
No version update was required.
Failed: Preserve Knowledge Base style based on themes
I receive this error in every single KB when i close on Genexus 17 and Open on Genexus 18.
Timestamp: 13/02/2023 14:09:47
Message: HandlingInstanceID: 24c7ba00-4ede-4a8d-b273-6b13d512b349
An exception of type 'Artech.Common.Diagnostics.GxException' occurred and was caught.
-------------------------------------------------------------------------------------
02/13/2023 14:09:47
Type : Artech.Common.Diagnostics.GxException, Artech.Common, Version=11.0.0.0, Culture=neutral, PublicKeyToken=6f5bf81c27b6b8aa
Message : Cannot access a disposed object.
Object name: 'ObjectSelectorControl'.
Source :
Help link :
Exception Data
Product : GeneXus 18
Version : 18.0.167910 U1
Exception.Severity : Error
TargetSite :
HResult : -2146232832
Stack Trace : The stack trace is unavailable.
Additional Info:
MachineName : MACHINNENAME
TimeStamp : 13/02/2023 17:09:47
FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=79a65ef946496ecc
AppDomainName : GeneXus.exe
ThreadIdentity : MACHINNENAME\WINDOWSUSER
WindowsIdentity : MACHINNENAME\WINDOWSUSER
Inner Exception
---------------
Type : System.ObjectDisposedException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Cannot access a disposed object.
Object name: 'ObjectSelectorControl'.
Source : System.Windows.Forms
Help link :
ObjectName : ObjectSelectorControl
TargetSite : Void CreateHandle()
HResult : -2146232798
Stack Trace : at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at Artech.Core.UI.ToolWindows.ObjectSelectorControl.StopPainting()
at Artech.Core.UI.ToolWindows.ObjectSelectorControl.OnUpdateDataSource(List`1 items)
at Artech.Core.UI.ToolWindows.ObjectSelectorControl.set_Objects(List`1 value)
at Artech.Core.UI.ToolWindows.WorkWithObjectsEditor.Artech.Core.UI.ToolWindows.IObjectBrowser.UpdateControl(ObjectBrowserHelperResult result)
at Artech.Core.UI.ToolWindows.ObjectBrowserHelper.WorkerRunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
at System.ComponentModel.RunWorkerCompletedEventHandler.Invoke(Object sender, RunWorkerCompletedEventArgs e)
at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
at System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg)
Category: Default Category
Priority: 0
EventId: 100
Severity: Error
Title:Genexus Application Exception
Machine: MACHINNENAME
Application Domain: GeneXus.exe
Process Id: 6420
Process Name: C:\Program Files (x86)\GeneXus\GeneXus18\GeneXus.exe
Win32 Thread Id: 3696
Thread Name:
Extended Properties: AdvancedInformation.Product - GeneXus 18
AdvancedInformation.Version - 18.0.167910 U1
Exception.Severity - Error

Heroku successful deploy but receiving error on opening the app

I have deployed a DotNet Core application on Heroku but I m receiving the following error when I'm trying to open the application
fail: ShopApi.Program[0]
An error occurred while migrating the database.
Npgsql.PostgresException (0x80004005): 28000: no pg_hba.conf entry for host "3.249.151.147", user "ddojar225ki3s4", database "ddojar225ki3s4", SSL off
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>c__DisplayClass41_0.<<Open>g__OpenAsync|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnection.Open()
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at ShopApi.Extensions.MigrateDatabaseExtension.MigrateDatabase[T](IHost webHost) in /src/ShopApi/Extensions/MigrateDatabaseExtension.cs:line 22
Exception data:
Severity: FATAL
SqlState: 28000
MessageText: no pg_hba.conf entry for host "3.249.151.147", user "ddojar225ki3s4", database "ddojar225ki3s4", SSL off
File: auth.c
Line: 496
Routine: ClientAuthentication
I have added an Add-On for Postgresql.
I am connecting to the database like this :
services.AddDbContext<DataContext>(optionsBuilder =>
optionsBuilder.UseNpgsql(Configuration.GetConnectionString("PostgresSqlDatabaseConnection")));
My Connection String
"PostgresSqlDatabaseConnection": "User ID=ddojar225ki3s4;Password=correct_password;Server=ec2-34-242-89-204.eu-west-1.compute.amazonaws.com;Port=5432;Database=ddojar225ki3s4;Integrated Security=true; Pooling=true"
Solution
I had to add
SSL Mode=Require; to the connection string.
Be careful NOT to type Required or SSL Mode=SSL.Require

ELK serilog sink FailureCallback

I was able to successfully integrate the elastic search sink in my .net app, now I am trying to setup the FailureCallback option but every time there is an error the exception in LogEvent is null, I can see the actual error in the console but I want to be able to capture this exception in my failure callback function, here is my current configuration:
myLogger = new LoggerConfiguration()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticSearchUrl))
{
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
IndexDecider = (#event, dateTimeOffset) =>
{
//some logic here
return $"custom-index";
},
EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog | EmitEventFailureHandling.RaiseCallback,
FailureCallback = HandleElasticError
})
.Enrich.WithProperty("Environment", Config.Environment)
.Destructure.ByTransforming<ExpandoObject>(JsonConvert.SerializeObject)
.CreateLogger();
Here is my HandleElasticError function:
private void HandleElasticError(LogEvent e)
{
FileLogger.Error(e.Exception, e.MessageTemplate.Text, e.Properties);
}
When I attach the debugger and inspect the LogEvent, exception is null, however in the output window in Visual Studio I can see the actual error:
2020-11-30T20:55:07.7820674Z Caught exception while preforming bulk operation to Elasticsearch: Elasticsearch.Net.ElasticsearchClientException: The underlying connection was closed: An unexpected error occurred on a send.. Call: Status code unknown from: POST /_bulk ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
I am not concerned about the error, I know what the issue is, I just want to be able to capture this exception in my failure callback function.
Any ideas?
LogEvent.Exception is the Exception shipped with your call to (for example) logger.Error(myException) - not the exception thrown by failure to write to Elastic Search.
The exception you're trying to catch doesn't look to be exposed by the sink as it just passes the LogEvent to FailureCallback and not exception that caused the failure.
Here's what it could look like were the exception exposed.
you can use:
StreamWriter writer = File.CreateText(...);
Serilog.Debugging.SelfLog.Enable(writer);

How to use Rebus in combination with OracleDB

I am trying to make Rebus work on Oracle DB but I keep getting errors.
I have the following configuration in my Startup:
In the ConfigureServices
services.AutoRegisterHandlersFromAssemblyOf<NewActionRequestMessageHandler>();
services.AddRebus(configure => configure
.Logging(l => l.Serilog())
.Transport(t => t.UseOracle(connectionString, "QueueTable", "Queue"))
.Routing(r => r.TypeBased()
.Map<NewActionRequestMessage>("Queue")
.Map<RevokeActionRequestMessage>("Queue"))
.Subscriptions(s => s.StoreInOracle(connectionString, "Subscriptions")));
In the Configure
var bus = app.ApplicationServices.GetRequiredService<IBus>();
app.ApplicationServices.UseRebus();
bus.Send(new NewActionRequestMessage());
The error I get is:
[11:55:48] Alpha event ID: Partition ID: - An error occurred when attempting to receive the next message: "Rebus.Exceptions.RebusApplicationException: Could not 'GetOrAdd' item with key 'oracle-transport-connection' as type Rebus.Oracle.UnitOfWork
---> System.MissingMethodException: Method not found: 'Void Rebus.Transport.ITransactionContext.OnCommitted(System.Func1<System.Threading.Tasks.Task>)'. at Rebus.Oracle.Transport.TransactionContextExtensions.<>c__DisplayClass2_0.<GetConnection>b__0() at Rebus.Transport.TransactionContextExtensions.<>c__DisplayClass2_01.b__0(String id)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Rebus.Transport.TransactionContextExtensions.GetOrAdd[TItem](ITransactionContext context, String key, Func1 newItemFactory) --- End of inner exception stack trace --- at Rebus.Transport.TransactionContextExtensions.GetOrAdd[TItem](ITransactionContext context, String key, Func1 newItemFactory)
at Rebus.Oracle.Transport.TransactionContextExtensions.GetConnection(ITransactionContext context, OracleFactory factory)
at Rebus.Oracle.Transport.OracleTransport.Receive(ITransactionContext context, CancellationToken cancellationToken)
at Rebus.Workers.ThreadPoolBased.ThreadPoolWorker.ReceiveTransportMessage(CancellationToken token, ITransactionContext context)"
Help?

Testing my Xamarin.Forms iOS Application with Xamarin.UITest: The first test always fails

I am testing an Xamarin.iOS Application on a real device (iPhone 6s with iOS 12.1) with Xamarin.UITest.
When I am running my few UI Tests, the first test always seam to crash (regardless of what is happening inside the test) due to the same error (see below).
Enviroment is:
Xamarin.UITest 2.2.7
NUnitTestAdapter 2.1.1
NUnit 2.6.3
Xamarin.TestCloud.Agent 0.21.7
Setup is:
[SetUp]
public void Setup(){
this.app = ConfigureApp.iOS
.EnableLocalScreenshots()
.InstalledApp("my.app.bundle")
.DeviceIdentifier("My-iPhone6s-UDID-With-iOS12.1")
.StartApp();
}
[Test]
public void FirstTestThatCouldBeEmpty(){
//But doesn't have to be empty to produce the error
}
Resulting error:
2019-01-17T14:11:20.4902700Z 1 - ClearData:> 2019-01-17T14:11:20.4916340Z bundleId: my.app.bundle
2019-01-17T14:11:20.4929580Z deviceId: My-iPhone6s-UDID-With-iOS12.1
2019-01-17T14:11:33.7561260Z 3 - LaunchTestAsync:
2019-01-17T14:11:33.7574050Z deviceId: My-iPhone6s-UDID-With-iOS12.1
2019-01-17T14:11:33.9279420Z 5 - HTTP request failed, retry limit hit
2019-01-17T14:11:33.9302300Z Exception: System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Unable to read data from the transport connection: Connection reset by peer. ---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer. ---> System.Net.Sockets.SocketException: Connection reset by peer
2019-01-17T14:11:33.9322710Z at System.Net.Sockets.Socket.EndReceive (System.IAsyncResult asyncResult) [0x00012] in <23340a11bb41423aa895298bf881ed68>:0
2019-01-17T14:11:33.9340560Z at System.Net.Sockets.NetworkStream.EndRead (System.IAsyncResult asyncResult) [0x00057] in <23340a11bb41423aa895298bf881ed68>:0
2019-01-17T14:11:33.9358740Z --- End of inner exception stack trace ---
2019-01-17T14:11:33.9377100Z at System.Net.Sockets.NetworkStream.EndRead (System.IAsyncResult asyncResult) [0x0009b] in <23340a11bb41423aa895298bf881ed68>:0
2019-01-17T14:11:33.9398100Z at System.IO.Stream+<>c.b__43_1 (System.IO.Stream stream, System.IAsyncResult asyncResult) [0x00000] in <98fac219bd4e453693d76fda7bd96ab0>:0
2019-01-17T14:11:33.9415720Z at System.Threading.Tasks.TaskFactory1+FromAsyncTrimPromise1[TResult,TInstance].Complete (TInstance thisRef, System.Func`3[T1,T2,TResult] endMethod, System.IAsyncResult asyncResult, System.Boolean requiresSynchronization) [0x00000] in <98fac219bd4e453693d76fda7bd96ab0>:0
Sometimes it is this error:
SetUp : Xamarin.UITest.XDB.Exceptions.DeviceAgentException : Unable to end session: An error occurred while sending the request
System.Net.Http.HttpRequestException : An error occurred while sending the request
System.Net.WebException : Unable to read data from the transport connection: Connection reset by peer.
System.IO.IOException : Unable to read data from the transport connection: Connection reset by peer.
System.Net.Sockets.SocketException : Connection reset by peer
What could be a solution to this?
Doing the version puzzle of the nuget packages got me this far, that all tests are working besides this one.
A dummy test would be a possibility, but that would that countinous builds with those test would never be in the state of "successful" because this one test that is failing =(
I was able to find a work around for this issue, and really any issue with the device agent not connecting to the app under test.
public static IApp StartApp(Platform platform)
{
if (platform == Platform.iOS)
{
try
{
return ConfigureApp.iOS
.InstalledApp("com.example")
#if DEBUG
.Debug()
#endif
.StartApp();
}
catch
{
return ConfigureApp.iOS
.InstalledApp("com.example")
#if DEBUG
.Debug()
#endif
.ConnectToApp();
}
}
In plain language : "If you tried to start the app, and something went wrong, try to see if the app under test was started anyway and connect to it"
Note : As https://stackoverflow.com/users/1214857/iupchris10 mentioned in the comments, a caveat to this approach is that when you run tests consecutively, while the StartApp call will in theory reliably shut down the app, with the point of failure being reconnection, if it does not and you are running tests consecutively, you will simply connect to the running app instance in whatever state it was left in. This approach offers no recourse. Xamarin's StartApp will throw Exception, rather than a typed exception, and so mitigating this will rely on you parsing InnerException.Message and keeping a table of expected failures.

Resources