Google Analytics Mapping Exception - exception

I am new to Google Analytics and trying to integrate it with my windows phone app. I followed the steps like creating a tracking ID, installing the nuget package and editing the information in analytics.xaml.
<?xml version="1.0" encoding="utf-8" ?>
<analytics xmlns="http://googleanalyticssdk.codeplex.com/ns/easytracker">
<trackingId>UA-49305542-1</trackingId>
<appName>MyPhoneApp</appName>
<appVersion>1.0.0.0</appVersion>
</analytics>
I even added a tracker in my app initializer
GoogleAnalytics.EasyTracker.GetTracker().SendView("MainPage");
When I try to execute the code in emulator, I am getting an exception. Details below
Message :
An attempt to override an existing mapping was detected for type GoogleAnalytics.Core.IPlatformInfoProvider with name "", currently mapped to type GoogleAnalytics.Core.PlatformInfoProvider, to type GoogleAnalytics.PlatformInfoProvider.
Stack Trace :
at Microsoft.Practices.Unity.UnityContainerRegistrationByConventionExtensions.RegisterTypeMappings(IUnityContainer container, Boolean overwriteExistingMappings, Type type, String name, IEnumerable1 fromTypes, Dictionary2 mappings)
at Microsoft.Practices.Unity.UnityContainerRegistrationByConventionExtensions.RegisterTypes(IUnityContainer container, IEnumerable1 types, Func2 getFromTypes, Func2 getName, Func2 getLifetimeManager, Func`2 getInjectionMembers, Boolean overwriteExistingMappings)
at MyPhoneApp.IocContainer.AppContainer.RegisterMySdk()
at MyPhoneApp.IocContainer.AppContainer.Initialize(Frame rootFrame, DataContext dataContext)
at MyPhoneApp.App.d_5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.b_0(Object state)
can someone help me in fixing this?

Unity Container provides an option to override the default behavior.
App.Container.RegisterTypes(
AllClasses.FromApplication(),
WithMappings.FromMatchingInterface,
WithName.Default,
overwriteExistingMappings:true);
Adding the extra parameter solved the problem.

Related

MSBuild stuck on packages restore and sometimes throws exception

It stuck at Determining projects to restore...
Stack trace of the exception:
Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: enumType
at System.Enum.ToObject(Type enumType, Int32 value)
at Microsoft.Build.BackEnd.BinaryTranslator.BinaryReadTranslator.TranslateEnum[T](T& value, Int32 numericValue)
at Microsoft.Build.BackEnd.BinaryTranslator.BinaryReadTranslator.Translate(DateTime& value)
at Microsoft.Build.Shared.LogMessagePacketBase.ReadEvaluationEvent(ITranslator translator)
at Microsoft.Build.Shared.LogMessagePacketBase.ReadProjectEvaluationStartedEventFromStream(ITranslator translator)
at Microsoft.Build.Shared.LogMessagePacketBase.ReadEventFromStream(LoggingEventType eventType, ITranslator translator)
at Microsoft.Build.Shared.LogMessagePacketBase.ReadFromStream(ITranslator translator)
at Microsoft.Build.BackEnd.LogMessagePacket.FactoryForDeserialization(ITranslator translator)
at Microsoft.Build.BackEnd.NodePacketFactory.PacketFactoryRecord.DeserializeAndRoutePacket(Int32 nodeId, ITranslator translator)
at Microsoft.Build.BackEnd.NodePacketFactory.DeserializeAndRoutePacket(Int32 nodeId, NodePacketType packetType, ITranslator translator)
at Microsoft.Build.BackEnd.NodeProviderOutOfProcBase.NodeContext.ReadAndRoutePacket(NodePacketType packetType, Byte[] packetData, Int32 packetLength)
at Microsoft.Build.BackEnd.NodeProviderOutOfProcBase.NodeContext.BodyReadComplete(IAsyncResult result)
at System.IO.Pipes.PipeStream.AsyncPSCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
It is Visual Studio 2022, exception happens not each time. Also it can successfully continue building if command executed once again. What can it be and what can I check?
UPDATE
Probably I need to tell that it is virtual guest (host is VMWare Workstation). If VM is running on PC with i6700 it works fine. In case of 5950x it fails. It looks like PC is too fast for MSBuild or it is some other hardware related issue. VM is identical absolutely (I copied it from PC with AMD CPU). Can it be bug of VS and some sort of race condition?
I have added /maxcpucount:1 to temporarily workaround the issue. In original settings it was 8 (as cores in VM).
I have tested also /maxcpucount:2 it works fine as well.

How to fix Glass Mapper error - failed to find configuration for parent item type?

I have a Sitecore 8.1 CD instance. I also have some code that needs to create a content item in the Master database. (I am aware that is a no-no but I just need to figure this out at the moment) When my code attempts to use Glass Mapper to create a content item I get an error. Here is the code snippet and the error message. I am just trying to understand what the error means. I have a sense that this is simply a configuration problem. This code works fine on our Sitecore CM server. So I am hoping that by simply adjusting the config on our CD server I can get this to work. So far I have re-enabled the Master entry in ConnectionStrings.config and in Sitecore.config. But that hasn't fixed this.
SitecoreService service = new SitecoreService("master");
SimpleAes aes = new SimpleAes();
using (new SecurityDisabler())
{
Item parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses");
newAddress = service.Create(parentItem, newAddress); //THIS IS WHERE THE CODE FAILS
user.Addresses.Add(newAddress);
Utility.PublishItem(service.ResolveItem(newAddress));
id = aes.EncryptToString(newAddress.Id.ToString());
user.Addresses = user.Addresses;
user.Save();
}
Error Message:
Glass.Mapper.MapperException: Failed to find configuration for parent
item type Sitecore.Data.Items.Item ---> System.NullReferenceException:
Object reference not set to an instance of an object. at
System.Object.GetType() at
Glass.Mapper.Context.GetTypeConfiguration[T](Object obj, Boolean
doNotLoad, Boolean checkBase) at
Glass.Mapper.Sc.SitecoreService.Create[T,TK](TK parent, T newItem,
Boolean updateStatistics, Boolean silent) --- End of inner exception
stack trace --- at Glass.Mapper.Sc.SitecoreService.Create[T,TK](TK
parent, T newItem, Boolean updateStatistics, Boolean silent)
It is failing on this line
Item parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses");
if you put a check around it saying
if (parentItem != null) { // your code }
Then the code will work through and you will not get exception, but nothing will happen as well if parentItem is null.
Quick fix solution will be to give a 'master' DB connection string on your CD server (which is a no-no as you said). Better solution will be to expose master database through Sitecore Item API or your custom API, securing it through authentication and then calling this code from CD server via API.
I am not sure if you still are looking how to solve this issue, but when I faced today with it I found your question.
Problem is that your parentItem has type Item. It causes issue inside in Glass.
You can use any type as parent, but limitation is that it should not be inherited from Sitecore Item class.
Try this:
var parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses").GlassCast<BaseSitecoreItem>();
newAddress = service.Create(parentItem, newAddress);
where BaseSitecoreItem is some your Glass Model.
It helped me and hope will help you.

Adding a link to an invoice into a notification message

I have a screen with a form contaning invoices I want to notify the user with. The screen is used as bodyScreenLocation for the EmailTemplate. Up to here, it works. I wanted to add a link for each invoice so that the user can open the document right from withing the message. How to construct the path? This way it does not work:
This field is created in a form, that is included in a screen. This screen is used in a template called using
<service-call name="org.moqui.impl.EmailServices.send#EmailTemplate" async="true">
Added 18.10.2016
I attempted to use your advice.
<actions>
<entity-find entity-name="mantle.account.invoice.Invoice" list="invoiceList"/>
<script>
import org.moqui.impl.context.WebFacadeImpl
def httpUrl = WebFacadeImpl.getWebappRootUrl('webroot',null,false,false,ec)
</script>
</actions>
This is the log:
21:47:18.996 WARN oquiWorker-2 o.moqui.i.c.TransactionFacadeImpl Transaction set rollback only. The rollback was originally caused by: Error rendering screen [component://HS-data/screen/Notification/PayablesDue.xml]
java.lang.NullPointerException: null
at org.moqui.impl.context.WebFacadeImpl.makeWebappHost(WebFacadeImpl.groovy:477) ~[moqui-framework-2.0.0.jar:2.0.0]
at org.moqui.impl.context.WebFacadeImpl.makeWebappRootUrl(WebFacadeImpl.groovy:520) ~[moqui-framework-2.0.0.jar:2.0.0]
at org.moqui.impl.context.WebFacadeImpl.getWebappRootUrl(WebFacadeImpl.groovy:467) ~[moqui-framework-2.0.0.jar:2.0.0]
at org.moqui.impl.context.WebFacadeImpl$getWebappRootUrl.call(Unknown Source) ~[?:?]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) ~[groovy-2.4.7.jar:2.4.7]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) ~[groovy-2.4.7.jar:2.4.7]
at PayablesDue_xml_screen_actions.run(PayablesDue_xml_screen_actions:11) ~[script:?]
What you're looking for is the WebFacade.getWebappRootUrl() method. Use a call that is something like this in your template to get the base URL:
ec.web.getWebappRootUrl(true, null)
When there is no WebFacade in place, such as when running in an async service, you'll have to drop a level lower and there is a static method in WebFacadeImpl for this (it's not so convenient when you don't have the standard interfaces to go through), here is the method signature:
String getWebappRootUrl(String webappName, String servletContextPath, boolean requireFullUrl, Boolean useEncryption, ExecutionContextImpl eci)
The standard webappName is 'webroot' and unless you're doing something fancy in your Moqui Conf XML file this can be a static String. The servletContextPath can be null or an empty String if your Moqui webapp is mounted on the root (commonly the case; without a request where we can get to the ServletContext to see where it is mounted this can't be determined automatically).

org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs)

I have a hibernate and JSF2 application going to the deployment server and suddenly throwing an org.hibernate.AssertionFailure: null id in exception. I will provide the stack trace and code immediately but here are four important issues first:
This happens only on the deployment server (Jboss & MySql running on Windows Sever 2008.) It does not happen on my development machine (Tomcat and MySql running on Windoes 7 Pro) and also not on the staging environment (Jboss and MySql running on Linux.)
Researching this, it seems that people get this error when trying to insert an object. But I get the error when I'm doing a simple query. (various different queries, actually, as the error pops up on several pages randomly.)
The error hits only every now and then. If I do a Jboss restart it goes away, but a time later returns. Also, it's not consistent, on some clicks it's there, on others it's not. Even when it hits, when I do a simple refresh of the page it returns fine.
I'm using c3p0 (config below)
Any idea what's going on?
The code details:
This happens on an address object. Here's the full hbm:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.idex.auctions.model">
<class name="Address" table="address" lazy="true">
<id name="addressID" column="AddressID">
<generator class="native"/>
</id>
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="zip" column="zip"/>
<property name="state" column="state"/>
<property name="region" column="region"/>
<property name="country" column="country"/>
<many-to-one name="user"
class="com.idex.auctions.model.User"
column="userid"
unique="true"
cascade="save-update"/>
</class>
</hibernate-mapping>
The Java class is straight forward:
public class Address implements Serializable {
private static final long serialVersionUID = 7485582614444496906L;
private long addressID;
private String street;
private String city;
private String zip;
private String state;
private String region;
private String country;
private User user;
public Address() {
}
public long getAddressID() {
return addressID;
}
public void setAddressID(long addressID) {
this.addressID = addressID;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
The c3p0 configuration:
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">1000</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
The versions used are
hibernate3.jar
c3p0-0.9.1.2.jar
myfaces-api-2.1.4.jar
myfaces-impl-2.1.4.jar
mysql-connector-java-5.1.20-bin.jar
The full stacktrace
org.hibernate.AssertionFailure: null id in com.idex.auctions.model.Address entry
(don't flush the Session after an exception occurs)
org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(
DefaultFlushEntityEventListener.java:78)
org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(
DefaultFlushEntityEventListener.java:187)
org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(
DefaultFlushEntityEventListener.java:143)
org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(
AbstractFlushingEventListener.java:219)
org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(
AbstractFlushingEventListener.java:99)
org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(
DefaultAutoFlushEventListener.java:58)
org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:997)
org.hibernate.impl.SessionImpl.list(SessionImpl.java:1142)
org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
com.idex.auctions.manager.DatabaseManager.getAllObjects(DatabaseManager.java:464)
com.idex.auctions.ui.NavBean.gotoHome(NavBean.java:40)
sun.reflect.GeneratedMethodAccessor350.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:735)
javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246)
org.apache.el.parser.AstValue.getValue(AstValue.java:159)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
org.apache.myfaces.view.facelets.el.ContextAwareTagValueExpression.getValue(
ContextAwareTagValueExpression.java:96)
javax.faces.component._DeltaStateHelper.eval(_DeltaStateHelper.java:246)
javax.faces.component.UIOutcomeTarget.getOutcome(UIOutcomeTarget.java:50)
org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils.getOutcomeTargetHref(
HtmlRendererUtils.java:1542)
org.apache.myfaces.shared.renderkit.html.HtmlLinkRendererBase.renderOutcomeLinkStart(
HtmlLinkRendererBase.java:908)
org.apache.myfaces.shared.renderkit.html.HtmlLinkRendererBase.encodeBegin(
HtmlLinkRendererBase.java:143)
javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:502)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:744)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(
FaceletViewDeclarationLanguage.java:1900)
org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:285)
com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(
PrettyViewHandler.java:163)
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:59)
org.apache.myfaces.tomahawk.application.ResourceViewHandlerWrapper.renderView(
ResourceViewHandlerWrapper.java:93)
com.idex.auctions.ui.CustomViewHandler.renderView(CustomViewHandler.java:98)
org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:115)
org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:241)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:199)
com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:126)
com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118)
The exception:
org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs)
Tells us that the session exception has happened before the point where this org.hibernate.AssertionFailure is thrown.
To be exact, the org.hibernate.AssertionFailure is thrown when the session.flush() is happening, not the point where the error ocurred.
The above is a fact, thus a possible conclusion from it is: something could be suppressing the original exception.
So look for other possible points of error: A save() or saveOrUpdate() is possibly trying to persist an entity with a null field where, in the table, the column is NOT NULL?
TIP:
To help in the debugging, try adding a session.flush() after every interaction with the Session object (e.g. session.save(obj), session.merge(obj), etc.), this will hopefully cause the org.hibernate.AssertionFailure to happen earlier, closer to where the real problem is taking place. (Of course, after the debugging, remove those session.flush().)
In my case, the **real** exception was taking place inside a `try/catch {}` block where the `catch` suppressed the exception (didn't rethrow or warn me about it).
I would bet for a concurrency issue but it may occur at different levels:
a hibernate session may be shared between different users if the classical "open session in view" pattern is not properly implemented
an entity is shared between two user sessions because of improper hibernate cache settings
a JDBC connection is shared between two different hibernate session (less likely)
Apart from these potential sources of troubles, I would remove c3p0 (maybe just rumors...) as your stack already provides DataSource with connection pooling integrated with the transaction manager.
The #asdcjunior has answered correctly. Something has happened before the exception is thrown.
In that kind of situations (it happens often on integration tests when you dealing with single transaction for one test - for example #Transaction annotation) I'm invoking the method:
session.clear()
It helps because all the 'dirty' objects are removed from current session so when the next flush is executed the problem does not appear.
Example flow:
insert the assignment entity (many-to-many relation with constraint that could exist only single assignment) -> everything ok
insert the same assignment entity one more time -> everything ok, controller in this case return some kind of bad request exception, under the hood Spring throws the IntegrityViolationException -> in test everything looks ok
get the repository and execute findAll().size() to check the count of existed assigned to be sure that we have only single assignment -> the mentioned exception is thrown ;/ what happend? on the session exist still dirty object, normally the session would be destroyed (controller return error) but here we have the next assertions to check regarding database, so the solution here is additional session.clear() before next db related method executions
Example correct flow:
insert the assignment entity
insert the same assignment entity
session.clear()
get the repository and execute findAll().size()
Hope it helps ;)
You are probably hitting some Hibernate bug. (I'd recommend upgrading to at least Hibernate 3.3.2.GA.)
Meanwhile, Hibernate does better when your ID is nullable so that Hibernate can always tell the difference between a new object that has not yet been persisted to the database and one that's already in the database. Changing the type of addressID from long to Long will probably work around the problem.
The stack trace you provided shows that you are seeing the problem on a query because your query is forcing buffered writes to be flushed to the database before the query is executed and that write is failing, probably with the same insert problem other people are seeing.
I was facing this issue
I just add try catch block and in catch block I wrote seesion.clear();
now I can proceed with the rest of records to insert in database.
OK, I continued researching based among other things on other answers in this thread. But in the end, since we were up against a production deadline, I had to choose the emergency rout. So instead of figuring out hibernate I did these two things:
Removed a jQuery library I was using to grab focus on one of the forms. I did this because I read somewhere that this type of bug may happen due to a form posting a null value -- causing the null id down the line. I suspected the jQuery library may not sit well with PrimeFaces, and cause some form to malfunction. Just a hunch.
I killed the hibernate implemented relationship I had between user and address. (just one required, not one to many) and wrote the code myself when needed. Luckily it only affected one page significantly, so it wasn't much work.
The bottom line: we went live and the application has been running for several days without any errors. So this solution may not be pretty -- and I'm not proud of myself -- but I have a running app and a happy client.
Problem flow :
You create a new transient entity instance (here an Address instance)
You persist it to the database (using save, merge or persist in hibernate Session / JPA EntityManager)
As the entity identifier is generated by the database hibernate has to trigger the database insertion (it flushes the session) to retrieve the generated id
The insert operation trigger an exception (or any pending unflushed change in the session)
You catch the exception (without propagating it) and resume the execution flow (at this point your session still contains the unpersisted instance without the id, the problem is that hibernate seems to consider the instance as managed but the instance is corrupted as a managed object must have an id)
you reach the end of your unit of work and the session is automatically flushed before the current transaction is committed, the flush fails with an assertion failure as the session contains a corrupted instance
You have many possible ways to mitigate this error :
Simplest one and as hibernate stands "don't flush the Session after an exception occurs" ie. immediately give up and roll back the current transaction after a persistence exception.
Manually evict (JPA : detach) the corrupted instance from the session after catching the error (at point 5, but if the error was triggered by another pending change instead of the entity insert itself, this will be useless)
Don't let the database handle the id generation (use UUID or distributed id generation system, in this case the final flush will throw the real error preventing the persistence of the new instance instead of an hibernate assertion failure)
org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs)
This just happened to us and I thought I'd add some details for posterity. Turns out that we were trying to create an entity with a duplicate field that violated a condition:
Caused by: org.hibernate.exception.ConstraintViolationException: Duplicate entry '' for key
'Index_schools_name'
This exception however was being masked because hibernate was trying to commit the session even though the create failed. When the created failed then the id was not set hence the assert error. In the stack trace we could see that hibernate was committing:
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit
(HibernateTransactionManager.java:480)
It should have been rolling back the session, not committing it. This turned out to be a problem with our rollback configuration. We are using the old XML configs and the exception path was incorrect:
<prop key="create*">PROPAGATION_REQUIRED,-org.x.y.LocalException</prop>
The LocalException path was incorrect and hibernate didn't throw an error (or it was buried in the startup log spew). This would probably also be the case if you are using the annotations and don't specify the right exception(s):
// NOTE: that the rollbackFor exception should match the throws (or be a subclass)
#Transactional(rollbackFor = LocalException.class)
public void create(Entity entity) throws AnotherException {
Once we fixed our hibernate wiring then we properly saw the "duplicate entry" exception and the session was properly being rolledback and closed.
One additional wrinkle to this was that when hibernate was throwing the AssertionFailure, it was holding a transaction lock in MySQL that then had to be killed by hand. See: https://stackoverflow.com/a/39397836/179850
This happened to me in the following situation:
New entity is persisted.
Entity is configured with javax.persistence.EntityListeners. javax.persistence.PostPersist runs.
PostPersist needs some data from the database to send a message via STOMP. A org.springframework.data.repository.PagingAndSortingRepository query is executed.
Exception.
I fixed it by using the following in the EntityListeners:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.time.Instant;
...
ThreadPoolTaskScheduler scheduler = ApplicationContextHolder.getContext().getBean(ThreadPoolTaskScheduler.class);
scheduler.schedule(() -> repository.query(), Instant.now());
Where ApplicationContextHolder is defined as:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
#Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
In my case the problem was the length parameter of an entity's field. When I tried to save an object with too long String value in one of its fields, I got the error. The solution was to set the proper value of parameter "length" in hibernate configuration.
<property name="status" type="string" length="150" not-null="false" access="field"/>
It can also be done with annotation #Length like that:
#Length(max=150)
private String status;
The hibernate exception's message was very misleading in my case, as was stacktrace. The fastest way to locate where the problem occures is to follow your code with debugger and evaluate session.flush(); after every save() and saveOrUpdate() method.
This is nothing to do with the Query that is being executed. This just triggers the flush. At this point Hibernate is trying to assign an identifier to the entity and seems to have failed for some reason.
Could you try changing the generator class:
<generator class="identity"/>
see if that makes a difference. Also have you made sure that the database you have deployed has the correct auto-incrementing column set up on the table?
It sounds like your issue is similar to this one.
Changing the generator class:
<generator class="identity" />
to
<generator class="assigned" />
I have the same exception too, in hibernate config file:
<property name="operateType" type="java.lang.Integer">
<column name="operate_type" not-null="true" />
</property>
when pass null value at object, occur exception
"org.hibernate.AssertionFailure: null id in com.idex.auctions.model.Address entry",
I think the reason because Hibernaye will check 'not-null' property, so, remove 'not-null' property or set 'not-null' for 'false', will resolve the problem.
Sometimes this happens when length of string is greater than that allowed by DB.
DataIntegrityViolationException translates to this exception which is a weird behavior by hibernate.
So if you have Column annotation on the String field of the entity with length specified and the actual value is greater than that length, above exception is thrown.
Ref: https://developer.jboss.org/thread/186341?_sscc=t
org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs)
Your getting this error while using the save method, if your maintaining the version history of the user activity and try to set the following values
setCreatedBy(1);
setModifiedBy(1);
setCreationDate();
setChangeDate();
}
You will get the above error to solve this you need to create the following columns on table.
Created_By
Modified_By
Creation_Date
Change_Date
if you are getting same error while Update method to solve this problem Just you need to change the Update() method to merge() method that it
i hope helped you.
I had the same error. In my case it was because before this exception I executing create query with exception. Exception is caught and don't rollback the transaction in catch block. Then I use this broken transaction in other operation and after a few time I got the same exception. At first I set flush mode to manual
public final Session getCurrentSession()
{
Session session = sessionFactory.getCurrentSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
}
Then I got another exception, that explained to me what happened in fact. Then I done transaction rollback in catch block of my create method. And it helped to me.
I'm hitting the same error when I make session.getCurrentSession.refresh(entity) it looks more like a bug to me instead of an issue with my code. I'm getting this error in a unit test when I'm trying to refresh an entity in the beginning of a test and that entity is created in the test setup (annotated with junit's #Before). What is strange is that I'm creating 3 entities from the same class with random data at the same time and by the same way in the setup and I can refresh the first two created but the refresh fails for the last one. So for example If I create 3 entities User in the test setup I can refresh user1 and user2 and it fails for user3. I was able to resolve this by adding session.flush() at the end of the code that is creating the entity in the setup. I don't get any errors and I should but I cannot explain why the extra flush is needed. Also I can confirm that the entities are actually in the test DB even without flush because I can query them in the test but still failing the refresh(entity) method.
In my case, I traced out the error and found that I had not marked my table's primary key i.e. 'ID' as 'Auto_Increment' AI. Just tick the AI checkbox and it would work.
I don't know if im late or not, but my issue here was that i was opening an transaction and commiting -> flushing -> closing after the request. However between those did i have a nhibernate save() operator which does this automatically, in that case it complained.
Threw exception:
session.BeginTransaction();
model.save(entity);
session.Transaction.commit();
Solved for me
model.save(entity) //this one should open transaction, save and commit/flush by itself
However alot of people says that you should use both, ex NHibernate: Session.Save and Transaction.Commit.
But for some reason does it work for me now without transactions..
Roll back your transaction in the catch block

Deserialization problem: Error when deserializing from a different program version

I finally decided myself to post my problem, after a couple of hours spent searching the Internet for solutions and trying some.
[Problem Context]
I am developing an application which will be deployed in two parts:
an XML Importer tool: its role is to Load/Read an xml file in order to fill some datastructures, which are afterwards serialized into a binary file.
the end user application: it will Load the binary file generated by the XML Importer and do some stuff with the recovered data structures.
For now, I only use the XML Importer for both purposes (meaning I first load the xml and save it to a binary file, then I reopen the XML Importer and load my binary file).
[Actual Problem]
This works just fine and I am able to recover all the data I had after XML loading, as long as I do that with the same build of my XML Importer. This is not viable, as I will need at the very least two different builds, one for the XML Importer and one for the end user application. Please note that the two versions of the XML Importer I use for my testing are exactly the same concerning the source code and thus the datastructures, the only difference lies in the build number (to force a different build I just add a space somewhere and build again).
So what I'm trying to do is:
Build a version of my XML Importer
Open the XML Importer, load an XML file and save the resulting datastructures to a binary file
Rebuild the XML Importer
Open the XML Importer newly built, load the previously created binary file and recover my datastructures.
At this time, I get an Exception:
SerializationException: Could not find type 'System.Collections.Generic.List`1[[Grid, 74b7fa2fcc11e47f8bc966e9110610a6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadType (System.IO.BinaryReader reader, TypeTag code)
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadTypeMetadata (System.IO.BinaryReader reader, Boolean isRuntimeObject, Boolean hasTypeInfo)
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectInstance (System.IO.BinaryReader reader, Boolean isRuntimeObject, Boolean hasTypeInfo, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info)
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info)
For your information (don't know if useful or not), the actual type it is struggling to deserialize is a List, Grid being a custom Class (which is correctly serializable, as I am able to do it when using the same version of XML Importer).
[Potential Solution]
I do believe it comes from somewhere around the Assembly, as I read many posts and articles about this. However, I already have a custom Binder taking care of the differences of Assembly names, looking like this:
public sealed class VersionDeserializationBinder : SerializationBinder
{
public override Type BindToType( string assemblyName, string typeName )
{
if ( !string.IsNullOrEmpty( assemblyName ) && !string.IsNullOrEmpty( typeName ) )
{
Type typeToDeserialize = null;
assemblyName = Assembly.GetExecutingAssembly().FullName;
// The following line of code returns the type.
typeToDeserialize = Type.GetType( String.Format( "{0}, {1}", typeName, assemblyName ) );
return typeToDeserialize;
}
return null;
}
}
which I assign to the BinaryFormatter before deserializing here:
public static SaveData Load (string filePath)
{
SaveData data = null;//new SaveData ();
Stream stream;
stream = File.Open(filePath, FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Binder = new VersionDeserializationBinder();
data = (SaveData)bformatter.Deserialize(stream);
stream.Close();
Debug.Log("Binary version loaded from " + filePath);
return data;
}
Do any of you guys have an idea on how I could fix it? Would be awesome, pretty please :)
Move the working bits to a separate assembly and use the assembly in both "server" and "client". Based on your explanation of the problem, this should get around the "wrong version" problem, if that is the core issue. I would also take any "models" (i.e. bits of state like Grid) to a domain model project, and use that in both places.
I just bumped into your thread while I had the same problem. Especially your code sample with the SerializationBinder helped me a lot. I just had to modify it slightly to tell a difference between my own assemblies and those of Microsoft. Hopefully it still helps you, too:
sealed class VersionDeserializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type typeToDeserialize = null;
string currentAssemblyInfo = Assembly.GetExecutingAssembly().FullName;
//my modification
string currentAssemblyName = currentAssemblyInfo.Split(',')[0];
if (assemblyName.StartsWith(currentAssemblyName))assemblyName = currentAssemblyInfo;
typeToDeserialize = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
return typeToDeserialize;
}
}
I believe the problem is that you are telling it to look for List<> in the executing assembly, whereas in fact it is in the System assembly. You should only re-assign the assembly name in your binder if the original assembly is one of yours.
Also, you might have to handle the parameter types for generics specifically in the binder, by parsing out the type name and making sure the parameter types are not specific to the foreign assembly when you return the parameterized generic type.