EventStore throws ConcurrencyException when using RavenDB - ravendb

My wire up looks like this.
return Wireup.Init()
.UsingRavenPersistence("RavenDB")
.ConsistentQueries()
.InitializeStorageEngine()
.UsingJsonSerialization()
.Build();
When I try to save an event, like this:
using (eventStore)
using (var stream = eventStore.CreateStream(myEvent.AggreagateId))
{
stream.Add(new EventMessage { Body = myEvent });
stream.CommitChanges(myEvent.Id);
}
It throws an EventStore.ConcurrencyException
I'm using eventstore 3.0 and RavenDB 2.0
What am I doing wrong?
Here is the stack trace:
EventStore.ConcurrencyException was unhandled by user code
HResult=-2146233088
Message=Exception of type 'EventStore.ConcurrencyException' was thrown.
Source=EventStore.Persistence.RavenPersistence
StackTrace:
at EventStore.Persistence.RavenPersistence.RavenPersistenceEngine.Commit(Commit attempt) in c:\Code\public\EventStore\src\proj\EventStore.Persistence.RavenPersistence\RavenPersistenceEngine.cs:line 135
at EventStore.OptimisticEventStore.Commit(Commit attempt) in c:\Code\public\EventStore\src\proj\EventStore.Core\OptimisticEventStore.cs:line 98
at EventStore.OptimisticEventStream.PersistChanges(Guid commitId) in c:\Code\public\EventStore\src\proj\EventStore.Core\OptimisticEventStream.cs:line 166
at EventStore.OptimisticEventStream.CommitChanges(Guid commitId) in c:\Code\public\EventStore\src\proj\EventStore.Core\OptimisticEventStream.cs:line 147
at TeamHabits.Web.Habit.CreateHabitModule.<>c__DisplayClass6.<.ctor>b__1(Object _) in c:\Users\Emil\Dropbox\Active projects\TeamHabits\Source\TeamHabits.Web\Habit\CreateHabitModule.cs:line 41
at Nancy.Routing.Route.Invoke(DynamicDictionary parameters)
at Nancy.Routing.DefaultRouteInvoker.Invoke(Route route, DynamicDictionary parameters, NancyContext context)
at Nancy.Routing.DefaultRequestDispatcher.Dispatch(NancyContext context)
InnerException:

Related

Mono.zip request fails when subscribed

I have the following piece of code, where externalgetcall is a GET request to a external service asking for some data
myservice.externalgetcall(id).blockOptional();
this code works, but if i get rid of the blockOptional and write the following, externalgetcall fails with a java.lang.NullPointerException:
java.lang.NullPointerException: null
at org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository.saveAuthorizedClient(HttpSessionOAuth2AuthorizedClientRepository.java:63) ~[spring-security-oauth2-client-5.7.2.jar:5.7.2]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint ? Request to GET
myservice.externalgetcall(id).subscribe();
moreover, if I do this, the blocking one right before the non blocking one, it works, so it clearly has to do with Oauth not completing somehow if the call is non blocking:
myservice.externalgetcall(id).blockOptional();
myservice.externalgetcall(id).subscribe();
externalgetcall(id)
public Mono<MyClass> externalgetcall(String id) {
logger.debug("getting contact: {}", id);
return this.webClient
.get()
.uri(externaluri)
.retrieve()
.bodyToMono(MyClass.class)
.doOnNext(myClass -> logger.debug("success {}", myClass))
.doOnError(throwable -> logger.error("error : ", throwable))
}
it fails at this point:
it looks like it happens when trying to run the setAttribute method,when debugging i can see this:
this = {FluxSubscribeOnCallable$CallableSubscribeOnSubscription#13199} size = 1
Unable to evaluate the expression Method threw 'java.lang.UnsupportedOperationException' exception.
public final class HttpSessionOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository {
private static final String DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME = HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS";
private final String sessionAttributeName;
public HttpSessionOAuth2AuthorizedClientRepository() {
this.sessionAttributeName = DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME;
}
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, HttpServletRequest request, HttpServletResponse response) {
if (this.isPrincipalAuthenticated(principal)) {
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
} else {
this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, request, response);
}
}
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
This is not much context to come to a rock-solid explanation, but the NPE leads me to believe that this is a case of race condition.
Something to consider is the fact that you are replacing a blocking terminal operation with an asynchronous terminal operation on the publisher. blockOptional and subscribe both initiate a subscription, but in the latter case, execution will not wait at that point for the publisher's onComplete signal.
Again, hard to tell without the complete code, but my guess is that whatever code comes after this snippet is using some data that is populated or hydrated as a result of this publisher. Using blockOptional ensures that the publisher completes before this happens, while subscribe does not.

Apache Camel: How to get the exception message inside the doCatch() block?

I need to return the message from a thrown exception, or put it in the outmessage. But it does not print the correct message on the frontend.
The camel docs suggest using .transform(simple?...) .handled(true) but most of it is deprecated.
What's the correct way of doing this?
Response:
<418 I'm a teapot,simple{${exception.message}},{}>
Route
from("direct:csv")
.doTry()
.process(doSomeThingWithTheFileProcessor)
.doCatch(Exception.class)
.process(e -> {
e.getOut().setBody(new ResponseEntity<String>(exceptionMessage().toString(), HttpStatus.I_AM_A_TEAPOT));
}).stop()
.end()
.process(finalizeTheRouteProcessor);
doSomethingWithFileProcessor
public void process(Exchange exchange) throws Exception {
String filename = exchange.getIn().getHeader("CamelFileName", String.class);
MyFile mf = repo.getFile(filename); //throws exception
exchange.getOut().setBody(exchange.getIn().getBody());
exchange.getOut().setHeader("CamelFileName", exchange.getIn().getHeader("CamelFileName"));
}
There is a lot of ways how to do it. All of it is correct, choose your favourite depending on complexity of error handling. I have published examples in this gist. None of it is deprecated in Camel version 2.22.0.
With Processor
from("direct:withProcessor")
.doTry()
.process(new ThrowExceptionProcessor())
.doCatch(Exception.class)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
final Throwable ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
exchange.getIn().setBody(ex.getMessage());
}
})
.end();
With Simple language
from("direct:withSimple")
.doTry()
.process(new ThrowExceptionProcessor())
.doCatch(Exception.class)
.transform().simple("${exception.message}")
.end();
With setBody
from("direct:withValueBuilder")
.doTry()
.process(new ThrowExceptionProcessor())
.doCatch(Exception.class)
.setBody(exceptionMessage())
.end();
In the doCatch() Camel moves the exception into a property on the exchange with the key Exchange.EXCEPTION_CAUGHT (http://camel.apache.org/why-is-the-exception-null-when-i-use-onexception.html).
So you can use
e.getOut().setBody(new ResponseEntity<String>(e.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class).getMessage(), HttpStatus.OK));

The resource identifier failed to decrypt

We are hosting a site that has sitefinity, the site is crashing frequently and getting the error given below:
============================
Event code: 3012
Event message: An error occurred processing a web or script resource request. The resource identifier failed to decrypt.
Event time: 8/4/2016 1:09:19 PM
Event time (UTC): 8/4/2016 6:09:19 PM
Event ID: 9ed7856e9baa479f944599104bda8f46
Event sequence: 1265
Event occurrence: 6
Event detail code: 0
Exception information:
Exception type: HttpException
Exception message: Unable to validate data.
at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo, Boolean useLegacyMode, IVType ivType, Boolean signData)
at System.Web.UI.Page.DecryptString(String s, Purpose purpose)
at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
Stack trace: at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo, Boolean useLegacyMode, IVType ivType, Boolean signData)
at System.Web.UI.Page.DecryptString(String s, Purpose purpose)
at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
+++++++++++++++++
I have already implemented the steps given in the URL:
http://www.sitefinity.com/developer-network/forums/general-discussions-/event-code-3012
Please let me know if you need any additional logs
Please advice.
Regards,
Set machine decryption key same at all application servers.
https://msdn.microsoft.com/en-us/library/w8h3skw9(v=vs.100).aspx

NHibernate Validator throws System.NotSupportedException after upgrading to 3.1

Has anyone encountered this?
After upgrading to NHibernate 3.1, I am receiving the following exception from NHibernate Validator when running NUnit test cases:
System.NotSupportedException : The invoked member is not supported in
a dynamic assembly. at
System.Reflection.Emit.InternalAssemblyBuilder.GetManifestResourceStream(String
name) at
NHibernate.Validator.Cfg.XmlMappingLoader.AddResource(Assembly
assembly, String resource) at
NHibernate.Validator.Cfg.XmlMappingLoader.GetXmlMappingFor(Type type)
at
NHibernate.Validator.Engine.JITClassMappingFactory.GetExternalDefinitionFor(Type
type) at
NHibernate.Validator.Engine.JITClassMappingFactory.GetClassMapping(Type
clazz, ValidatorMode mode) at
NHibernate.Validator.Engine.ClassValidator.InitValidator(Type clazz,
IDictionary`2 nestedClassValidators) at
NHibernate.Validator.Engine.ClassValidator..ctor(Type clazz,
IConstraintValidatorFactory constraintValidatorFactory, IDictionary`2
childClassValidators, IClassValidatorFactory factory) at
NHibernate.Validator.Engine.StateFullClassValidatorFactory.GetRootValidator(Type
type) at
NHibernate.Validator.Engine.ValidatorEngine.GetClassValidator(Type
entityType) at
NHibernate.Validator.Engine.ValidatorEngine.GetElementOrNew(Type
entityType) at
NHibernate.Validator.Engine.ValidatorEngine.InternalValidate(Object
entity, Object[] activeTags) at
NHibernate.Validator.Engine.ValidatorEngine.Validate(Object entity,
Object[] activeTags) at
NHibernate.Validator.Event.ValidateEventListener.Validate(Object
entity, EntityMode mode) at
NHibernate.Validator.Event.ValidatePreUpdateEventListener.OnPreUpdate(PreUpdateEvent
event) at NHibernate.Action.EntityUpdateAction.PreUpdate() in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Action\EntityUpdateAction.cs:
line 200 at NHibernate.Action.EntityUpdateAction.Execute() in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Action\EntityUpdateAction.cs:
line 58 at NHibernate.Engine.ActionQueue.Execute(IExecutable
executable) in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\ActionQueue.cs: line
136 at NHibernate.Engine.ActionQueue.ExecuteActions(IList list) in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\ActionQueue.cs: line
126 at NHibernate.Engine.ActionQueue.ExecuteActions() in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\ActionQueue.cs: line
170 at
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource
session) in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\AbstractFlushingEventListener.cs:
line 241 at
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent
event) in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultFlushEventListener.cs:
line 19 at NHibernate.Impl.SessionImpl.Flush() in
d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs: line
1472 at TestDataAccess.FooTest.TestFoo() in FooTest.cs
As you can see from the stack trace, the error occurs when the session is flushed and NHibernate Validator does its thing.
Update I have tried stepping through the NH Validator code and it appears that at some point it is trying to validate the Castle proxy of an entity, rather than the underlying entity itself. This then causes the trouble. No idea what to do about this...
Update The problem goes away if I use the LinFu ProxyFactoryFactory, rather than Castle. Unfortunately, LinFu is giving me other problems so I don't want to use it.
NHibernate 3.2 removed the need for external proxy libraries.
They are still supported, but they are not distributed anymore, and the default is to use an internal implementation.
Have you tried upgrading?
Update: in order to compile NHibernate Validator for NH 3.2, you need to modify NHibernateHelper as follows:
public static bool IsProxyFactoryConfigurated()
{
var f = NHibernate.Cfg.Environment.BytecodeProvider.ProxyFactoryFactory;
return f != null;
}
For details, read NHV-116

Retrieving parameter values using Microsoft Enterprise Library Exception Handler

We are using Enterprise Library for all our logging and exception handling needs in our app. We have added an email listener to send all the caught exceptions in email to the administrator. One requirement is that when an exception occurs in a method we need to retrieve the parameter values of the method if any and attach it to the exception details in the email sent. Is it possible without writing a custom logger?
Just create a custom exception, setting the message to the parameters:
try {
...
} catch(Exception ex) {
var customException = new CustomException(ex, string.format("Param1 {0}, Param2 {1}", param1, param2));
bool rethrow = ExceptionPolicy.HandleException(customException, PolicyName);
}
verified that in fact the ExceptionFormatter class will indeed traverse all inner exceptions, so your CustomException could be as simple as
public class CustomException : Exception
{
public CustomException(string message, Exception innerException) : base(message, innerException)
{
}
}