How to fix Newtonsoft.Json.JsonConvert deserialize failure? - c#

I have an asp.net WebAPI app. I'm returning files to the client in the Request.CreateResponse(,) second parameter as type Dictionary<string, List<System.Net.Http.StreamContent>>, where List<System.Net.Http.StreamContent>> contains all the files.
I'm deserializing the files at the client using the following:
var someContent = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, List<System.Net.Http.StreamContent>>>(result.Content.ReadAsStringAsync().Result);
This code throws the exception:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newstonsoft.Json.dll.
Additional information: Unable to find a construction to use for type
System.Net.Http.StreamContent. A class should either have default
constructor, one constructor with arguments or a constructor marked
with the JsonConstructor attribute. Path 'myFiles[0].Headers'
Is there a different way to return actual files?

Related

Passing Lambda Expression condition as parameter in the WCF

My ASP.NET MVC application has multiple conditions to fetch the record from the database for different scenarios. In order to implement the same in the WCF with multiple functions for different conditions. I tried to implement the below code,
ASP.NET MVC code:
IEnumerable<WCF.UserApplicationDetails> Search_UserApplicationDetails =
shareGatewayClient.GetUserApplicationDetailsByCondition(x => (x.FirstName == Name)).ToList();
WCF code - basic http binding endpoint:
public IEnumerable<UserApplicationDetails> GetUserApplicationDetailsByCondition(Func<UserApplicationDetails, bool> condition)
{
DBContext databaseEntities = new DBContext();
return databaseEntities.UserApplicationDetails.Where(condition).ToList();
}
It was working properly in the same application, but in WCF I'm getting this error:
Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Is there any alternative to achieve this?

Amadeus Car Availability

If I can invoke the api Car Availability with a locationDescription.name that have more than three letters the api send me the following errors:
"18|Presentation|Serializing/Deserializing error: [type = DataElement]
[name = name] [Error = Invalid length for data element]."
Could you help, please?
Thanks
Seems like your class does not have public default constructor.
Refer : https://support.microsoft.com/en-in/help/330592/error-message-when-you-serialize-a-class-by-using-the-xmlserializer-cl
When you try to use the XmlSerializer class to serialize a class that
does not have a public default constructor, you may receive the
following System.InvalidOperationException exception error message: An
unhandled exception of type 'System.InvalidOperationException'
occurred in system.xml.dll Additional information: There was an error
reflecting 'class'. where class indicates the class that the
XmlSerializer class tried to serialize.

How to handle OdataException in DefaultODataPathHandler.Parse at global level?

DefaultODataPathHandler.Parse(string serviceRoot, string odataPath, IServiceProvider requestContainer)
is throwing ODataException when I try to send a wrong data type to a
OData controller function. For example, calling GetOrders(date = 20181001), (with an integer instead of a date (2018-10-01)), throws ODataException with message:
not able to cast Edm.Int32 to Emd.DateTime
How can I handle this exception at global level?

MVC Deserialization Error

Okay. This is my company's customer portal, it's an MVC 2 project. We have a back end SAP system that the portal draws data from. But it does not directly hit SAP, it sends an xml request to a VB app that gets the data and sends it back in an xml response. There is an interface IRequest that all the various requests implement examples would be CustomerNumberRequest, CompanyNameRequest, etc. These all implement the method ToXml which as the name suggests simply builds xml to send. All of the existing requests work fine. (Let me preface this by saying that I inherited this project and the guy who wrote it is no longer with us) I am now trying to send a request to get the Rep Groups from SAP. I basically copied one of the other requests verbatim, making the necessary tweaks to send the appropriate request. But it keeps failing with error messages that I don't understand:
The formatter threw an exception while
trying to deserialize the message:
There was an error while trying to
deserialize parameter
http://tempuri.org/:request. The
InnerException message was 'The
deserializer cannot load the type to
deserialize because type
'XXXXX.CustomerPortal.Domain.RepGroupRequest'
could not be found in assembly
'XXXXX.CustomerPortal.Domain,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'. Check that the
type being serialized has the same
contract as the type being
deserialized and the same assembly is
used.'. Please see InnerException for
more details.
This error happens right at _communicationService.ProcessRequest(request); (shown below) It does not enter the ProcessRequest method it just tries to create a NetDataContractSerializer here:
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
{
return new NetDataContractSerializer();
}
and then it dies. These are the methods being called:
private void PopulateRepGroups()
{
List<string> repGroups = new List<string>();
RepGroupRequest request = new RepGroupRequest();
foreach (RepGroup repGroup in _repService.GetRepGroups(request))
repGroups.Add(repGroup.RepGroupName);
ViewData["RepGroups"] = new SelectList(repGroups);
}
public List<RepGroup> GetRepGroups(RepGroupRequest request)
{
string response = _communicationService.ProcessRequest(request);
return RepGroupResponseFactory.GetRepGroupResponse(response);
}
Can anybody tell me what this error message is telling me? It says the type cannot be found but the type should be IRequest (that's what it says when the CreateSerializer is hit) which is used all over this. I'm clearly lost, please help!
Quoting your exception
Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used
Check the version of the library on both ends that CustomerPortal.Domain.RepGroupRequest resides in to make sure they are the same version exactly.

Problem with c# webservice, referencing a method and a type

I have run into a bit of a problem, well not sure if it is a problem, but would like some advice.
I have developed a c# webservice in vs2010 and when I debug the service i get this error in my browser
The XML element 'VoucherResponse' from namespace 'http://test.org/' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The XML element 'VoucherResponse' from namespace 'test.org' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Now looking at my code in at the actual class "VoucherResponse" i have,
public class VoucherResponse : AResponse
{
public Voucher Voucher { get; set; }
}
And the Voucher object looks like this
public class Voucher
{
public string PIN { get; set; }
public string Serial { get; set; }
public string Batch { get; set; }
}
Now in one of my web methods I return the VoucherResponse and I am assuming that this error occurs when it is reflected through and checked.
Has anyone had a similar problem with this before, or can anyone give me some advice on this?
Thanks
I found another case that raises the error! Here's my code:
[WebMethod]
public CheckUpdateResponse CheckUpdate()
{
...
}
Ok, let me explain: CheckUpdateResponse is a structure I defined in my code, CheckUpdate() is a method. So, in the WSDL .NET add automatically a Response suffix to the method name CheckUpdate.
Et voilĂ : it finds a duplicate element and gives the error "Change the method's message name using WebMethodAttribute..."
Solution? I renamed the returned type from CheckUpdateResponse to CheckUpdateResult and now everything works fine!
I hope this will help someone! I lost a lot of time on this...
Apparently, SOAP cannot handle methods that have the same name as their return type.
You can fix it by reading the error, and acting accordingly:
public class VoucherResponse
{
[WebMethod(MessageName="TheVoucher")]
public Voucher Voucher{get; set;}
}
I had the same issue, but in my case; the application that I developed is web service client, so I don't have control on changing the WSDL\Schema.
The problem was that I had one web service with 17 operations, all of them are returning the same complex type, I got the mentioned error due to deserialization of the return type, because .Net is wrapping the return type for each output, and the serializer is throwing error:
The XML element 'XYZ' from namespace 'ABC' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.
Solution:
I opened Reference.cs file, removed all wappered return type generated classes, and kept only one, then changed its class name to be generic, not related to the operation, it worked for me.

Categories