How can I post data in RestSharp ? I am very new to RestSharp and dont quite understand the process.
I am familar with Get Requests, which I have written API tests for with no problems.
Using the below example I want to post the Order Qty:
"name": "PostToCurrentBasket",
"class": [
"PostToCurrentBasket"
],
"method": "POST",
"href": "*",
"title": "Add Product to Current Basket",
"type": "application/json",
"fields": [
{
"name": "ProductId",
"type": "text",
"value": 101112,
"title": "Product ID"
},
{
"name": "Quantity",
"type": "number",
"value": 0,
"title": "Order Qty"
}
]
}
],
What I have so far:
var request = new RestRequest("baskets/current/", Method.POST);
Do I need to be using .AddBody and if so how do I use this correctly?
request.RequestFormat = DataFormat.Json; // If you want it to be json
request.AddBody(new { Name = "Foo", LastName = "Bar" }); // Any object that can be serialized
client.Execute(request);
Related
I am trying to serialize a FeatureCollection so I can pass it as a request body. To do this I am using a NetTopologySuite.IO.GeoJSON package and using the instruction they provide on their github page. The problem is, when hitting the jsonSerializer.Serialize method, I get an error saying: {"At least one element in the source array could not be cast down to the destination array type."} System.Exception {System.InvalidCastException}.
My method looks like this:
private async Task<IEnumerable<VehicleArea>> GetVehiclesInAreas(FeatureCollection areas)
{
var uri = $"www.someurl/getByArea";
using var httpClient = new HttpClient();
string stringifiedAreas;
var jsonSerializer = GeoJsonSerializer.CreateDefault();
using (var stringWriter = new StringWriter())
using (var jsonwriter = new Newtonsoft.Json.JsonTextWriter(stringWriter))
{
jsonSerializer.Serialize(jsonwriter, areas);
stringifiedAreas = stringWriter.ToString();
}
StringContent content = new StringContent(stringifiedAreas, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(uri, content);
}
The GEOSJON object I am passing in the request body of my controller, that ends up being the areas FeatureCollection provided to the given method looks like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 16,
"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
"coordinates": [
[
[
12.1234,
55.1234
],
[
12.7,
55.7],
[
12.8,
55.8
],
[
12.9,
55.9
],
[
12.1234,
55.1234
]
]
]
}
]
}
},
{
"type": "Feature",
"id": 16,
"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
"coordinates": [
[
[
12.1234,
55.1234
],
[
12.7,
55.7],
[
12.8,
55.8
],
[
12.9,
55.9
],
[
12.1234,
55.1234
]
]
]
}
]
}
}
]
}
Finally, here is a snippet of how the areas object looks like during runtime:
Thanks to #FObermaier's comment, I was able to implement a solution. As he mentioned, I am using a NetTopologySuite.IO.GeoJSON4STJ package which uses the System.Text.Json. By refactoring my code to use System.Text.Json.JsonSerializer, I was able to make it work. For anyone encountering the same issue, make sure to also pass the options object with the GeoJsonConverter factory added as a converter. Here is the code example:
var options = new JsonSerializerOptions();
options.Converters.Add(new NetTopologySuite.IO.Converters.GeoJsonConverterFactory());
var serialized = JsonSerializer.Serialize(areas, options);
var stringifiedAreas = serialized.ToString();
This is the sample on Botframework v4 docs. But it does not work.
It says "Can't Render Card" on the Microsoft bot emulator.
What i'm trying to do is a carouselCard but this simple card from Microsoft's sample is already not working.
{
"type": "message",
"text": "Plain text is ok, but sometimes I long for more...",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "TextBlock",
"text": "Hello World!",
"size": "large"
},
{
"type": "TextBlock",
"text": "*Sincerely yours,*"
},
{
"type": "TextBlock",
"text": "Adaptive Cards",
"separation": "none"
}
],
"actions": [
{
"type": "Action.OpenUrl",
"url": "http://adaptivecards.io",
"title": "Learn More"
}
]
}
}
]
}
However, if i remove the top part of the code this code works:
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "TextBlock",
"text": "Hello World!",
"size": "large"
},
{
"type": "TextBlock",
"text": "*Sincerely yours,*"
},
{
"type": "TextBlock",
"text": "Adaptive Cards",
"separation": "none"
}
],
"actions": [
{
"type": "Action.OpenUrl",
"url": "http://adaptivecards.io",
"title": "Learn More"
}
]
}
This is how i call the card. Is there a better way to do this?
public class GetNameAndAgeDialog : WaterfallDialog
{
private readonly string _cards = #".\Resources\TryCarouselCard.json";
private static Attachment CreateAdaptiveCardAttachment(string filePath)
{
var adaptiveCardJson = File.ReadAllText(filePath);
var adaptiveCardAttachment = new Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(adaptiveCardJson),
};
return adaptiveCardAttachment;
}
public GetNameAndAgeDialog(string dialogId, IEnumerable<WaterfallStep> steps = null) : base(dialogId, steps)
{
AddStep(async (stepContext, cancellationToken) =>
{
var cardAttachment = CreateAdaptiveCardAttachment(_cards);
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>() { cardAttachment };
await stepContext.Context.SendActivityAsync(reply, cancellationToken);
return await stepContext.ContinueDialogAsync();
});
}
}
The "top part" of the first block of JSON you posted is the card contained within an activity. The second block of JSON posted is indeed just the card itself and what you'd want to put into an Attachment.
As for your code, it looks correct to me. I might consider caching the attachment JSON as you probably don't want to hit the file system every time you want to display the card, but that would just be an optimization.
I'm unclear if you are experiencing any further problems or just looking for validation of the approach now. If you are still experiencing a problem please update the question with some more details and I'll update my answer to try and help.
I am planning to write a simple SugarCrm .Net client.
Could anyone give me a pointer to a .Net wrapper/library for the SugarCrm REST api?
//lasse
Realize this is old, but in case anyone stumbles across this looking for a .NET wrapper for newer version of the web service (SugarCRM > 6.7), here is a wrapper I am currently building https://github.com/dlively1/SugarSharp
There is a wrapper that uses SOAP called CandyWrapper, which is a bit old but could help you with a starting point on building your own.
http://developers.sugarcrm.com/wordpress/2011/08/10/web-services-in-your-own-language-part-6-candywrapper-for-net/
I also realize this is old, but for SugarCRM CE 6.x I created SugarRestSharp. The sample I give below is in json, but the request would be in C# models. This implements get_entry_list SugarCrm Rest API method.
Passing request to RestSharp:
dynamic data = new
{
session = sessionId,
module_name = moduleName,
query = queryString,
order_by = string.Empty,
offset = 0,
select_fields = selectFields,
link_name_to_fields_array = string.Empty,
max_results = maxCountResult,
deleted = 0,
favorites = false
};
var client = new RestClient(url);
var request = new RestRequest(string.Empty, Method.POST);
string jsonData = JsonConvert.SerializeObject(data);
request.AddParameter("method", "get_entry_list");
request.AddParameter("input_type", "json");
request.AddParameter("response_type", "json");
request.AddParameter("rest_data", jsonData);
var response = client.Execute(request);
Request in json
{
"session": "olgg6hf5sqi6hk9u3tgpafbn66",
"module_name": "Accounts",
"query": "",
"order_by": "",
"offset": 0,
"select_fields": [
"name",
"industry",
"website",
"shipping_address_city",
"id"
],
"link_name_to_fields_array": "",
"max_results": 10,
"deleted": 0,
"favorites": false
}
Response in json
{
"result_count": 10,
"total_count": "58",
"next_offset": 10,
"entry_list": [
{
"id": "1e0eec64-8cc6-58ff-57f1-58533731b145",
"module_name": "Accounts",
"name_value_list": {
"name": {
"name": "name",
"value": "New SugarRestSharp Acccount 1 10397"
},
"industry": {
"name": "industry",
"value": "Manufacturing"
},
"website": {
"name": "website",
"value": "www.sugarrestsharp1.com"
},
"shipping_address_city": {
"name": "shipping_address_city",
"value": "Los Angeles"
},
"id": {
"name": "id",
"value": "1e0eec64-8cc6-58ff-57f1-58533731b145"
}
}
},
......... (other 9 items truncated)
],
"relationship_list": [
]
}
For more implementation and wiki check SugarRestSharp: https://github.com/mattkol/SugarRestSharp
I started testing OrientDB. I get the following JSON Response from the Demo Database:
{
"schema":{
"name":"OUser",
"properties":{
"roles":{
"name":"roles",
"linkedClass":"ORole",
"type":"LINKSET",
"mandatory":false,
"notNull":true,
"min":null,
"max":null
},
"name":{
"name":"name",
"type":"STRING",
"mandatory":true,
"notNull":false,
"min":null,
"max":null
},
"password":{
"name":"password",
"type":"STRING",
"mandatory":true,
"notNull":false,
"min":null,
"max":null
}
}
},
"result":[
{
"#type":"d",
"#rid":"#4:0",
"#version":0,
"#class":"OUser",
"name":"admin",
"password":"{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873FC4BB8A81F6F2AB448A918",
"status":"ACTIVE",
"roles":[
"#3:0"
]
},
{
"#type":"d",
"#rid":"#4:1",
"#version":0,
"#class":"OUser",
"name":"reader",
"password":"{SHA-256}3D0941964AA3EBDCB00CCEF58B1BB399F9F898465E9886D5AEC7F31090A0FB30",
"status":"ACTIVE",
"roles":[
"#3:1"
]
},
{
"#type":"d",
"#rid":"#4:2",
"#version":0,
"#class":"OUser",
"name":"writer",
"password":"{SHA-256}B93006774CBDD4B299389A03AC3D88C3A76B460D538795BC12718011A909FBA5",
"status":"ACTIVE",
"roles":[
"#3:2"
]
}
]
}
How can you get a List of OUser Objects out of that? Using JSON.Net, JavaScriptSerializer or whatever?
There are a number of json parsers for c# at:
http://www.json.org/. It seems like fastJSON should be pretty quick.
Once logged in execute a query against OUser class:
select from ouser
Via HTTP protocol would be a GET request against this address:
http://localhost:2480/query/demo/sql/select%20from%20ouser
{
"result": [{
"#type": "d", "#rid": "#4:0", "#version": 0, "#class": "OUser",
"name": "admin",
"password": "{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873FC4BB8A81F6F2AB448A918",
"status": "ACTIVE",
"roles": ["#3:0"]
}, {
"#type": "d", "#rid": "#4:1", "#version": 2, "#class": "OUser",
"name": "reader",
"password": "{SHA-256}3D0941964AA3EBDCB00CCEF58B1BB399F9F898465E9886D5AEC7F31090A0FB30",
"status": "ACTIVE",
"roles": ["#3:1"]
}, {
"#type": "d", "#rid": "#4:2", "#version": 0, "#class": "OUser",
"name": "writer",
"password": "{SHA-256}B93006774CBDD4B299389A03AC3D88C3A76B460D538795BC12718011A909FBA5",
"status": "ACTIVE",
"roles": ["#3:2"]
}
]
}
this looks like an easy structure to deserialise using json.NET
I've successfully created code that serializes a complex javascript object and posts it to an ASP.NET page. I can get the JSON string using Request.Form and the result looks like this (I've added indentation for readability):
{
"gasterPerStolPerVecka": {
"name": "gasterPerStolPerVecka",
"keyValue_id": "2",
"set_id": "1",
"containerElement": "#gasterPerStolPerVecka",
"keyValueComponents": [
{
"name": "gasterPerStolPerVecka_guestsPerWeek",
"value": "200"
},
{
"name": "gasterPerStolPerVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "gäster/stol per vecka",
"keyValueCalculationMethod": "divide",
"isValid": true,
"result": 2
},
"tillgangligaStolstimmarPerVecka": {
"name": "tillgangligaStolstimmarPerVecka",
"keyValue_id": "1",
"set_id": "1",
"containerElement": "#tillgangligaStolstimmarPerVecka",
"keyValueComponents": [
{
"name": "tillgangligaStolstimmarPerVecka_openHoursPerWeek",
"value": "35"
},
{
"name": "tillgangligaStolstimmarPerVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "stolstimmar/vecka",
"keyValueCalculationMethod": "multiply",
"isValid": true,
"result": 3500
},
"planeradIntaktPerTillgangligStolOchVecka": {
"name": "planeradIntaktPerTillgangligStolOchVecka",
"keyValue_id": "",
"set_id": "",
"containerElement": "#planeradIntaktPerTillgangligStolOchVecka",
"keyValueComponents": [
{
"name": "planeradIntaktPerTillgangligStolOchVecka_weeklyRevenue",
"value": ""
},
{
"name": "planeradIntaktPerTillgangligStolOchVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "kr",
"keyValueCalculationMethod": "divide",
"isValid": false,
"result": null,
"errorText": "Ofullständigt underlag för beräkning."
},
"planeradIntaktPerTillgangligaStolstimmar": {
"name": "planeradIntaktPerTillgangligaStolstimmar",
"keyValue_id": "",
"set_id": "",
"containerElement": "#planeradIntaktPerTillgangligaStolstimmar",
"keyValueComponents": [
{
"name": "planeradIntaktPerTillgangligaStolstimmar_weeklyRevenue",
"value": ""
},
{
"name": "planeradIntaktPerTillgangligaStolstimmar_openHoursPerWeek",
"value": "35"
},
{
"name": "planeradIntaktPerTillgangligaStolstimmar_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "kr",
"keyValueCalculationMethod": "divide_divide",
"isValid": false,
"result": null,
"errorText": "Ofullständigt underlag för beräkning."
}
}
Now I try to deserialize this on the server side, but it's difficult. I keep getting the error:
[NullReferenceException: Object reference not set to an instance of an object.]
I don't know where to start looking for errors?
Thanks in advance!
/Thomas Kahn
use stringify instead serialization
You need to use a deserialization library for ASP.NET. See http://json.org/ for libraries that are available or maybe there is one built into ASP.NET. Either way, the code will look like:
String s = getAppropriateFormField();
Object o = JSONLibraryPackage.parse(s);
where obviously you'll have to fill in the blanks for how you get the form field and then what package and method does the parsing.