The format of response
adbc91a43e988a3b5b745b8529a90b61
<RESPONSE Stamp="YYYY-MM-DDTHH:MM:SSZ" RE="…" ERR_TEXT="…">
<PaymentID>3242343</PaymentID>
</RESPONSE>
The first line of the response consists of a md5-hash xml-response + parameters hash, followed by
xml-response.
The main element of xml-response is called RESPONSE...
How and where to add the hash code?
Thanks
I have XML without hashcode. My code in c#
[WebMethod]
public RESPONSE GET( string id)
{
RESPONSE res = new RESPONSE();
res.ERR_TEXT = "";
res.RE = "";
res.Stamp = DateTime.Now.ToString("yyyy-MM-ddthh-mm-ssz");
res.PaymentID = id;
return res;
}
public class RESPONSE
{
[XmlAttribute]
public string ERR_TEXT { get; set; }
[XmlAttribute]
public string RE { get; set; }
[XmlAttribute]
public string Stamp { get; set; }
public string PaymentID { get; set; }
}
In output get only XML. But must still pass the hash code.
I must send a response to a client request. And they want that at response body was hash and xml. And how it should look like I can not understand.
Related
I need to send body parameters using JSON. I'm working with Printify APIs.
I keep getting error response from server, that my body parameters are empty.
This is the command I'm trying to create:
POST https://api.printify.com/v1/uploads/images.json
it needs to includes the body parameters (that's an example from the API guide):
BODY PARAMETER (UPLOAD IMAGE BY BASE64-ENCODED CONTENTS)
{
"file_name": "image.png",
"contents": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
}
This is my code:
public class ImageContentsParams
{
public string FileName { get; set; }
public string Contents { get; set; }
}
ImageContentsParams imageContents = new ImageContentsParams();
imageContents.FileName = "example.png";
byte[] imageArray = System.IO.File.ReadAllBytes("D:\\example.png");
imageContents.Contents = Convert.ToBase64String(imageArray);
var json = JsonConvert.SerializeObject(imageContents);
using (HttpClient client = new HttpClient())
{
var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.printify.com/v1/uploads/images.json");
request.Content = jsonBody;
using (HttpResponseMessage res = await client.SendAsync(request))
{
// here I'm checking the returned response
}
}
I keep getting the following error response from Prinify server (this is after parsing):
Code: 10100
Message: Validation failed.
Reason:
file_name: The file name field is required.
contents: The contents field is required when url is not present.
url: The url field is required when contents is not present.
What am I doing wrong???
FileName property will be serialized into fileName and that will not match file_name convention. Change the property to match or specify mapping schema on the serialization to translate FileName into file_name.
You can do the mapping by specifyng [JsonProperty("file_name")] attribute on the FileName property. Something like this:
public class ImageContentsParams
{
[JsonProperty("file_name")]
public string FileName { get; set; }
public string Contents { get; set; }
}
Probably your FileName in JsonContentParams must be renamed to be the same as the JSON that is expected in that service. This is because the params will be serialized and will not match with the specification of the service.
public class ImageContentsParams
{
public string file_name { get; set; }
public string contents { get; set; }
}
Another solution can be to add the JsonProperty attribute, in order to not to refactor all your code.
public class ImageContentsParams
{
[JsonProperty("file_name")]
public string FileName { get; set; }
[JsonProperty("contents")]
public string Contents { get; set; }
}
Try something like that and tell me if it works.
I am calling SendGrid's Email Activity API using the RestSharp RestClient and it is properly returning data via a standard JSON response.
However, I'd like to deserialize that into a C# object since it would be much easier to work with than a raw JSON string. So I created a C# class that has public properties for each field in the JSON response, and gave them annotations with the exact name of the JSON fields.
But when I call JsonDeserializer().Deserialize>(response), while there's no error/exception, all of the fields in the objects are NULL.
Any ideas what's wrong? (You can just take out the "EventType" references as it's not really relevant here). Relevant code is below.
I'm using RestSharp v106.6.10.0 and Newtonsoft.Json v9.0.0.0 (the latter probably older but that's the library we normally use).
Project is .NET v4.6.1
private void QuerySendGridForEmailActivity(EventType eventType)
{
string query = string.Empty;
RestClient client = null;//new RestClient(emailActivityEndpoint);
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer " + apiKey);
request.AddParameter("limit", "1000");
if (eventType == EventType.Opens)
{
// request.AddParameter("query", WebUtility.UrlEncode("(Contains(events,\"open\"))"));
client = new RestClient(emailActivityEndpoint + "?limit=10&query=" + System.Web.HttpUtility.UrlPathEncode("(Contains(events,\"open\"))"));
}
IRestResponse response = client.Execute(request);
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
this.emailActivityEvents = new JsonDeserializer().Deserialize<List<EmailActivityEvent>>(response);
int i = 0;
}
else
{
}
}
public class EmailActivityEvent
{
[DeserializeAs(Name = "from_email")]
public string FromEmail { get;set; }
[DeserializeAs(Name = "msg_id")]
public string MessageId { get; set; }
[DeserializeAs(Name = "subject")]
public string Subject { get; set; }
[DeserializeAs(Name = "to_email")]
public string ToEmail { get; set; }
[DeserializeAs(Name = "status")]
public string Status { get; set; }
[DeserializeAs(Name = "opens_count")]
public int OpensCount { get; set; }
[DeserializeAs(Name = "clicks_count")]
public int ClicksCount { get; set; }
[DeserializeAs(Name = "last_event_time")]
public DateTime LastEventTime { get; set; }
}
Ok, I should've gotten this earlier but I didn't think I needed to do this.
I had to add another class that I named "EmailActivity" that just has a List<> of the email events, with a deserialize annotation matching the actual name of the item in JSON. Like this:
public class EmailActivity
{
[DeserializeAs(Name = "messages")]
public List<EmailActivityEvent> Events { get; set; }
}
Then just adjust the deserialize call slightly to this:
var emailActivity = new JsonDeserializer().Deserialize<EmailActivity>(response);
And that did it. Duh.
Just FYI, the JSON being returned was in this format:
{"messages":
[{
"from_email":"from#email.com",
"msg_id":"msgid",
"subject":"Test",
"to_email":"to#email.com",
"status":"delivered",
"opens_count":0,
"clicks_count":0,
"last_event_time":"2019-11-26T20:30:02Z"
},
{
"from_email":"from#email.com",
"msg_id":"msgid",
"subject":"Test",
"to_email":"to#email.com",
"status":"delivered",
"opens_count":0,
"clicks_count":0,
"last_event_time":"2019-11-26T20:30:01Z"
},
{
"from_email":"from#email.com",
"msg_id":"msgid",
"subject":"Test",
"to_email":"to#email.com",
"status":"delivered",
"opens_count":0,
"clicks_count":0,
"last_event_time":"2019-11-25T22:06:25Z"
}
]}
Thanks for your comments!
we're sending HTTP request to Bing maps with address details to get back the address map point. The response of the HTTP request is read as stream async, this stream is then deserialized to Bing response format. When I deserialize, I'm getting this error: System.Runtime.Serialization.SerializationException : Error while deserializing the object of type Previseo.Workflows.BingResponse. Unexpected character '<'.
Your help is so appreciated.
I've used Fiddler to see the response of bings which sends it back in the form of JSON:https://i.stack.imgur.com/LPIeW.png
JSON returned as text:
{"authenticationResultCode":"ValidCredentials","brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png","copyright":"Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.","resourceSets":[{"estimatedTotal":1,"resources":[{"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1","bbox":[46.175388336181641,5.1528801918029785,46.231620788574219,5.28734016418457],"name":"01000, Ain, France","point":{"type":"Point","coordinates":[46.203506469726563,5.2217612266540527]},"address":{"adminDistrict":"Auvergne-Rhone-Alpes","adminDistrict2":"Ain","countryRegion":"France","formattedAddress":"01000, Ain, France","locality":"Bourg-en-Bresse","postalCode":"01000"},"confidence":"High","entityType":"Postcode1","geocodePoints":[{"type":"Point","coordinates":[46.203506469726563,5.2217612266540527],"calculationMethod":"Rooftop","usageTypes":["Display"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"e1464a431e5e46b9854053ed8ae76ba8|DU00000D78|7.7.0.0|Ref A: 865592F3CBB74AD6ADA8A71D8344F297 Ref B: DB3EDGE0817 Ref C: 2019-08-07T07:56:20Z"}
private MapPoint GetAddressMapPoint(string address, string ville)
{
int idx;
string postal, city, url;
HttpClient client;
HttpResponseMessage apires;
DataContractJsonSerializer jsonSerializer;
BingResponse bingResp = null;
idx = ville.IndexOf(" ");
postal = ville.Substring(0, idx);
city = ville.Substring(idx + 1);
url = BING_MAPS_BASE_ADDRESS + $"REST/v1/Locations/FR/{postal}/{city}/{address.Trim()}?key={BingMapsKey}";
client = new HttpClient();
apires = client.GetAsync(url).Result;
jsonSerializer = new DataContractJsonSerializer(typeof(BingResponse));
Stream stream = apires.Content.ReadAsStreamAsync().Result;
bingResp = (BingResponse)jsonSerializer.ReadObject(stream); //here is where I'm getting the error 'Unexpected caracter '<'
if (bingResp.resourceSets.Count > 0)
{
if (bingResp.resourceSets[0].resources.Count > 0)
{
var point = bingResp.resourceSets[0].resources[0].point;
return point;
}
}
return null;
}
public class BingResponse
{
[DataMember]
public string authenticationResultCode { get; set; }
[DataMember]
public string brandLogoUri { get; set; }
[DataMember]
public string copyright { get; set; }
[DataMember]
public List<ResourceSet> resourceSets { get; set; }
[DataMember]
public int statusCode { get; set; }
[DataMember]
public string statusDescription { get; set; }
[DataMember]
public string traceId { get; set; }
}
I am attempting to work with a REST API using RestSharp and C#.
The documentation for the API that I am using gives a sample XML request:
<?xml version='1.0' encoding='UTF-8'?>
<messages>
<accountreference>EX0000000</accountreference>
<from>07700900654</from>
<message>
<to>07700900123</to>
<type>SMS</type>
<body>Hello Mr Sands.</body>
</message>
<message>
<to>07700900124</to>
<type>SMS</type>
<body>Hello Mr Mayo.</body>
</message>
</messages>
I am struggling to understand how to build the request in the format that they want (multiple elements called "message")
I have created these classes for RestSharp to serialize:
public class messages
{
public string accountreference { get; set; }
public string from { get; set; }
public message message { get; set; }
}
public class message
{
public string to { get; set; }
public string body { get; set; }
}
And here is my RestSharp code:
var client = new RestClient("http://api.url.com/v1.0")
{
Authenticator =
new HttpBasicAuthenticator(
UserName,
Password)
};
var request = new RestRequest("theresource", Method.POST) { RequestFormat = DataFormat.Xml };
request.AddBody(
new messages
{
accountreference = Configuration.AccountReference,
from = Configuration.From,
message =
new message { to = Configuration.Message.To, body = Configuration.Message.Body }
});
var response = client.Execute(request);
This works great when I have only 1 message element, but I don't know how to create multiple message elements without having them nested in an array, which doesn't work with the API.
By default RestSharp is using its own serializer but it also packs the DotNetSerializer so you achieve your goal by changing the serializer like this:
var request = new RestRequest("theresource", Method.POST)
{
RequestFormat = DataFormat.Xml,
XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer()
};
Then you can use a list of message objects and decorate it with XmlElement attribute:
public class messages
{
public string accountreference { get; set; }
public string from { get; set; }
[XmlElement("message")]
public List<message> messageList { get; set; }
}
public class message
{
public string to { get; set; }
public string body { get; set; }
}
Then you can change the last bit to add multiple messages:
request.AddBody(
new messages
{
accountreference = "ref",
from = "from",
messageList = new List<message>() {
new message { to = "to1", body = "body1" },
new message { to = "to2", body = "body2" }
}
});
which would produce (I got the XML by checking request.Parameters[0].Value):
<?xml version="1.0" encoding="utf-8"?>
<messages>
<accountreference>ref</accountreference>
<from>from</from>
<message>
<to>to1</to>
<body>body1</body>
</message>
<message>
<to>to2</to>
<body>body2</body>
</message>
</messages>
I guess this is the XML format you've been looking for.
Having message as list will work -
public class messages
{
public string accountreference { get; set; }
public string from { get; set; }
public List<message> message { get; set; }
}
public class message
{
public string to { get; set; }
public string body { get; set; }
}
Check the very last answer here -
How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
If you face issues with list, try this -
Can RestSharp send a List<string> in a POST request?
i use RestSharp to access a Rest API. I like to get Data back as an POCO.
My RestSharp Client looks like this:
var client = new RestClient(#"http:\\localhost:8080");
var request = new RestRequest("todos/{id}", Method.GET);
request.AddUrlSegment("id", "4");
//request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
//With enabling the next line I get an new empty object of TODO
//as Data
//client.AddHandler("*", new JsonDeserializer());
IRestResponse<ToDo> response2 = client.Execute<ToDo>(request);
ToDo td=new JsonDeserializer().Deserialize<ToDo>(response2);
var name = response2.Data.name;
my Class for the JsonObject looks like this:
public class ToDo
{
public int id;
public string created_at;
public string updated_at;
public string name;
}
and the Json Response:
{
"id":4,
"created_at":"2015-06-18 09:43:15",
"updated_at":"2015-06-18 09:43:15",
"name":"Another Random Test"
}
Per the documentation, RestSharp only deserializes to properties and you're using fields.
RestSharp uses your class as the starting point, looping through each
publicly-accessible, writable property and searching for a
corresponding element in the data returned.
You need to change your ToDo class to the following:
public class ToDo
{
public int id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string name { get; set; }
}