Visual Studio Team Services API Example Throwing System.Net.Http Error - c#

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

Related

Running remote PowerShell script using .Net 5.0

The method call in C# is like this -
public void GetKey()
{
WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
var ss = new NetworkCredential("xxx.yyyy\\Administrator", "PassFail2Hehe");
connectioninfo.ComputerName = "<some IP Address>";
connectioninfo.Credential = new PSCredential(ss.UserName, ss.SecurePassword);
//Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo);
//runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
var re = ps.AddScript("Get-Service");
var results = re.Invoke();
}
}
I am using the NuGet package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0', as it is showing as the recommended package in Visual Studio 2019 for resolving the types of "Runspace", "PowerShell" etc.
However, I am getting the exception when the instance of "Runspace" or "PowerShell" is created. The exception is like this - "Common Language Runtime detected an invalid program."
I found this post and realized that I was getting the warning indeed for the NuGet package -
"Package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0' was restored using '.NETFramework,Version=v4.6.1,
.NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2,
.NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project."
As per suggested in the post, I installed Powershell Core 7.1.3, but the warning and exceptions were not resolved. Then I switched to ".Net Standard 2.0", since it the project was a class library, but nothing changed. The same warning message and exception.
How can I make remote PowerShell call using ".Net Core 5.0" (or ".Net Standard 2.0") ?
If you want to target .Net 5, the correct nuget package to use is Microsoft.PowerShell.SDK

Is it possible to install a local version of a package at runtime and use said local package?

As part of trying to test a NuGet package with a Console application, is it possible to have the console application get the latest version of said NuGet package programmatically, and then use said package to call various methods and what not? This is the flow that I'm trying to achieve...
A NuGet package is created locally (already done as part of a build process)
A console application installs this package
The same console application calls a few methods that are inside this package (if this uses reflection insdie the console app to achieve this it isn't an issue)
How can this be achieved? I've tried the following code using the NuGet.Core & NuGet.Protocol NuGet packages...
// exception thrown for trying to resolving newtonsoft
IPackageRepository packageRepository = new NuGet.LocalPackageRepository(directoryPath);
PackageManager pm = new PackageManager(packageRepository, GetExecutingAssemblyDirectory());
pm.InstallPackage("package_id", SemanticVersion.Parse("package_version"));
NuGet.Common.ILogger logger = new Logger();
IEnumerable<LocalPackageInfo> packageInfos = LocalFolderUtility.GetPackagesV2(directoryPath, logger);
foreach (LocalPackageInfo lpi in packageInfos)
{
// no obvious way to actually install the package
}
// never more than zero packages
var localRepo = new LocalPackageRepository(directoryPath);
var packages = localRepo.GetPackages();
if (packages?.Count() > 0)
{
var packageManager = new PackageManager(localRepo, GetExecutingAssemblyDirectory());
packageManager.InstallPackage(packages.ElementAt(0).Id);
}
I haven't been able to get any of those pieces of code to work. Is this actually possible? Would I have to look at using 2 Console apps (one to install into the other, which then does the calling of methods), and if so how would this be done?

ML.NET: strange runtime error on some machines

I wrote a simple UWP app using the ML.NET framework, and it worked on one of my machines without installing any Nuget packages, without any additional setup etc.
However, on my other machine, after running the application, I get this error:
System.Runtime.InteropServices.COMException: 'Unspecified error
No suitable kernel definition found for op Sub (node Minus675)'
The error happens in this segment of code:
public static async Task<modelModel> CreateFromStreamAsync(IRandomAccessStreamReference stream)
{
modelModel learningModel = new modelModel();
learningModel.model = await LearningModel.LoadFromStreamAsync(stream);
learningModel.session = new LearningModelSession(learningModel.model); // it breaks here
learningModel.binding = new LearningModelBinding(learningModel.session);
return learningModel;
}
In case anyone should ask - yes I have added my .onnx model in the Assets folder. My configuration is: VS 2017, Windows 10 version 1809, build 17763.194, and I have Windows 10 SDK version 10.0.17763.132. I have tried installing the Visual Studio Tools for AI and ML.NET Templates VS extensions, but it didn't help.

SQLite with MVC Core

I'm trying to create a database in memory and run a query with .NET Core 2.1 framework. To do this I have installed a package called Microsoft.Data.Sqlite.Core and then tried to do the following:
var connection = new SqliteConnection("Data Source=:memory:");
connection.Execute("Some Create Table Query");
And my code will crash with the following error:
You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().
I've done a lot of digging to find a solution and one of them suggested calling this:
SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());
This produces me a new error:
'Unable to load DLL 'e_sqlite3' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)'
I am really lost at this point how to accomplish this. All I want to do is create an in-memory database so I can run some queries for purposes of unit testing.
I'm not sure if this is relevant but I am not using EF6, I am using Dapper and also I am using SQL Server in my actual project. I wanted to plug in Sqlite in unit tests so I can also test my queries.
I have a feeling I am using wrong packages, but looking around there are so many and I can't find any clear documentation on how to use Sqlite with MVC Core projects.
Try adding the SQLitePCLRaw.bundle_green package to your project.
dotnet add package SQLitePCLRaw.bundle_green
At that point, the following program (inspired by this) works:
using Microsoft.Data.Sqlite;
class Program
{
static void Main()
{
var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
var createCommand = connection.CreateCommand();
createCommand.CommandText =
#"
CREATE TABLE data (
value TEXT
)
";
createCommand.ExecuteNonQuery();
}
}
This is the test that I ran locally.
cd C:/temp
dotnet new console
dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.bundle_green
//
// paste the above program into Program.cs, then...
//
dotnet run
What is bundle_green? bundle_green is one of the Sqlite "bundle packages", which are expressly designed to ease cross-platform development. Here is a description from the official repository:
These packages automatically bring in the right dependencies for each platform. They also provide a single Init() call that is the same for all platforms... SQLitePCLRaw.bundle_green is a bundle that uses e_sqlite3 everywhere except iOS, where the system-provided SQLite is used.

API resource location is not registered

i am able to create project/delete/rename everything but when it come for getting group its says "API resource location ebbe6af8-0b91-4c13-8cf1-777c14858188 is not registered on http://khanamar3:8080/tfs/DefaultCollection/" please help.....
public PagedGraphGroups GetAllGroups()
{
VssConnection connection = Context.Connection;
GraphHttpClient graphClient = connection.GetClient<GraphHttpClient>();
//error coming in next line...
PagedGraphGroups groups = graphClient.GetGroupsAsync().Result;
foreach (var group in groups.GraphGroups)
{
LogGroup(group);
}
return groups;
}
There might be two problems with
API resource location {0} is not registered on {1}
1. With URL
I think it should be without default collection, so in your example
http://khanamar3:8080/tfs/
2. With TFS/API version (I had this problem myself)
2.1
First check the version of your TFS server in TFS Management
for example
C:\Program Files\Microsoft Team Foundation Server 2018\Tools\TfsMgmt.exe
Once you know your TFS Server version you can see which API Version it supports
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=vsts-rest-tfs-4.1
For example TFS 2018 UPDATE 1 supports API version 4.0
2.2
Then check what API version is called by DLLs you use. I coudn't find this information on nuget site
https://www.nuget.org/packages/Microsoft.TeamFoundationServer.Client/
UPDATE: You can check which dll version supports which TFS version here:
https://learn.microsoft.com/en-us/azure/devops/integrate/concepts/dotnet-client-libraries?view=azure-devops
but as described here
How to specify the API version?
you can check what API version is passed by the method using ILSpy
Method in your case would be:
GetGroupsAsync
And you can check this using https://marketplace.visualstudio.com/items?itemName=SharpDevelopTeam.ILSpy
In my case it looked like this
So API from nuget Versioned 16.153.0 uses calls with 5.1.1
So in my case TFS 2018 UPDATE 1 did not supported API version 5.1.1, so I will need to downgrade nuget or upgrade TFS Server Version (or both)
You could use IIdentityManagementService with ListApplicationGroups to get the list of application groups.
TeamFoundationIdentity[] ListApplicationGroups(
string scopeId,
ReadIdentityOptions readOptions
)
Sample code
var applicationGroups = identityManagementService.ListApplicationGroups(projectcollection.Uri.AbsoluteUri, ReadIdentityOptions.None);
Also take a look at this similar question: TFS 2013 get All TFS group including Windows group

Categories

Resources