I have created a new iPhone (iOs 9.3) app with Xamarin from within Visual Studio 2015 update 2. I have Xamarin beta channel on the mac (which has Xcode etc.)
I have this code:
using Windows.Web.Http;
...
private async void GetPois()
{
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://onlinesource/json"));
}
and I get the error on the GetAsync I do not have the httpclient nuget installed, because it threw an error.
already had ModernHttpClient nuget installed, but did not use it. #Andrii Krupka yes I also have using System;
I added System.Net.Http instead of Windows but now I have type or namespace could not be found. added a reference to both system.net and system.net.http and now it works. next thing to solve is to disable ats. will mark this as answered by #SushiHangover thanks everyone!
Use the namespace System.Net.Http instead of Windows.....
Then your HttpClient will work fine under iOS, assuming your have disable ATS since that is a non-secure HTTP link... ;-)
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://onlinesource/json"));
On a personal note: I greatly prefer ModernHttpClient #
https://github.com/paulcbetts/modernhttpclient
(Cross platform, PCL, cleaner, faster, able to leap buildings in a single request, etc...)
Related
I am trying to do a test post to a 3rd party web api.
The code how to post was provided by the documentation from 3rd party.
'RestClient' is a namespace but is used like a type
The type or namespace name 'RestRequest' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'IRestResponse' could not be found (are you missing a using directive or an assembly reference?)
The name 'ParameterType' does not exist in the current context
The name 'Method' does not exist in the current context
The method I am working with:
public void CreatePanelists (Newtonsoft.Json.Linq.JObject data)
{
Parameters parameters = JsonConvert.DeserializeObject<Parameters>(data.ToString())
IList<Panelist> panelistList = parameters.panelists;
string id = parameters.id;
var client = new RestClient("https://3rdparty.com/v2/events/5893/atendees");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer vJRMZ92lsOE1sKGVF7_4zCezTjxO2RoFeOVGULSJS2_dRhgU5QfZeKqGaoS0ogPv0WISEuZ1RcNzJDUsv27uGA");
request.AddParameter("application/json", "{\"attendees\":[{\"name\":\"Mary\",\"email\":\"maryjkdfdsgfshdgf#jdfdkjdglfk.jkfgdj\"},{\"name\":\"Mike\",\"email\":\"dfdsgfsdhf#jkgfdgfkdhgfdjg.fkjgdf\"}]}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}
I installed RestClient 4.0.0 but that did not remove the errors.
I am not using .Net not .net Core. What am I missing?
First time developing this type of project, please pardon if my technical language is not correct.
Your help is much appreciated.
Thank you,
Erasmo
UPDATE - I was able to install RestSharp Version 106.11.4.0, and RestClient Version 2.5.0.6.
The only error that persists is
'RestClient' is a namespace but is used like a type
It seems like you missed to include namespace for the use of RestClient package. use the following namespace at top of the file.
using RestSharp;
Also, you should install nuget package before use this RestClient package. If not installed , then use follow command in Nuget package manager console.
PM> install-package RestSharp
The RestSharp code you're using is out of date for .Net Full Framework < 5.0.
The new RestSharp syntax looks like this: https://restsharp.dev/intro.html#basic-usage
using RestSharp;
using RestSharp.Authenticators;
var client = new RestClient("https://api.twitter.com/1.1");
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest("statuses/home_timeline.json", DataFormat.Json);
var timeline = await client.GetAsync<HomeTimeline>(request, cancellationToken);
I've raised a support request #98090 to PostMan to update the RestSharp Code Generated.
First you need to uninstall the RestClient packages :
Manage -> nuget packages
Then install Restsharp package.
PM -> install-package RestSharp
then use using RestSharp
Using RestSharp.RestClient would resolve the error. You would not need RestClient package.
i'm using the Microsoft Graph Apps to retrieve or create OneDrive files. I made a POC last week and everything worked wonderfully.
Now i tried implementing the our App into an existing MVC website but i'm having weird messages that System.Threading.Tasks.Task cannot be found:
at Microsoft.Graph.DriveRequest.<GetAsync>d__6.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Graph.DriveRequest.GetAsync(CancellationToken cancellationToken)
at Microsoft.Graph.DriveRequest.GetAsync()
at BizzMine.Data.Repositories.OnlineEditorRepo.OnlineEditorRepository.<RequestSuccess>d__10.MoveNext() in C:\Users\geertverthe\Documents\repos\bizzmine\BizzMine.Data.Repositories\OnlineEditorRepo\OnlineEditorRepository.cs:line 89
I suspect that there is some kind of problem with binding references to System.Threading.Tasks or even System.Web.Http but i am not sure.
This is the (simple) code i use:
Drive myDrive = await _graphServiceClient.Me.Drive.Request().GetAsync();
And my GraphServiceClient is constructed like this:
_graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => {
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", _tokens.AccessToken);
await Task.FromResult<object>(null);
}));
.NET Framework version is 4.6.1
I do have the correct consent permissions and do have a valid access token.
Any idea on why i receive such kind of error and how i can fix this?
Thank you very much
After lot of trying i managed to solve my issue. Since our solution and projects contain lots of nuget packages, one of them was system.net.http. Apparantly this came with a package NETStandard.Library.1.6.1.
I found it strange to have a nuget package for system.net.http as this is just in the framework itself.
I could delete the system.net.http nuget packages after upgrading NETSTandard.Library.1.6.1 to the latest version.
Only changes i had to do after this was referencing the FRAMEWORK system.net.http in projects where it was missing and removing an obsolete binding redirect in some projects.
It works fine now :-)
I'm trying to write an application that communicates with Visual Studio Team Services, using the Nuget packages listed here.
The example code is directly from Microsoft's official documentation, on same same page the packages are listed, under "Pattern for use". My test code is in a console application, set to version 4.7 of the .net framework (compiled by Visual Studio 2017 15.2(26430.16) Release, but I don't think that matters). The code is identical to Microsoft's example, other than changing the connection url, project, and repo name.
The only Nuget package directly installed (about 30 others are installed as dependencies) is Microsoft.TeamFoundationServer.ExtendedClient.
Install-Package Microsoft.TeamFoundationServer.ExtendedClient
using System;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
namespace vssApiTest
{
class Program
{
const String c_collectionUri = "https://[[redacted]].visualstudio.com/DefaultCollection";
const String c_projectName = "Inspections";
const String c_repoName = "Src";
static void Main(string[] args)
{
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to VSTS
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
// Get a GitHttpClient to talk to the Git endpoints
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
// Get data about a specific repository
var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;
}
}
}
On the line VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);, a TypeLoadException is thrown (at run-time) with the message:
Inheritance security rules violated by type:
'System.Net.Http.WebRequestHandler'. Derived types must either match
the security accessibility of the base type or be less accessible.
None of the Google search variants I've tried on this error message have returned anything helpful.
Am I doing something wrong, is the example code I'm following wrong, or is there some other issue going on?
The problem was due to a bug introduced in version 4.1.0 of the System.Net.Http Nuget package, as discussed here.
The solution was to update that Nuget package to the latest version (4.3.2 at this time, it may have been fixed in earlier versions also).
Ive got Web API project which hosts data service. Everything is ok and I can consume it from console client using this code:
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:15017/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products");
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsAsync<List<Product>>();
foreach (var product in products)
{
Console.WriteLine(product.Name);
Console.WriteLine(product.Description);
Console.WriteLine(product.ShortDescription);
Console.WriteLine(product.Prize);
Console.WriteLine("\n");
}
}
}
}
private static void Main(string[] args)
{
RunAsync().Wait();
}
Works perfect.
Than I have windows phone 8 app. It has such a structure that I have ViewModels which create instances of IRepository interfaces. I try to connect to web api and load data from IRepository classes using the same code as in my console app but when I try to add reference to System.Net.Http.Formatting which is needed Ive got an error whiole installing package:
Adding 'Microsoft.AspNet.WebApi.WebHost 5.1.2' to PhoneApp.
Install-Package : Could not install package 'Microsoft.AspNet.WebApi.WebHost 5.1.2'. You are trying to install this package into a project that
targets 'WindowsPhone,Version=v8.0', but the package does not contain any assembly references or content files that are compatible with that
framework. For more information, contact the package author.
So how can I consume web api from inside my windows phone app ?
I am relatively new to WP8 development and have come across a problem that i just cannot figure out, even after hours of googling.
I am using visual studio 2012 and have implemented System.Net.Http using NuGet, have checked references, copy local is set to true, but it will not build.
This is the error message which greets me:
CA0001 Error Running Code Analysis CA0001 : The following error was encountered while reading module '3D Protect Premium': Could not resolve member reference: [System.Net.Http, Version=1.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]System.Net.Http.HttpClient::PostAsync. [Errors and Warnings] (Global)
How do i fix this so the referenced version is correct??
Edit
Code added below. This doesnt seem to be problematic, its just the referencing - i think its me misunderstanding to be honest, i Just dont have a clue whats going on with the System.Net.Http assembly!!
//Creates a new HttpClient Instance
var client = new HttpClient();
// This is the postdata
// Data forms an array and is used to populate the remote MySQL DB
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("name", "windowsphonetest"));
postData.Add(new KeyValuePair<string, string>("latitude", LatitudeString));
postData.Add(new KeyValuePair<string, string>("longitude ", LongitudeString));
postData.Add(new KeyValuePair<string, string>("devID", "test"));
HttpContent content = new FormUrlEncodedContent(postData);
//The actual HTTP Transaction
client.PostAsync("http://blah.com", content).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
The System.Net.Http package you're trying to use has been deprecated but you can use Microsoft.Net.Http instead.
Solution: Delete all dependent NuGet packages, cleaning solution, deleting references to System.Net.* assemblies.
Install Microsoft.Net.Http and its dependencies as suggested by NuGet. Then install Microsoft.Bcl.Async - this is a dependency which is not flagged by NuGet (thanks keyboardP)
Now go into project properties and disable 'Code analysis on build' - this tool is tripping up over the version number for some reason. Now the code builds and deploys fine.