How to specify the API version? - c#

According to the Azure DevOps Services REST API Reference, the request URI has the following format:
https://{instance}[/{team-project}]/_apis[/{area}]/{resource}?api-version={version}
Regarding the api-version:
Every API request should include an api-version to avoid having your app or service break as APIs evolve.
I started using the .NET client libraries for Azure DevOps Services (and TFS) to manage dashboards programmatically.
I am able to connect to Azure DevOps using a Personal Access Token:
var credential = new VssBasicCredential(string.Empty, "PersonalAccessToken");
using (VssConnection connection = new VssConnection(new Uri("...."), credential))
using (var client = connection.GetClient<DashboardHttpClient>())
{
// ...
}
How can I specify the API version? Does it still make sense to do it, when using the .NET client libraries?

The API version is decided by the client libraries. You can confirm this by disassembling them (e.g. using ILSpy).
For example, in the current stable release of Microsoft.TeamFoundationServer.Client, DashboardHttpClientBase has a CreateDashboardAsnc method that makes the following call:
this.SendAsync<Dashboard>(..., new ApiResourceVersion("4.1-preview.2"), ...);

Related

.NET PowerBIClient NuGet Package adds wrong relative URI

I try to encapsule our PowerBI Server REST API via the PowerBI Client NuGet Package from Microsoft.
I ran into the problem that the URI gets a wrong relative path added.
The REST API of our Reporting Server (on-premise) has a base URI like: https://niceReportingURL.com/reports/api/v2.0 but the NuGet package adds another "/v1.0/myorg" to the URI, which is not necessary.
So resulting of that, the request URI looks like this: https://niceReportingURL.com/reports/api/v2.0/v1.0/myorg
I saw in the source code of the class "ReportsOperations" that this weird relative URI gets added hardcoded!
string uriString = new Uri(new Uri(absoluteUri + (absoluteUri.EndsWith("/") ? "" : "/")), "v1.0/myorg/reports").ToString();
I omitted the "/Reports" in my example URIs because it looks like a general problem.
Is there an option or workaround that the NuGet Package doesn't add this relative URI?
The request looks like this:
var c = new BasicAuthenticationCredentials
{
UserName = "reportingUser",
Password = "secretReportingPW"
};
var client = new PowerBIClient(new Uri("https://niceReportingURL.com/reports/api/v2.0"), c);
var result = await client.Reports.GetReportsAsync().ConfigureAwait(false); // Here comes the fail
The PowerBI Client package encapsulates access to the PowerBI REST API.
This API is distinct from the Reporting Services REST API, which appears to have no ready-made NuGet package that encapsulates it, but does have an OpenAPI specification that makes it easy to use.
Both APIs have endpoints for retrieving reports, but they're different kinds of report. Confusingly, Microsoft has chosen to rebrand Reporting Services as "paginated reports" in the PowerBI ecosystem, so at least some Reporting Services reports can be retrieved using the PowerBI REST API. For reports hosted by an on-premise Reporting Services instance, though, you want the Reporting Services API and can't use the PowerBI REST API.

Service identification in a cloud docker system

I got a system in Azure cloud which has a docker and each pod in the docker is a different service implemented with c# .Net Core. One of these services is a gRPC service which is a file service and every other service who want to access a file are using an SDK which access that service directly and it allows to access the requested file. The SDK is a nuget which every service adds to its references.
A flow example: Service A => invoke a method from SDK => Calls file service which access a file => return a response to the SDK => return a response to service A.
My desired behavior: I want to identify in the SDK the service itself which invokes the SDK's method. I can't use a simple input like just passing a string parameter because it's important to know the true service and I can't risk someone sending wrong information.
this is a pseudo code of what I need:
//this is an SDK method
public string GetSomeValueFromFile(string fileName)
{
string invokingService = GetCurrentService();
...
...
}
And the question is how to implement this GetCurrentService() method since I have no idea where to start

Azure SignalR .NET Framework C# Client cannot authenticate

I am trying to connect a C# .NET 4.7 application as a client to my Azure SignalR service. I am using the ASP.NET version of the SignalR client library, NOT the ASP.NET CORE version.
I have code set up like this:
var serviceUtils = new ServiceUtils(ConfigurationManager.ConnectionStrings["Azure:SignalR:ConnectionString"].ConnectionString);
var url = $"{utils.Endpoint}/client/";
_connection = new HubConnection(url, $"?hub={hubName}")
{
ConnectionToken = serviceUtils.GenerateAccessToken(url, userId)
};
IHubProxy proxy = _connection.CreateHubProxy(hubName);
await _connection.Start().ConfigureAwait(false);
However, this does not work. I get back a 'StatusCode: 401, ReasonPhrase: 'Unauthorized'' when _connection.Start() throws an exception.
The "ServiceUtils" token generation is pulled from the example here:
https://github.com/vavjeeva/AzureSignalRConsoleApp/blob/master/AzureSignalRConsoleApp.Utils/ServiceUtils.cs
Interestingly, I have implemented the same logic in a basic C# .Net Core console app, using the .Net Core version of the library, and it actually does work, using the same connection string. The difference is I am using the HubConnectionBuilder, which does not exist in the asp.net version of the library. My assumption is that the two are authenticating in different ways.
How do I get this sort of functionality working in this version of the library? I want my service application, as a client, to be able to invoke hubu methods via the Azure SignalR Service.

Create an azure eventhub consumer group via net core SDK?

The older WindowsAzure.ServiceBus library has a call CreateConsumerGroupIfNotExists to create a consumer group on an azure eventhub. However, this is Net Framework 4.6 only. I'm trying to figure out how to create a consumer in netstandard2.0 from C# but I don't see an equivalent. Is there a way to do this?
Generally, you can directly use the REST API Create consumer group to create EventHubs Consumer Group in any programming language.
In your scenario using C#, there is an API of Azure SDK for .NET ConsumerGroupsOperationsExtensions.CreateOrUpdate(IConsumerGroupsOperations, String, String, String, String, ConsumerGroup) Method that you can use. And according to the information from NuGet Package Manager in Visual Studio 2017, as the figure below, the related package Microsoft.Azure.Management.EventHub supports Netstandard.Library (>=1.6.1), so it should also support your current environment netstandard2.0.
Peter Pan is correct in pointing out the C# API call for this. Here are some more details:
Create a service principal in Azure (or use an existing one)
Grant this service principal "Owner" access to the Event Hubs Instance (under IAM => "Role Assignments" in the portal)
The variables in the code below come from the service client, the event hub and the subscription:
private static async Task EnsureConsumerGroup(string consumerGroupName)
{
var context = new AuthenticationContext($"https://login.windows.net/{MY_TENANT_ID}");
var token = await context.AcquireTokenAsync(
"https://management.core.windows.net/",
new ClientCredential(MY_CLIENT_ID, MY_CLIENT_SECRET)
);
var serviceClientCredentials = new TokenCredentials(token.AccessToken);
var eventHubManagementClient = new EventHubManagementClient(serviceClientCredentials)
{
SubscriptionId = MY_SUBSCRIPTION_ID
};
var consumerGroupResponse = await
eventHubManagementClient.ConsumerGroups.CreateOrUpdateWithHttpMessagesAsync(
MY_RESOURCE_GROUP_NAME,
MY_NAMESPACE_NAME,
MY_EVENT_HUB_NAME,
consumerGroupName,
new ConsumerGroup() // I don't know what this parameter is supposed to do.
);
}
Presumably you would handle the error condition in consumerGroupResponse.Response as well.
See also:
https://github.com/Azure-Samples/event-hubs-dotnet-management

Ignore SSL self signed certificate errors Restful httpclient

I have done tons of searching and reading on this, there are so many different ways to achieve this. However, things have changed a bit since a lot of the posts. Ultimately, I am using a UWP (10586 minimum target) app. I have wrapped my httpclient code into a .net standard library which my UWP app consumes. However, because of the 10586 SDK version, my .net standard library must be 1.4 or lower.
I need to post json to a web service in a RESTful way. Tjis web service uses SSL but has a self signed certificate. So, I get certificate errors. I simply want to ignore them so I can make my calls. Using 3rd party web service test utility (Postman), I have confirmed the calls will work if SSL errors are simply ignored.
Based on my UWP and .net standard setup, I cannot use the X509 namespace to ignore SSL errors. This is one method but X509 is not available.
So, this looked most promising: https://blog.roushtech.net/2016/12/20/ignoring-ssl-certificate-errors-net-core-httpclient/
It has no compiler errors, but at runtime I get a "platform not supported" exception.
Is there any way to work around all of this given my configurations?
EDIT: The exact snippet I am using that seems to be the supported method in the future but gives platform error on UWP is the same in the link I copied above. For reference, this is what I am doing:
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message,
cert, chain, errors) => { return true; };
using (var client = new HttpClient(httpClientHandler))
{
// Make request here.
}
}
Also, yes my code does work with non ssl (http) calls. It had been working fine for some time until I needed to access a new/different web service which is configured as ssl.
Thanks!!!

Categories