Validation failed for one or more entities - entity-framework-4

I have following code in my asp.net MVC3 application:
string msg = "Beginning report run for: ";
msg += " Obligor Registry ID: " + obligorID;
msg += " Requesting Organization Registry ID:" + requestingOrgID;
msg += " Requesting Agent Registry ID: " + requestingAgentID;
TransactionLog lg = new TransactionLog();
lg.TransactionTypeId = 2;
lg.Message = msg;
context.TransactionLogs.Add(lg);
long referenceNumber = context.SaveChanges();
return referenceNumber;
and I am getting following error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
You need the namespace: System.Data.Entity.Validation

#GONeale helped me out in this regard. Moreover cause for this exception in my case is that I have certain not null db fields which I didnt included in the partial response update for certain transaction. context.Database.ExecuteSQLCommand would be my suggestion in this case.

Related

Connecting to Neo4j Aura with .NET Core 2.2 web api

I am trying to connect a to Neo4j Aura instance from a .NET core 2.2 web api. I understand I need the Neo4j .Net Driver v4.0.0-alpha01, but I do not seem to be able to connect. There aren't very many examples out there as this driver is new and so is Aura.
I keep getting:
Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again.
I configure the driver as such
public void ConfigureServices(IServiceCollection services)
{
string uri = "neo4j://1234567.databases.neo4j.io:7687";//not actual subdomain
string username = "neo4j";
string password = "seeeeeeecret";//not actual password
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password)));
}
and in my test controller i run this
private async Task<string> Neo4JTestAsync()
{
string db = "MyDb";
string message = "TESTMESSAGE";
IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(db));
try
{
var greeting = session.WriteTransactionAsync(async tx =>
{
var result = tx.RunAsync("CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
new { message });
var res = await result;
return "return something eventually";
});
return await greeting;
}
catch (Exception e)
{
return e.Message; // throws "Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again"
}
finally
{
await session.CloseAsync();
}
}
I can't get the exact error message you do - but I'm pretty sure this is due to encryption - one of the big differences between the 1.x and 4.x drivers is the default position on Encryption - which is now off by default.
So you'll want to change your initialisation to:
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password), config => config.WithEncryptionLevel(EncryptionLevel.Encrypted)));
That should get you going. Also - make sure you stick with the neo4j:// protocol, as that'll route you properly.
Have you tried bolt:// in the connection string?
string uri = "bolt://1234567.databases.neo4j.io:7687";//not actual subdomain

No errors are being raised when unsuccessfully writing to Azure service bus

When writing a message to the Azure Service Bus (using Microsoft.Azure.ServiceBus standard library, not the .Net Framework version) it works fine. However, when switching networks to a network that blocks that traffic and running it again I would expect an error being raised by SendAsync yet no error is thrown, therefor the function considers the send successful even though it is not.
Am I missing some logic to make sure that errors do get raised and trapped, it seems to be inline with all the examples I have seen.
I have tried this possible solution ..
Trouble catching exception on Azure Service Bus SendAsync method
.ContinueWith(t =>
{
Console.WriteLine(t.Status + "," + t.IsFaulted + "," + t.Exception.InnerException);
}, TaskContinuationOptions.OnlyOnFaulted);
.. and at no point does ContinueWith get hit.
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public ActionResult<Boolean> Post(Contract<T> contract)
{
Task.Run(() => SendMessage(contract));
// Other stuff
}
private async Task<ActionResult<Boolean>> SendMessage(Contract<T> contract)
{
JObject json = JObject.FromObject(contract);
Message message = new Message();
message.MessageId = Guid.NewGuid().ToString();
message.ContentType = ObjectType;
message.PartitionKey = ObjectType;
message.Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(contract));
foreach (KeyValuePair<String, String> route in DataRouting)
{
JToken jToken = json.SelectToken(route.Value);
if (jToken != null)
{
message.UserProperties[route.Key] = jToken.Value<String>();
}
else
{
String routeError = $"Could not find routing information in request for: {route.Key} in {route.Value}";
Logger.LogError(routeError);
return new UnprocessableEntityObjectResult(routeError);
}
}
// Send the message
try
{
await topicClient.SendAsync(message);
}
catch(Exception ex)
{
return new UnprocessableEntityObjectResult($"'Could not transmit message to service bus - {ex.Message}'");
}
return new OkObjectResult(true);
}
I expect that the error trap would be hit if the SendAsync fails to send the message. However it essentially fire and forgets, the message send is blocked by the firewall but is never reported to the caller by throwing an error.
Ok, found the answer, but I will leave this out there in case anyone else does this to themselves. It was down to my general muppetry when putting the MVC Controller together. Set async on the Post action and configure the await on the send. Obvious really but I missed it.
public virtual async Task<ActionResult<Boolean>> Post(Contract<T> contract){}
...
// Send the message
try
{
await topicClient.SendAsync(message).ConfigureAwait(false);
return new OkObjectResult(true); // Success if we got here
}
catch(Exception ex)
{
return new UnprocessableEntityObjectResult($"'Could not transmit message to service bus - {ex.Message}'");
}

Unknown Exception "null- Error while parsing the metadata." While executing DefaultSalesOrderService () - updateSalesOrder ()

As part of a PoC, I am currently trying to build a prototype for a side-by-side extension of S/4HANA Cloud, consisting of two layers: A SAPUI5 Frontend decoupled from a Java backend using the S/4HANA Cloud SDK.
On the whole it works great as well. But I often had trouble with the UPDATE commands, so I wrote a small servlet for demo purposes. Now I always get the same exception during the update, namely "Error while parsing the metadata".
I have already tried everything and now have no idea what could be the trigger for this exception.
I was trying to add more dependencies in the pom.xml, but that was without success. Also unsuccessful was the attempt to get all fields with the GET command and to update the filled object. The ETag is also not the problem, this is handled since the latest release by the "versionIdentifier" excellent.
If one of you has any idea of where my mistake lies, I would be very grateful!
Thanks in advance for your help!
[OLD] Code Snippet: public class UpdateService extends HttpServlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Test-Run: UPDATE
response.getWriter().write("Test-Run: UPDATE" + "\n");
// Prepare the S/4HANA Cloud Service
DefaultSalesOrderService service = new DefaultSalesOrderService();
// Prepare the required Variables
String salesOrderKey = "1";
String deliveryBlockReason = "01";
SalesOrder salesOrder;
try {
// Get the Sales Order
response.getWriter().write("Step 1: Get old data.." + "\n");
salesOrder = service.getSalesOrderByKey(salesOrderKey).select(SalesOrder.DELIVERY_BLOCK_REASON).execute();
// Output: OLD DATA
response.getWriter().write(new Gson().toJson(salesOrder) + "\n");
// Change the Data
response.getWriter().write("\n" + "Step 2: Set new data.." + "\n");
salesOrder.setDeliveryBlockReason(deliveryBlockReason);
// Output: NEW DATA
response.getWriter().write(new Gson().toJson(salesOrder) + "\n");
// Save the Changes
response.getWriter().write("\n" + "Step 3: Save new data.." + "\n");
service.updateSalesOrder(salesOrder).execute();
// Success Message
response.getWriter().write("\n" + "Update successful!");
} catch (final ODataException e) {
// Handle Errors
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("\n" + "Update failed!" + "\n");
response.getWriter().write("Error Code: " + e.getCode() + "\n");
response.getWriter().write("Message: " + e.getMessage() + "\n");
}
}
[OLD] Http-Response
Test-Run: UPDATE
Step 1: Get old data..
{"DeliveryBlockReason":"","versionIdentifier":"W/\"datetimeoffset\u00272017-06-19T08%3A31%3A55.6635100Z\u0027\""}
Step 2: Set new data..
{"DeliveryBlockReason":"01","versionIdentifier":"W/\"datetimeoffset\u00272017-06-19T08%3A31%3A55.6635100Z\u0027\""}
Step 3: Save new data..
Update failed!
Error Code: null
Message: Error while parsing the metadata.
UPDATE - 2018-04-18
First of all, thanks for your help!
I reprogrammed the code a bit and implemented Henning's workaround. At first glance, everything seems to work. There are no exceptions and no warnings.
However, in the backend you can see that, that the actual values remain unchanged. Would you have another advice for me?
[NEW] Code Snippet: public class UpdateService extends HttpServlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Test-Run: UPDATE
response.getWriter().write("Test-Run: UPDATE" + "\n");
// Prepare the S/4HANA Cloud Service
DefaultSalesOrderService service = new DefaultSalesOrderService();
// Prepare the Sales Order Object
SalesOrder salesOrder = null;
// Prepare the required Variables
String salesOrderKey = "163";
// GET
try {
salesOrder = service.getSalesOrderByKey(salesOrderKey).select(SalesOrder.ALL_FIELDS).execute();
// Success Message
response.getWriter().write("\n" + "GET successful!:" + "\n");
// Output: OLD DATA
response.getWriter().write("Old Data:" + "\n");
response.getWriter().write(new Gson().toJson(salesOrder) + "\n");
} catch (ODataException e) {
// Handle Errors
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("\n" + "GET failed!" + "\n");
response.getWriter().write("| Error Code: " + e.getCode() + "\n");
response.getWriter().write("| Message: " + e.getMessage() + "\n");
}
// CHANGE
salesOrder.setSalesOrderType("SO");
// Success Message
response.getWriter().write("\n" + "CHANGE successful!:" + "\n");
// Output: NEW DATA
response.getWriter().write("New Data:" + "\n");
response.getWriter().write(new Gson().toJson(salesOrder) + "\n");
// UPDATE
try {
// Workaround - Henning Heitkötter -
// https://stackoverflow.com/questions/49862888/unknown-exception-null-error-while-parsing-the-metadata-while-executing-defa
SalesOrderUpdateFluentHelper updateHelper = new SalesOrderUpdateFluentHelper(salesOrder) {
#Override
public ODataUpdateRequest toQuery() {
ODataUpdateRequestBuilder requestBuilder = getQueryBuilder()
.withErrorHandler(new ODataVdmErrorResultHandler());
getEntity().setSalesOrder(null);
final Map<String, Object> params = new ODataJsonMapResolver(getEntity()).withoutNullValues();
return requestBuilder.withBodyAsMap(params).build();
}
};
// EXECUTE
updateHelper.execute();
// Success Message
response.getWriter().write("\n" + "UPDATE successful!" + "\n");
} catch (ODataException e) {
// Handle Errors
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("\n" + "UPDATE failed!" + "\n");
response.getWriter().write("| Error Code: " + e.getCode() + "\n");
response.getWriter().write("| Message: " + e.getMessage() + "\n");
}
}
[NEW] Http-Response
Test-Run: UPDATE
GET successful!:
Old Data:
{"SalesOrder":"163","SalesOrderType":"OR","SalesOrganization":"1010","DistributionChannel":"10","OrganizationDivision":"00","SalesGroup":"","SalesOffice":"","SalesDistrict":"","SoldToParty":"1000355","CreationDate":1516752000000,"CreatedByUser":"CB9980000321","LastChangeDateTime":1516793069586,"PurchaseOrderByCustomer":"110","CustomerPurchaseOrderType":"","CustomerPurchaseOrderDate":1516752000000,"SalesOrderDate":1516752000000,"TotalNetAmount":35.00,"TransactionCurrency":"EUR","SDDocumentReason":"","PricingDate":1516752000000,"RequestedDeliveryDate":1516752000000,"ShippingCondition":"","CompleteDeliveryIsDefined":false,"ShippingType":"","HeaderBillingBlockReason":"","DeliveryBlockReason":"","IncotermsClassification":"CFR","IncotermsTransferLocation":"DE","IncotermsLocation1":"DE","IncotermsLocation2":"","IncotermsVersion":"","CustomerPaymentTerms":"0001","PaymentMethod":"","OverallSDProcessStatus":"A","TotalCreditCheckStatus":"","OverallTotalDeliveryStatus":"","OverallSDDocumentRejectionSts":"A","versionIdentifier":"W/\"datetimeoffset\u00272018-01-24T11%3A24%3A29.5861550Z\u0027\"","AssignmentReference":""}
CHANGE successful!:
New Data:
{"SalesOrder":"163","SalesOrderType":"SO","SalesOrganization":"1010","DistributionChannel":"10","OrganizationDivision":"00","SalesGroup":"","SalesOffice":"","SalesDistrict":"","SoldToParty":"1000355","CreationDate":1516752000000,"CreatedByUser":"CB9980000321","LastChangeDateTime":1516793069586,"PurchaseOrderByCustomer":"110","CustomerPurchaseOrderType":"","CustomerPurchaseOrderDate":1516752000000,"SalesOrderDate":1516752000000,"TotalNetAmount":35.00,"TransactionCurrency":"EUR","SDDocumentReason":"","PricingDate":1516752000000,"RequestedDeliveryDate":1516752000000,"ShippingCondition":"","CompleteDeliveryIsDefined":false,"ShippingType":"","HeaderBillingBlockReason":"","DeliveryBlockReason":"","IncotermsClassification":"CFR","IncotermsTransferLocation":"DE","IncotermsLocation1":"DE","IncotermsLocation2":"","IncotermsVersion":"","CustomerPaymentTerms":"0001","PaymentMethod":"","OverallSDProcessStatus":"A","TotalCreditCheckStatus":"","OverallTotalDeliveryStatus":"","OverallSDDocumentRejectionSts":"A","versionIdentifier":"W/\"datetimeoffset\u00272018-01-24T11%3A24%3A29.5861550Z\u0027\"","AssignmentReference":""}
UPDATE successful!
[NEW] S/4HANA Cloud API
<entry m:etag="W/"datetimeoffset'2018-01-24T11%3A24%3A29.5861550Z'"">
<id>
...../sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder('163')
</id>
<title type="text">A_SalesOrder('163')</title>
<updated>2018-04-18T16:03:24Z</updated>
<category term="API_SALES_ORDER_SRV.A_SalesOrderType" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
<link href="A_SalesOrder('163')" rel="edit" title="A_SalesOrderType"/>
<link href="A_SalesOrder('163')/to_Item" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/to_Item" type="application/atom+xml;type=feed" title="to_Item"/>
<link href="A_SalesOrder('163')/to_Partner" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/to_Partner" type="application/atom+xml;type=feed" title="to_Partner"/>
<link href="A_SalesOrder('163')/to_PricingElement" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/to_PricingElement" type="application/atom+xml;type=feed" title="to_PricingElement"/>
<content type="application/xml">
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<d:SalesOrder>163</d:SalesOrder>
<d:SalesOrderType>OR</d:SalesOrderType>
<d:SalesOrganization>1010</d:SalesOrganization>
<d:DistributionChannel>10</d:DistributionChannel>
<d:OrganizationDivision>00</d:OrganizationDivision>
<d:SalesGroup/>
<d:SalesOffice/>
<d:SalesDistrict/>
<d:SoldToParty>1000355</d:SoldToParty>
<d:CreationDate>2018-01-24T00:00:00</d:CreationDate>
<d:CreatedByUser>CB9980000321</d:CreatedByUser>
<d:LastChangeDate m:null="true"/>
<d:LastChangeDateTime>2018-01-24T11:24:29.5861550Z</d:LastChangeDateTime>
<d:PurchaseOrderByCustomer>110</d:PurchaseOrderByCustomer>
<d:CustomerPurchaseOrderType/>
<d:CustomerPurchaseOrderDate>2018-01-24T00:00:00</d:CustomerPurchaseOrderDate>
<d:SalesOrderDate>2018-01-24T00:00:00</d:SalesOrderDate>
<d:TotalNetAmount>35.00</d:TotalNetAmount>
<d:TransactionCurrency>EUR</d:TransactionCurrency>
<d:SDDocumentReason/>
<d:PricingDate>2018-01-24T00:00:00</d:PricingDate>
<d:RequestedDeliveryDate>2018-01-24T00:00:00</d:RequestedDeliveryDate>
<d:ShippingCondition/>
<d:CompleteDeliveryIsDefined>false</d:CompleteDeliveryIsDefined>
<d:ShippingType/>
<d:HeaderBillingBlockReason/>
<d:DeliveryBlockReason/>
<d:IncotermsClassification>CFR</d:IncotermsClassification>
<d:IncotermsTransferLocation>DE</d:IncotermsTransferLocation>
<d:IncotermsLocation1>DE</d:IncotermsLocation1>
<d:IncotermsLocation2/>
<d:IncotermsVersion/>
<d:CustomerPaymentTerms>0001</d:CustomerPaymentTerms>
<d:PaymentMethod/>
<d:AssignmentReference/>
<d:OverallSDProcessStatus>A</d:OverallSDProcessStatus>
<d:TotalCreditCheckStatus/>
<d:OverallTotalDeliveryStatus/>
<d:OverallSDDocumentRejectionSts>A</d:OverallSDDocumentRejectionSts>
</m:properties>
</content>
</entry>
The error while parsing metadata occurs because the key field SalesOrder is not set on your entity. You would need to retrieve it as part of the get-by-key as follows, and then you can change the fields that allow changes in SAP S/4HANA, such as the requested delivery date:
SalesOrder salesOrder = service.getSalesOrderByKey(salesOrderKey)
.select(SalesOrder.SALES_ORDER)
.execute()
salesOrder.setRequestedDeliveryDate(Calendar.getInstance());
service.updateSalesOrder(salesOrder).execute();
As of version 1.11.1 of the SAP S/4HANA Cloud SDK, this will only send changed fields (or any field that you explicitly specify via includingFields).
Note: Some fields such as the SalesOrderType or DeliveryBlockReason cannot be changed via the API.
Make sure to use the most recent version of the SAP S/4HANA Cloud SDK, at least version 1.11.1.
Which version of the S/4HANA Cloud SDK are you using?
If you're not using 1.10.0, kindly upgrade to this version (latest version currently) and retry.
I assume you're connecting to a current SAP S/4HANA release, am I right?
Kindly reproduce the error and open transaction /n/iwfnd/error_log.
Look for respective error messages and provide them here along with the corresponding response header and body.
Make sure that you omit any confidential information.

exception inside of OnException

I created a custom attribute, inheriting from HandleErrorAttribute:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
try
{
Utility.LogAndNotifyOfError(filterContext.Exception, null, true);
}
catch(Exception ex)
{
filterContext.Exception = ex;
}
}
}
, and then registered with:
filters.Add(new CustomHandleErrorAttribute());
This has always worked as intended. However a common problem with my log method is that it uses a custom event log source when writing to the event log, which the app pool account typically doesn't have the permissions to create. Creating the event log source is a simple powershell script, however I wanted to actually include that tidbit in the error:
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
The problem is that the catch in the OnException is never hit. When debugging, the custom error I throw from LogAndNotifyOfError instead triggers a second call to OnException, and the detail of my ErrorHandlerException is never seen. I want the asp.net error page that comes up to be with my custom error detail rather than the SecurityException that was originally raised.
You can even see the surrounding try in the displayed error:
Edit: Entire log method listed:
public static void LogAndNotifyOfError(Exception ex, String extraInfo, Boolean sendEmail)
{
//if the error handler itself faulted...
if (ex is ErrorHandlerException)
return;
string eventLogName = "Application";
string eventLogSource = "MySourceName";
String error = ex.ToString();
if (error.Length > 28000)
error.Substring(0, 28000);//event log is limited to 32k
error += "\r\n\r\nAdditional Information: \r\n"
+ "Machine Name: " + Environment.MachineName + "\r\n"
+ "Logged in user:" + App.CurrentSecurityContext.CurrentUser?.UserId + "\r\n"
+ extraInfo + "\r\n";
EventLog log = new EventLog(eventLogName);
log.Source = eventLogSource;
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{//this doesn't work - for some reason, OnError still reports the original error.
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
//if the email-to field has been set...
if (!String.IsNullOrEmpty(App.Config.General.ErrorHandlerSendToAddresses) && sendEmail)
{
//...then send the email
MailMessage email = new MailMessage();
email.To.Add(App.Config.General.ErrorHandlerSendToAddresses);
email.IsBodyHtml = false;
email.Subject = String.Format("Error in {0}", eventLogSource);
email.Body = email.Subject + "\r\n\r\n"
//+ "Note: This error may be occuring continuously, but this email is only sent once per hour, per url, in order to avoid filling your mailbox. Please check the event log for reoccurances and variations of this error.\r\n\r\n"
+ "The error description is as follows: \r\n\r\n"
+ error + "\r\n\r\n";
SmtpClient smtp = new SmtpClient();
smtp.Send(email);
}
}
I figured it out (sort of). It would appear that when the newly throw exception has an inner exception, it is only displaying that inner exception. It does not matter what the type is on the outer or inner exception.

Neo4jClient Transaction Error

When I try to update an existing Node in Neo4JClient without using transaction, which has a Unique Constraint on Id and Name property, I receive this Exception:
CypherExecutionException: Node 6 already exists with label User and property "Name"=[Mike]
But when I try to update a Node in transaction, I receive this Exception:
Received an unexpected HTTP status when executing the request.
The response status was: 404 Not Found
The response from Neo4j (which might include useful detail!) was: {"results":[],"errors":[{"code":"Neo.ClientError.Transaction.UnknownId","message":"Unrecognized transaction id. Transaction may have timed out and been rolled back."}]}
My Code is like this:
using (var transaction = client.BeginTransaction())
{
client.Cypher
.Merge("(user:User { Id: {id}})")
.OnCreate().Set("user = {user}")
.OnMatch().Set("user = {user}")
.WithParams(new { id = user.Id, user = user })
.ExecuteWithoutResults();
transaction.Commit();
}
My question is: Is there a way to get the actual error when using transaction, like I get one when I don't use transaction?
Thanks
EDIT 1:
It looks like the NULL Id in not being handled correctly. After drilling down, I managed to pull the actual error. The first exception in is:
errors = {[
{
"code": "Neo.ClientError.Statement.InvalidSemantics",
"message": "Cannot merge node using null property value for Id"
}
]}
The stack trace for this exception is:
at Neo4jClient.Serialization.CypherJsonDeserializer1.GetRootResultInTransaction(JObject root) in [PATH_HIIDEN]\Neo4jClient\Serialization\CypherJsonDeserializer.cs:line 316
at Neo4jClient.Serialization.CypherJsonDeserializer1.CheckForErrorsInTransactionResponse(String content) in [PATH_HIIDEN]\Neo4jClient\Serialization\CypherJsonDeserializer.cs:line 291
at Neo4jClient.GraphClient.<>c__DisplayClass84_01.<PrepareCypherRequest>b__0(Task1 responseTask) in [PATH_HIIDEN]\Neo4jClient\GraphClient.cs:line 933
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
And after that there is the exception with 404 NOT Found error. For that the stack trace is:
at Neo4jClient.Execution.HttpResponseMessageExtensions.EnsureExpectedStatusCode(HttpResponseMessage response, String commandDescription, HttpStatusCode[] expectedStatusCodes) in [PATH_HIIDEN]\Neo4jClient\Execution\HttpResponseMessageExtensions.cs:line 41
at Neo4jClient.Execution.HttpResponseMessageExtensions.EnsureExpectedStatusCode(HttpResponseMessage response, HttpStatusCode[] expectedStatusCodes) in [PATH_HIIDEN]\Neo4jClient\Execution\HttpResponseMessageExtensions.cs:line 14
at Neo4jClient.Execution.ResponseBuilder.<>c__DisplayClass21_0.b__0(Task1 requestTask) in [PATH_HIIDEN]\Neo4jClient\Execution\ResponseBuilder.cs:line 127
at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Can this error be fixed in the next release please?
EDIT 2
using (var transaction = client.BeginTransaction())
{
manifest.Users = client.Cypher
.Merge("(n:User { Id: '8be0b8fd-c433-44d3-a7e2-3f0d1a03fefa'}) " +
"ON CREATE " +
"SET n = { " +
"Id: '8be0b8fd-c433-44d3-a7e2-3f0d1a03fefa', " +
"UserName: 'test.user', " +
"Name: 'Test User', " +
"Active: true " +
"} " +
"ON MATCH " +
"SET n = { " +
"Id: '8be0b8fd-c433-44d3-a7e2-3f0d1a03fefa', " +
"UserName: 'test.user', " +
"Name: 'Test User', " +
"Active: true " +
"}")
.Return(n => n.As<User>())
.Results
.ToList();
transaction.Commit();
}
Meaning fluent Api is causing the error.
So the problem is that in Neo4j 2.2.6 a change was introduced whereby any ClientError (Constraint Violation etc) resulted in an automatic Rollback of a transaction on the server.
Neo4jClient already did an auto-rollback on error, and continued to do so. With 2.2.6 this resulted in a 404 error as the transaction was no longer there (previous versions were fine).
So, I've made a fix and published an updated Nuget package, so version 1.1.0.12 of Neo4jClient will now give you the correct response.

Resources