problem with the payload when saving a record - dynamics-crm

when I try to add\change the value of a custom lookup and then save it, I get this error:
Exception Message: Error identified in Payload provided by the user for Entity :'', For more information on this error please follow this help link https://go.microsoft.com/fwlink/?linkid=2195293 ----> InnerException : Microsoft.OData.ODataException: An undeclared property 'ey_org_unit_hr_id' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadUndeclaredProperty(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean propertyWithValue)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithoutValue(IODataJsonLightReaderResourceState resourceState, String propertyName)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.<ReadResourceContent>b__0(PropertyParsingResult propertyParsingResult, String propertyName)
at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func`2 readPropertyAnnotationValue, Action`2 handleProperty)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState)
at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource()
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties)
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector)
at Microsoft.OData.ODataReaderCore.ReadImplementation()
at Microsoft.OData.ODataReaderCore.InterceptException[T](Func`1 action)
at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader)
at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger).
ErrorCode: -2147185383
HexErrorCode: 0x80048d19
the field's logical and schema name is "ey_org_unit_hr_id" (both of them are identical).
I opened the post request that the form sends and this is what I found:
{"ey_org_unit_hr_id#odata.bind":"/ey_businessunits(91293b20-afb7-e611-bec8-0050568c00dc)",
"ey_org_unit_hr_id#OData.Community.Display.V1.FormattedValue":null,
"ey_s_name":"test555",
"ey_b_is_doctor_house":false,
"ey_b_is_route_service_requests":false,
"ey_b_real_branch":false,
"statuscode":1,
"statecode":0}
then I opened the metadata and found out that the NavigationalProperty Name of this field is different than what is used in the post request (ey_org_unit_hr_id is used in the request but the navigational property name is ey_ey_businessunit_ey_branch_hr which is also the name of the relationship).
Photo of the navigation property name
so i tried to send a post request using postman whith the currect NavigationProperty Name and it worked without an error.
Here is the request:
{"ey_ey_businessunit_ey_branch_hr#odata.bind":"/ey_businessunits(91293b20-afb7-e611-bec8-0050568c00dc)",
"ey_ey_businessunit_ey_branch_hr#OData.Community.Display.V1.FormattedValue":null,
"ey_s_name":"test555",
"ey_b_is_doctor_house":false,
"ey_b_is_route_service_requests":false,
"ey_b_real_branch":false,
"statuscode":1,
"statecode":0}
I thought about changing the navigational property name to what is used in the original post request but I don't know if I can change the metadata.

Try this property name: _ey_org_unit_hr_id_value.

You should check your error code at the below link.
https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
AFAIK, the 0x80048d19 code will be exposed by sending request with invalid data.
In my case, I got this error code when i sent request without header "Content-Type: application/json"
I hope this can be helpful to you

Related

How to replace 400 bad request error message with a custom message

I am creating a webapi and just wondering whether I can replace the default error message in case of 400 Bad Request.
For example, in this url (http://localhost/api/values/4) 4 is the integer type but if I pass a string intentionally (e.g. http://localhost:35453/api/values/sss), I receive an error (400 Bad Request) in the following format:
{
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult Get(Int32)' in 'WebAp__DELETE.Controllers.ValuesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
Is there any way I can replace this default error message with a custom error message of mine.

Basic MVC nullable char validation

I have the following in one of my view models:
public char? MyChar { get; set }
I noticed there appears to be no client-side validation on the textbox for MyChar, and it's possible for a user to submit a string that is too long for this char to my controller (it simply doesn't bind and remains null).
So, I added the [MaxLength] annotation. Client-side validation now works as expected, but when I submit a valid value to the server, I get the following exception in my event logs:
Exception information:
Exception type: InvalidCastException
Exception message: Unable to cast object of type 'System.Char' to type 'System.Array'.
at System.ComponentModel.DataAnnotations.MaxLengthAttribute.IsValid(Object value)
How can I validate the max length of a char correctly both client-side and server-side?
What I've Tried
For now, I've created my own MaxLength attribute for it to work with char types, but it feels like a heavy approach.

What is the best way to notify api clients of null-valued properties of returned JSON object?

I have an asp.net web api 2 application that provides data in JSON format for api clients. For GET api methods, an api client programmer who is using Java and C++ languages to call those GET method apis. However, for null-valued properties of JSON objects, the client programmer says he receives "null" (null in-quote string) for those properties. In SQL Server database for nvarchar (string) and datetime columns of different database tables, I save those null-valued columns as null as normal SQL server convention but not "null" string.
My question is what is the best way to let api client programmers know if a null-valued property is null to distinguish it from real "null" string, e.g. {"state": "null"} a literal string. Thanks in advance.
I have many GET method apis which returns null for null-valued properties of JSON objects.
I test my GET Api methods for null properties with Postman or Advanced Rest Client tool, I do not see those tool returns null in "null" (in-quote string) for null-valued properties: (here is state and closeddate properties)
{"firstname":"abc","lastname":"def","state":null,"birthdate":"1992-05-25T00:00:00","closeddate":null}
One of GET method api looks like:
[HttpGet]
public HttpResponseMessage GetUserInfo(int userid)
{
var user = _userService.GetUserInfo(userid);
var statusCode = _userService.StatusCode;
var errorCode = _userService.ErrorCode;
return _statusCode == HttpStatusCode.OK
? Request.CreateResponse(_statusCode, account)
: Request.CreateResponse(_statusCode, errorCode);
}
Since you are asking for an opinion, here's one from the creator of SlashDB API: when in doubt, leave it out.
In the JSON data format keys with null value can be omitted from the result.
The following API call returns a Customer record, which does not have a value in the Company field:
HTML rendering: http://demo.slashdb.com/db/Chinook/Customer/CustomerId/2.html
JSON rendering: http://demo.slashdb.com/db/Chinook/Customer/CustomerId/2.json
XML format is more formal about it because you can define a schema, which prescribes what is the allowed shape of data. In particular, an element (tag) could have a minOccurs=0 attribute to indicate its optionality, and/or a nillable=True to indicate that a tag could be present without a value (i.e. ). For completeness here's the same record in XML and its schema:
XML rendering: http://demo.slashdb.com/db/Chinook/Customer/CustomerId/2.html
XSD schema: http://demo.slashdb.com/db/Chinook/Customer.xsd

Spring form tags. Allow nulls in form:select (enum)

I'm using Spring form tags for filling form with values.
I have form backing object:
public class FormInfo {
public enum Status {ON, OFF}
private Satus status;
//getter setter
...
}
And in JSP Status enum presented like this:
<form:form commandObject="formInfo " ...>
<form:select path="status">
<form:option value="null" label="Please select"/>
<form:options/>
</form:select>
</form:form>
All works fine, i.e. default message and enum values are presented in <select>.
But the status field is not required, so I want allow user to leave Status field unselected. But if form submitted without selecting status field, then I get error:
error in object 'formInfo' on field 'status': rejected value [null];
How I can set enum to null when no values is selected?
Please note I'm using JSR 303 validation. And error described above is not happens automatically, I get this error message manually from following method BindingResult#getFieldErrors().
This is my controller code:
public void myMethod(#Valid #ModelAttribute("formInfo") FormInfo sourcingDetail, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
log.error("Error during validation is occurred." + bindingResult.getFieldErrors().toString()); // <-- this is error message
}
...
}
Also please note, I didn't set any JSR-303 annotation (like #NotNull) on status field.
UPDATE:
Almost full error message which I get from calling this method BindingResult#getFieldErrors() (explained above):
Error during validation is occurred.[Field error in object 'formInfo'
on field 'status': rejected value [null];
...
[Failed to convert property value of type 'java.lang.String' to
required type 'com.my.project.model.Status' for property 'status';
nested exception is java.lang.IllegalStateException: Cannot convert
value of type [java.lang.String] to required type
[com.my.project.model.Status] for property 'status': no matching
editors or conversion strategy found],
Looks like you have the same problem as i!.
There is a method in the controller that serves as a hook where you could specify how to transform the String values, that came from the HTTP request, to a concrete object!.
The method is called initBinder, and there you attach the right behavior to do the conversion properly. I am still researching, but so far, looks good.
Take a look at this :
Form Values to be Null instead of "" in Spring
http://kaushalyas.blogspot.com.ar/2011/02/data-binding-in-spring-mvc.html
Hope it helps to found the solution!
Greetings
Victor.

MVC Ajax Int32 error

Hi when I try to do an Ajax post to my controller I keep getting this message:
The parameters dictionary contains a
null entry for parameter 'id' of
non-nullable type 'System.Int32' for
method 'System.Web.Mvc.JsonResult
GetContactsByDepartment(Int32)' in
'Intranet.Controllers.MyController'.
An optional parameter must be a
reference type, a nullable type, or be
declared as an optional parameter.
The method head looks like this: public JsonResult GetContactsByDepartment(int id)
What am I missing? I have ensured that the id is being passed through my Jquery ajax call.
Try to rename id to for example DepartmentID.
Probably an issue with your registered routes.

Resources