Im using the neo4j Client v4.0.0.1 and want to create just a single node from a class but Im always getting the following 404 error.
Error Code:
System.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: '
If I use curl to check if all is fine:
curl -I localhost:7474
HTTP/1.1 200 OK
Date: Tue, 25 Feb 2020 14:23:18 GMT
Access-Control-Allow-Origin: *
Content-Type: application/json;charset=utf-8
Content-Length: 223
And:
curl -I http://localhost:7474/db/data
HTTP/1.1 302 Found
Date: Tue, 25 Feb 2020 14:23:26 GMT
Location: http://localhost:7474/db/data/
Content-Length: 0
all seems to be fine. Thats my try Id like to start with:
public class Person
{
public string Name { get; set; }
public int Id { get; set; }
public int Age { get; set; }
}
private void createNode(){
var client = new GraphClient(new Uri("http://localhost:7474/db/data/"), "neo4j", "neo4j");
client.Connect();
var results = client.Cypher
.Create("(n:Person)")
.Return((a) => new {
Person = a.As<Person>()
}).Results;
}
I recommend using Neo4j driver. I'm not sure that neo4j client .net library has support with Neo4j 4.0. Also, you can return to 3.5 version
Related
I'm trying to consume a public endpoint to get a list of objects in json. However, the API implements the OData protocol, and it always returns an invalid request. I think it's due to the way of calling this API. What should I adapt to my code to consume this API?
This is my code:
[HttpGet]
public async Task<List<TaxaSelic>> ObterTaxaSelic()
{
List<TaxaSelic> taxasSelic = new List<TaxaSelic>();
string apiResponse = string.Empty;
Uri uri = new Uri("https://api.bcb.gov.br/dados/serie/bcdata.sgs.4390/dados/ultimos/10/");
using (HttpClient httpClient = new HttpClient())
{
using (HttpResponseMessage response = await httpClient.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
apiResponse = await response.Content.ReadAsStringAsync();
taxasSelic = JsonConvert.DeserializeObject<List<TaxaSelic>>(apiResponse);
}
}
return taxasSelic;
}
and...
public class TaxaSelic : Entity
{
[JsonProperty("data")]
public string Data { get; set; }
[JsonProperty("valor")]
public string Valor { get; set; }
}
The website's server in some way checks the caller's user-agent. When I set a user-agent as following, it works like a charm.
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Linux; Android 9; SM-G973U Build/PPR1.180610.011) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile " +
"Safari/537.36");
using (HttpResponseMessage response = await httpClient.GetAsync(uri))
{
... rest of your code
.
.
.
Example output I got,
HTTP/1.1 200 OK
ETag: W/"173-8/kblablablaMdY/QZ9jQ"
Access-Control-Allow-Origin: *
Date: Mon, 18 Jul 2022 11:48:19 GMT
Set-Cookie: cookie_p=!ptxb5qIxn7aCp0blablablablaTOUoak=; path=/; Httponly; Secure
Set-Cookie: TS01799025=01blablablacae675f; Path=/
Strict-Transport-Security: max-age=16070400; includeSubDomains
Content-Type: application/json; charset=utf-8
Content-Length: 371
[{"data":"01/10/2021","valor":"0.49"},{"data":"01/11/2021","valor":"0.59"},{"data":"01/12/2021","valor":"0.77"},{"data":"01/01/2022","valor":"0.73"},{"data":"01/02/2022","valor":"0.76"},{"data":"01/03/2022","valor":"0.93"},{"data":"01/04/2022","valor":"0.83"},{"data":"01/05/2022","valor":"1.03"},{"data":"01/06/2022","valor":"1.02"},{"data":"01/07/2022","valor":"0.54"}]
I am writing a WinForms program (C#) using System.Net.Http.HttpClient to download webpages.
I'd like to get verbose info of the HTTP(S) requests like the following from libcurl:
* Trying xxx.xxx.xxx.xxx...
* TCP_NODELAY set
* Connected to xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx) port xxxx (#3)
* allocate connect buffer!
* Establish HTTP proxy tunnel to www.amazon.com:443
-> CONNECT www.amazon.com:443 HTTP/1.1
-> Host: www.amazon.com:443
-> User-Agent: libcurl/7.64.1 r-curl/4.3.2 httr/1.4.2
-> Proxy-Connection: Keep-Alive
->
<- HTTP/1.1 200 Connection established
<-
* Proxy replied 200 to CONNECT request
* CONNECT phase completed!
* CONNECT phase completed!
* CONNECT phase completed!
-> GET /xxxxxxx HTTP/1.1
-> Host: www.amazon.com
-> User-Agent: libcurl/7.64.1 r-curl/4.3.2 httr/1.4.2
-> Accept-Encoding: deflate, gzip
-> Cookie: session-id-time=xxxxxx; i18n-prefs=USD; session-id=xxxx; sp-cdn="L5Z9:SG"
-> Accept: application/json, text/xml, application/xml, */*
->
<- HTTP/1.1 200 OK
<- Server: Server
<- Content-Type: text/html;charset=UTF-8
<- x-amz-rid: xxxx
<- X-Content-Type-Options: nosniff
<- Expires: -1
<- X-XSS-Protection: 1;
<- Content-Language: en-US
<- Pragma: no-cache
<- Accept-CH-Lifetime: 86400
<- Cache-Control: no-cache
<- Content-Encoding: gzip
<- Accept-CH: ect,rtt,downlink
<- Strict-Transport-Security: max-age=47474747; includeSubDomains; preload
<- Vary: Content-Type,X-Amazon-Wtm-Tag-SP-Search-Secured-Port-Enabled,Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent
<- X-Frame-Options: SAMEORIGIN
<- Permissions-Policy: interest-cohort=()
<- Date: Tue, 04 Jan 2022 05:06:02 GMT
<- Transfer-Encoding: chunked
<- Connection: keep-alive
<- Connection: Transfer-Encoding
* Added cookie ubid-main="xxxx" for domain amazon.com, path /, expire 1672808762
<- Set-Cookie: ubid-main=xxx; Domain=.amazon.com; Expires=Wed, 04-Jan-2023 05:06:02 GMT; Path=/; Secure
<-
* Connection #3 to host xxx.xxx.xxx.xxx left intact
How do I get this kind of message in real time? I am not looking for capturing exceptions.
I understand there are answers using the app.config to create logs, but this kind of solution is not useful here because the log file is locked while the program is running. So I can't really read the log file of the program and show the content in the same program.
From the moment you can't use the logs, a good approach in this case, would be to create a function which is going to print all the data that you need just like libcurl. You may not get the info in real time just like curl or the logging but you'll have the data available to be used in your code without reading another file.
There is also CurlSharp but it doesn't receive a commit since 2017, although it contains many features used in the official libcurl. Beside the commits, you would also need to update the .NET version and the code.
Let's say that you want to do a Get Request, you would do something like this:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
With the HttpResponseMessage you can print many properties related to the request, in particular with the Headers property, you can use the HttpResponseHeaders class to print other properties such as the Connection, the Pragma or the Server. Here's an example:
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
//if you need it
//string responseBody = await response.Content.ReadAsStringAsync();
PrintHttpGetResponse(response);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
void PrintHttpGetResponse(HttpResponseMessage response) {
Console.WriteLine($"Content Type ---> {response.Content.Headers.ContentType}");
Console.WriteLine($"Status Code ---> {response.StatusCode}");
Console.WriteLine($"Headers ---> {response.Headers}");
Console.WriteLine($"Connection ---> {response.Headers.Connection}");
Console.WriteLine($"IsSuccessStatusCode ---> {response.IsSuccessStatusCode}");
}
You could also use some kind of Model with all the properties that you need, to save the response content and share it with other layers or classes easily in your code. For example:
using System.Net;
using System.Net.Http.Headers;
public class ResponseContent {
MediaTypeHeaderValue ContentType { get; set; }
HttpStatusCode StatusCode { get; set; }
HttpResponseHeaders Headers { get; set; }
HttpHeaderValueCollection<string> Connection { get; set; }
bool IsSuccessStatusCode { get; set; }
}
I have a problem with post request with RestSharp. I have 2 classes:
public class UnitToPost
{
public bool floating_point { get; set; }
public Dictionary<string, TranslationUnitToPost> translations { get; set; }
}
public class TranslationUnitToPost
{
public string name { get; set; }
}
And I want to send it with post request:
client = new RestClient(adresApi);
client.AddDefaultHeader("Authorization", "Bearer " + key);
IRestRequest updateProduct = new RestRequest("units", Method.POST);
ShoperModel.UnitToPost unitToPost = new ShoperModel.UnitToPost();
unitToPost.floating_point = true;
ShoperModel.TranslationUnitToPost transUnit = new ShoperModel.TranslationUnitToPost();
transUnit.name = "namename";
unitToPost.translations = new Dictionary<string, ShoperModel.TranslationUnitToPost>();
unitToPost.translations.Add("pl_PL", transUnit);
updateProduct.RequestFormat = RestSharp.DataFormat.Json;
updateProduct.AddBody(unitToPost);
IRestResponse updateProductResponse = this.client.Execute(updateProduct);
And I always get an error:
[RestSharp.RestResponse] = "StatusCode: InternalServerError,
Content-Type: application/json, Content-Length: -1)"
Content =
"{\"error\":\"server_error\",\"error_description\":\"Operation
Failed\"}"
What is the cause of it? Could it be because of Dictionary in my class?
I've run your code and it issues a request with a valid JSON body.
POST http://..../units HTTP/1.1
Accept: application/json,application/xml, text/json, text/x-json, text/javascript, text/xml
Authorization: Bearer a
User-Agent: RestSharp/105.2.3.0
Content-Type: application/json
Host: .....
Content-Length: 84
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{"floating_point":true,"translations":[{"Key":"pl_PL","Value":{"name":"namename"}}]}
It looks like the problem may be with the receiving server. If you're not doing so already I'd suggest running Fiddler (http://www.telerik.com/fiddler) and inspecting the request/response.
Edit...
I only just realised you want the JSON body to be :-
{"floating_point":true,"translations":{"pl_PL":{"name":"namename"}}}
I did find a RestSharp issue that covers this :-
https://github.com/restsharp/RestSharp/issues/696
This includes a post where someone has used an ExpandoObject to get the required result.
http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/
However, I found it easier to use JSON .NET to serialise and set the body with the following code:-
updateProduct.AddBody(JsonConvert.SerializeObject(unitToPost));
Hi I try to call an web api by server side with:
using (var client = new HttpClient())
{
using (var rsp = client.PostAsJsonAsync<Request>(url, model).Result)
{
if (!rsp.IsSuccessStatusCode)
{
// throw an appropriate exception
}
var result = rsp.Content.ReadAsAsync<string>().Result;
}
}
but I get error
Error reading string. Unexpected token: StartObject. Path '', line 1, position 1.
If I try to call same url from jQuery
$.post('http://localhost/api/Test')
the server return
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 25 Oct 2015 12:15:56 GMT
Content-Length: 104
{
"Header": {
"Token": "Response",
"Timestamp": "2015-10-25T14:15:56.0092197+02:00"
}
}
The "model" arrive on api controller but I can't get response from request.
ReadAsAsync<T> attempts to deserialize the response to type T. In this case, you're saying you want to deserialize JSON to a string, which doesn't really make sense. Either use a type matching the response (i.e. a custom data structure containing Header, Token, etc.) or use ReadAsStringAsync() if you really want to get a string.
I'm having trouble renaming a folder inside a document library using the REST api provided by SharePoint 2013. Here is the code I'm using below.
string digest = String.Empty;
using (var response = await connector.HttpClient.PostAsync("_api/contextinfo", null, token))
{
response.EnsureSuccessStatusCode();
var obj = await response.ReadObject("d");
digest = obj["GetContextWebInformation"].Value<string>("FormDigestValue");
}
using (var request = new HttpRequestMessage(HttpMethod.Post, String.Format("/_api/Web/GetFolderByServerRelativeUrl('{0}')", operation.Path.FullName)))
{
request.Headers.Add("X-HTTP-Method", "MERGE");
request.Headers.Add("IF-MATCH", "*");
request.Headers.Add("X-RequestDigest", digest);
//{ '__metadata': { 'type': 'SP.Folder' }, 'Name': 'New name' }
dynamic obj = new JObject();
obj.__metadata = new JObject();
obj.__metadata.type = "SP.Folder";
obj.Name = operation.DesiredName;
request.Content = new ODataJObjectContent(obj);
using (var response = await connector.HttpClient.SendAsync(request, token))
{
response.EnsureSuccessStatusCode();
await response.ReadText();
}
}
In Fiddler here is the request:
POST http://2013.blah.com/_api/Web/GetFolderByServerRelativeUrl('/Shared%20Documents/Test') HTTP/1.1
X-HTTP-Method: MERGE
IF-MATCH: *
X-RequestDigest: 0xA7C057B3AECE805B7313909570F64B8EACD7A677014B8EBE7F75CC5A7C081F87973D94E7CC22346964ECAB1FE3C6B326DA3B67DF7A646FE6F47E9B1E686C3985,11 Apr 2013 15:13:05 -0000
Accept: application/json; odata=verbose
Content-Type: application/json; odata=verbose
Host: 2013.skysync.com
Content-Length: 50
Expect: 100-continue
{"__metadata":{"type":"SP.Folder"},"Name":"Test2"}
And then the response:
HTTP/1.1 204 No Content
Cache-Control: private, max-age=0
Expires: Wed, 27 Mar 2013 15:13:15 GMT
Last-Modified: Thu, 11 Apr 2013 15:13:15 GMT
Server: Microsoft-IIS/8.0
X-SharePointHealthScore: 0
SPClientServiceRequestDuration: 15
X-AspNet-Version: 4.0.30319
SPRequestGuid: 53bd109c-43bb-2064-4a1b-82298b670ece
request-id: 53bd109c-43bb-2064-4a1b-82298b670ece
X-RequestDigest: 0x9CDB4F31CC5F3877C4383657C12BEC6CFF10FC28AB6A0BB2D9D38B4279187CBD1450359BDFF07F0E63FF550BFF96C46E0476FB895CDA104348AC066D86246BC6,11 Apr 2013 15:13:15 -0000
X-FRAME-OPTIONS: SAMEORIGIN
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 15.0.0.4420
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
Date: Thu, 11 Apr 2013 15:13:15 GMT
Everything looks good until I go back to SharePoint and the Test folder is still the same name. I'm following the guidelines from here and I've seen other very similar examples. I can rename it through the interface without any problem.
Thanks in advance for any help!
The following example demonstrates how to rename Folder via SharePoint 2013 REST service
Scenario: rename Archive folder to 2015 located in Documents
library
using (var client = new SPHttpClient(webUri, userName, password))
{
RenameFolder(client, webUri.ToString(),"Documents/Archive","2015");
}
where
private static void RenameFolder(SPHttpClient client, string webUrl,string folderUrl,string folderName)
{
var folderItemUrl = webUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/ListItemAllFields";
var data = client.ExecuteJson(folderItemUrl);
var itemPayload = new {
__metadata = new { type = data["d"]["__metadata"]["type"] },
Title = folderName,
FileLeafRef = folderName,
};
var itemUrl = data["d"]["__metadata"]["uri"];
var headers = new Dictionary<string, string>();
headers["IF-MATCH"] = "*";
headers["X-HTTP-Method"] = "MERGE";
client.ExecuteJson((string)itemUrl, HttpMethod.Post, headers, itemPayload);
}
Note:
SPHttpClient class - inherits from HttpClient and provides some additional SharePoint specific functionaly such as getting
request digest
SPHttpClientHandler class - hides all the intricacies related to SharePoint Online authentication
Try to add list in your manifest file. It seems like a permissions problem, and when you have to "trust" an application then choose the list which you want to operate with.