How to reference System.Net.Http in WP8? - c#

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.

Related

Could not load file or assembly Microsoft.IdentityModel.Tokens problem

I am trying to verify users with a JWT token. The code I used below works perfectly fine in a console application. But when I want to apply it in my Azure function it gives me the error:
Could not load file or assembly Microsoft.IdentityModel.Tokens
I do have one other Azure function in my solution but it doesn't use this NuGet package. I already took a look at this link:
Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=5.2.0.0
I can't get anything out of that. So what am I doing wrong? Thanks in advance
string key = "";
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);
var payload = new JwtPayload
{
{ "some ", "hello "},
{ "scope", "http://dummy.com/"},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var tokenString = handler.WriteToken(secToken);
var token = handler.ReadJwtToken(tokenString);
log.LogInformation(token.ToString());
Solved it by adding a line of code in the .csproj file
<PropertyGroup>
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>
I had this problem not when running in development, but on deployed projects. This did not relate to Azure project, but to a web application deployed onto a remote windows web server
I took these steps to resolve it:
Get the files names of the DLLs from references
Find these DLLS in the packages subfolder of your vs project.
Make sure you have the right version for your .net framework version
Copy the DLLs to a folder, we called it "deployments"
Remove the Nuget packages
Reference the DLLs directly with copylocal=true
You may or may not need to add the DLLs to the bin folder in your deployment package. The packages we needed are shown below

Method not found: 'System.Threading.Tasks.Task`1<!!0>

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 :-)

Mono NotImplementedException in X509CertificateCollection

I have a console application written in C# that I'm trying to run on Linux with mono 4.2.1 (also tried 4.4.1), but I'm getting a NotImplementedException when calling X509CertificateCollection.Add(). This is the offending code:
var cert = new X509Certificate2(certFilename, "");
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(cert);
I have mono-complete installed, and tried both a standard build and Xamarin build, with the same results. I also checked I have ca-certificates-mono installed based on this in the docs. I did some digging and found this in the mono code, which suggests this functionality has been implemented, but clearly is not working for me. Am I missing part of the build/deployment process here?
If you are getting a NotImplementedException then something is missing down the chain of your assembly dependencies. What I would do is check if your solution has the required dependencies for the X509Certificate installed in your GAC/BIN on debug. I hope this helps!

Xamarin needs reference to Windows.Foundation.FoundationContract

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...)

Universal Windows Platform and SignalR (Could not load file or assembly 'System.Net, Version=2.0.5.0)

when using the new Universal Windows Platform and a SignalR client (from Nuget) a strange thing happens when you set the network credential.
The following code works flawlessly:
NetworkCredential Connection_Credentials = new NetworkCredential( "Name", "Password" );
Microsoft.AspNet.SignalR.Client.Connection Connection = new Microsoft.AspNet.SignalR.Client.Connection( "http://localhost/Bla" );
However when you assign the NetworkCredential in the following way the runtime crashes even before executing the code:
NetworkCredential Connection_Credentials = new NetworkCredential( "Name", "Password" );
Microsoft.AspNet.SignalR.Client.Connection Connection = new Microsoft.AspNet.SignalR.Client.Connection( "http://localhost/Bla" );
Connection.Credentials = Connection_Credentials;
The error is: "System.IO.FileNotFoundException: Could not load file or assembly 'System.Net, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The system cannot find the file specified.\r\n at UAP2.MainPage.Page_Loaded(Object sender, RoutedEventArgs e)"
Is this an error I can fix myself (I tried doing the same with another project) or is there a problem in the SignalR package (or one of it's dependencies?).
Why would it want to reference 2.0.5.0 of System.Net and not a 4-* version?
it's a bit crude, but I have found a fix/workaround. Basically you have to make sure you use the assembly from the WinRT project in stead of the two that NuGet attaches. See http://dotnetbyexample.blogspot.nl/2015/05/getting-signalr-clients-to-work-on.html for details
I don't have the answer to the problem, but I reported an issue about it on GitHub. Hopefully someone will finally look into it.
https://github.com/SignalR/SignalR/issues/3483
Edit:
Did some testing with the source code of SignalR.Client and it crashes in its DefaultHttpHandler(IConnection connection) constructor. Most likely when in System.Net.Http.HttpClientHandler constructor (for which I don't have source code).
A workaround for this should be to compile the SignalR client DLL without support for SL5 - targeting .NET 4.5, Windows 8, Windows Phone Silverlight 8, and Windows Phone 8.1, also known as PCL Profile 259.

Categories

Resources