Rebus Handler with TransactionScope - transactionscope

I have setup a Rebus handler with a Transaction Scope attached to it to MSMQ and RabbitMQ. The handler handles the first few messages 100%. After a couple of minutes when I try publish new messages to the queue I get the error message below....
What am I doing wrong?
[11:09:59 ERR] An error occurred when attempting to complete the transaction context
System.Transactions.TransactionAbortedException: The transaction has aborted.
---> System.TimeoutException: Transaction Timeout
--- End of inner exception stack trace ---
at System.Transactions.TransactionStateAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
at System.Transactions.CommittableTransaction.Commit()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
at Rebus.TransactionScopes.TransactionScopeTransportDecorator.<>c__DisplayClass7_0.<Receive>b__1(ITransactionContext ctx)
at Rebus.Transport.TransactionContext.Dispose()
at Rebus.Transport.TransactionContext.Complete()
at Rebus.Workers.ThreadPoolBased.ThreadPoolWorker.ProcessMessage(TransactionContext context, TransportMessage transportMessage)
// Initialize Class
_activator = new BuiltinHandlerActivator();
// Register
_activator.Register((context, handler) => new Handler(_activator.Bus));
// Configure
Configure.With(_activator)
.Logging(logging => logging.Serilog())
.Options(options =>
{
options.HandleMessagesInsideTransactionScope();
options.SimpleRetryStrategy(maxDeliveryAttempts: 1, secondLevelRetriesEnabled: true);
options.SetMaxParallelism(5);
options.SetNumberOfWorkers(5);
})

Related

Dynamodb nodejs client throws an exception and the exception is an empty object

I get this exception several times in the logs. I am using nodejs and the dynamodb client throws an exception when inserting an object. I have wrapped the code in try catch block and log the exception. But the exception is just an empty object. Any insights would be awesome.
try {
// documentClient is the instantiated dynamo client
await documentClient.put(params).promise();
} catch (e) {
console.log(e);
}

Getting Cannot access a disposed object. Object name: 'SocketsHttpHandler' exception in .Net 6 Application

In one of my Azure Function app(.Net 6 isolated process) and I am making some http requests with a client certificate. I'm registering my services in the Program.cs like this,
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);
services.AddHttpClient().Configure<HttpClientFactoryOptions>(
"myClient", options =>
options.HttpMessageHandlerBuilderActions.Add(builder =>
builder.PrimaryHandler = handler));
services.AddTransient<IMyCustomClient, MyCustomClient>(provider =>
new MyCustomClient(provider.GetService<IHttpClientFactory>(),
cutomParameter1, cutomParameter2));
services.AddSingleton<IMyCustomService, MyCustomService>();
And injecting MyCustomClient in MyCustomService constructor
private readonly IMyCustomClient _myCustomClient;
public PlatformEventManagementService(IMyCustomClient myCustomClient)
{
_myCustomClient = myCustomClient;
}
var result = await _myCustomClient.GetResponse();
It works fine for some time and getting the below exception after sending many requests.
Cannot access a disposed object. Object name: 'SocketsHttpHandler'.
You are supplying the factory with a single instance of HttpClientHandler to use in all clients. Once the default HandlerLifetime has elapsed (2 minutes) it will be marked for disposal, with the actual disposal occurring after all existing HttpClients referencing it are disposed.
All clients created after the handler is marked continue to be supplied the soon-to-be disposed handler, leaving them in an invalid state once the disposal is actioned.
To fix this, the factory should be configured to create a new handler for each client. You may wish to use the simpler syntax shown in the MS documentation.
// Existing syntax
services.AddHttpClient().Configure<HttpClientFactoryOptions>(
"myClient", options =>
options.HttpMessageHandlerBuilderActions.Add(builder =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);
builder.PrimaryHandler = handler;
}));
// MS extension method syntax
services
.AddHttpClient("myClient")
// Lambda could be static if clientCertificate can be retrieved from static scope
.ConfigurePrimaryHttpMessageHandler(_ =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);
return handler;
});

What is causing my DbUpdateConcurrencyException?

In my .NET Core Web API, I have implemented the transactional outbox pattern to monitor a database table and publish messages to an Azure Service Bus topic whenever a record appears in the database table. This takes place within a hosted service class that inherits from Microsoft.Extensions.Hosting.BackgroundService. This is a stripped-down version of what I have:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
IEnumerable<RelayMessage> messagesToSend = new List<RelayMessage>();
// _scopeFactory is an implementation of Microsoft.Extensions.DependencyInjection.IServiceScopeFactory:
using (var scope = _scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
while (!stoppingToken.IsCancellationRequested)
{
messagesToSend = await dbContext.RelayMessage.ToListAsync();
foreach (var message in messagesToSend)
{
try
{
await SendMessageToAzureServiceBus(message);
dbContext.RelayMessage.Remove(message);
dbContext.SaveChanges();
}
catch (Exception ex)
{
Log.Error(ex, $"Could not send message with id {message.RelayMessageId}.");
}
}
await Task.Delay(5000, stoppingToken);
}
}
await Task.CompletedTask;
}
catch (Exception ex)
{
Log.Error(ex, "Exception thrown while processing messages.");
}
The records are being deleted from the database, but the following exception gets thrown on the call to SaveChanges():
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(Int32 commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithoutPropagation(Int32 commandIndex, RelationalDataReader reader)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(RelationalDataReader reader)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at ReinsuranceReferenceSystemApi.Services.ServiceBus.ParticipantPublishingService.ExecuteAsync(CancellationToken stoppingToken)
I did check out the link in the exception message, but am not sure if the information applies to my situation. The RelayMessage instance is created and saved to the database (in a method not shown here), then this method reads it and deletes it. There aren't any modifications of this type anywhere in the application, so I'm unclear on how this could be a concurrency issue.
I'd appreciate any help.
EDIT:
Here's the registration of my DbContext in Startup.cs:
services.AddDbContext<MyDbContext>(o =>
{
o.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"));
});

Java.Net.SocketException Error: Socket closed in System.net.Http httpClient, occurs only when sending files larger than 50kbs

I am making a program in xamarin, which uses http requests to get data from an API made in net.core 2.0, but some requests (most of them actually) culminate in the following error:
System.AggregateException: One or more errors occurred. ---> Java.Net.SocketException: Socket closed
at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
at Java.Net.HttpURLConnection.get_ResponseCode () [0x0000a] in <b781ed64f1d743e7881ac038e0fbdf85>:0
at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass45_0.<DoProcessRequest>b__1 () [0x00000] in <b781ed64f1d743e7881ac038e0fbdf85>:0
at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at System.Threading.Tasks.Task.Execute () [0x00000] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
--- End of stack trace from previous location where exception was thrown ---
at Xamarin.Android.Net.AndroidClientHandler+<DoProcessRequest>d__45.MoveNext () [0x0036c] in <b781ed64f1d743e7881ac038e0fbdf85>:0
--- End of stack trace from previous location where exception was thrown ---
at Xamarin.Android.Net.AndroidClientHandler+<SendAsync>d__40.MoveNext () [0x00230] in <b781ed64f1d743e7881ac038e0fbdf85>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at System.Threading.Tasks.Task`1[TResult].get_Result () [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at FonoApp.Services.DataService.SendImageAsync (System.String token, FonoApp.Model.Imagem imagem) [0x00059] in C:\Projetos Sorri\FonoApp\AppTeste\AppTeste\Services\DataService.cs:154
--- End of inner exception stack trace ---}
This error occurs in this code snippet:
public async Task<String> SendImage(string token, Imagem imagem)
{
string baseAddress = #"http://192.168.0.4:5000/" + VersaoApi + #"/Imagem/";
var json = JsonConvert.SerializeObject(imagem);
var contentString = new StringContent(json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
try
{
HttpResponseMessage tokenResponse = client.PostAsync(baseAddress, contentString).Result;//Erro ocorre nesta linha
var jsonContent = tokenResponse.Content.ReadAsStringAsync().Result;
return jsonContent;
}
catch (Exception e)
{
return e.InnerException.Message.ToString();
}
}
From what I researched, and discovered from this error, means that the connection is being closed either by the server or by the client, but I can't even know who closes the connection suddenly let alone prevent this / exception error, I don't know if it matters but I am testing the app on an android 4.2-API 17 tablet. Thanks in advance for any guidance on this as I am still learning how to program in C #.
one thing I forgot to say before was that Postman API requests work without problems
I noticed something interesting the error I get only occurs when trying to send images larger than 100 kb by http request, how can I increase the send and receive weight limit on my server?
Firstly, you need to use await instead of Result() to make this method async:
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
And yes, this exception occurs when internet connection is lost. You can do these things to make your app more usable:
Display a warning message in try-catch block
Check internet connection by using Xamarin.Essentials.Connectivity plugin
Set a timeout for your HttpClient object and catch the TimeoutException to display proper message

CRM 2011 Dicovery Service FaultException

I have asked the same question at http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/d5d00302-8f7b-4efc-873b-c54b3e29749d but didn't get an answer. So, I will give another try at stackoverflow.
I was running the example code from the crm 2011 training kit.
var creds = new ClientCredentials();
var dsp = new DiscoveryServiceProxy( dinfo, creds);
dsp.Authenticate();
var orgRequest = new RetrieveOrganizationRequest();
var response = dsp.Execute(orgRequest);
var orgResponse = response as RetrieveOrganizationsResponse;
if (orgResponse != null)
comboOrgs.ItemsSource = orgResponse.Details;
At the line of var response = dsp.Execute(orgRequest), I got the FaltException`1, the detailed message is as follows
System.ServiceModel.FaultException`1 was unhandled
Message=organizationName
Source=mscorlib
Action=http://schemas.microsoft.com/xrm/2011/Contracts/Discovery/IDiscoveryService/ExecuteDiscoveryServiceFaultFault
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
at Microsoft.Xrm.Sdk.Client.DiscoveryServiceProxy.Execute(DiscoveryRequest request)
I was able to access the Discovery.svc file using browser. So the server url should be correct. Is this an authentication problem?
Is this for Microsoft CRM Online or on-premise? For Online, I know you would want to use something along the lines of what is found in the SDK -
// Connect to the Discovery service.
// The using statement assures that the service proxy will be properly disposed.
using (DiscoveryServiceProxy _serviceProxy = new DiscoveryServiceProxy(serverConfig.DiscoveryUri,
serverConfig.HomeRealmUri,
serverConfig.Credentials,
serverConfig.DeviceCredentials))
{
// You can choose to use the interface instead of the proxy.
IDiscoveryService service = _serviceProxy;
#region RetrieveOrganizations Message
// Retrieve details about all organizations discoverable via the
// Discovery service.
RetrieveOrganizationsRequest orgsRequest =
new RetrieveOrganizationsRequest()
{
AccessType = EndpointAccessType.Default,
Release = OrganizationRelease.Current
};
RetrieveOrganizationsResponse organizations =
(RetrieveOrganizationsResponse)service.Execute(orgsRequest);
}
There are overloads for the DiscoveryServiceProxy class but if you provide some more details on what you are trying to connect to, I think it will narrow it down.

Resources