APIM endpoint is not working through latest elastic client library - c#

I am using latest "Elastic.Clients.Elasticsearch" library in .NET console application to talk to my elastic latest version 8.X. However, in my scenario I will not be talking directly to elastic I have a middle layer APIM endpoint. This is working fine when I am using NEST package with EnableAPIVersioningHeader setting. But in case of new library it throws 404 "resource not found error". Please can you let me know what are the changes that needs to be done to get this working.
Note: I am removing NEST package dependency from code, as Elastic will not support it in the future.
Sample Code:
public static ElasticsearchClient NewSearchClusterClient
{
get
{
var connectionSettings = new ElasticsearchClientSettings(new Uri("<apimendpoint>"));
connectionSettings.MaximumRetries(5);
connectionSettings.DefaultIndex("test");
connectionSettings.IncludeServerStackTraceOnError(true);
connectionSettings.EnableTcpStats(true);
connectionSettings.DisableDirectStreaming(true);
NameValueCollection collection = new NameValueCollection
{
};
connectionSettings.GlobalHeaders(collection);
var client = new ElasticsearchClient(connectionSettings);
return client;
}
}
Call this --> var respone = NewSearchClusterClient.Search(q => q.Query(m => m.MatchAll()));

Related

Why is my gremlin.net gremlin client not working with azure cosmos graph db

I've set up a serverless azure cosmos graph db account and now I'm trying to connect to it using the following code:
.AddSingleton(s =>
{
var connectionPool = new ConnectionPoolSettings
{
MaxInProcessPerConnection = 32,
PoolSize = 4,
ReconnectionAttempts = 4,
ReconnectionBaseDelay = TimeSpan.FromSeconds(1)
};
var server = new GremlinServer("<project-name>.documents.azure.com", 443, true, "/dbs/<DatabaseName>/colls/<GraphName>", "<primary key>");
return new GremlinClient(server, connectionPoolSettings: connectionPool);
})
The GremlinClient throws an Exception with the message
The server returned status code '200' when status code '101' was expected.
I'm using Gremlin.Net 3.6.0 with NET 6
Any ideas?
If you were connecting well with earlier versions of Gremlin.Net you might want to revert. According to their website their supported version is 3.4.6. While later versions along 3.4.x might work, it might require more configuration (like, I think you might have to switch the serializer as I dont think CosmosDB supports the GraphBinary serializer) and you'd have to take care to not use certain features that newer versions of TinkerPop have that 3.4.6 did not.
The issue was resolved by changing the uri from
<project-name>.documents.azure.com
to
<project-name>.gremlin.cosmosdb.azure.com
https://learn.microsoft.com/en-us/azure/cosmos-db/graph/gremlin-api-faq#why-am-i-getting-the--websocketexception--the-server-returned-status-code--200--when-status-code--101--was-expected--error-

Is it possible to set a discovery URI for token acquisition in Microsoft.Identity.Web?

I have a .NET5 app that is utilizing Microsoft.Identity.Web for a secure API. When attempting to retrieve the access token:
var accessToken = await _tokenAcquisition.GetAccessTokenForAppAsync(scopesToAccessDownstreamApi);
The first thing that happens is it makes a request to the discovery endpoint:
https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=.......%2Fauthorize
I have a static authority specified in my config which I thought it should be using instead. For my Blazor app it works just fine. MS.Identity.Web first gets my key information at my authority:
https://myCustomAuthority/myTenantId/oauth2/v2.0/.well-known/openid-configuration
With the tokenAcquisition however, it always calls login.microsoft.com, fails, and then finally redirects to my endpoint.
Digging through both the MS.Identity.Web and MS.Identity.Client code they definitely had this in mind.
/// Allows developers to configure their own valid authorities. A json string similar to https://aka.ms/aad-instance-discovery should be provided.
See here: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/AbstractApplicationBuilder.cs#L51
public InstanceDiscoveryResponse CustomInstanceDiscoveryMetadata { get; set; }
public Uri CustomInstanceDiscoveryMetadataUri { get; set; }
And here:
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/ApplicationConfiguration.cs#L95
But I'm unable to find it on the API side. And when I look at TokenAquisition it's calling ConfidentialClientApplicationBuilder.CreateWithApplicationOptions
var builder = ConfidentialClientApplicationBuilder
.CreateWithApplicationOptions(_applicationOptions)
.WithHttpClientFactory(_httpClientFactory);
https://github.com/AzureAD/microsoft-identity-web/blob/b106d9a9250522d0bf9ed0e78e0e3dbd376d8170/src/Microsoft.Identity.Web/TokenAcquisition.cs#L583
Which then creates a new ConfidentialClientApplicationBuilder with an empty ApplicationConfiguration object so the CustomInstanceDiscovery is always null
var config = new ApplicationConfiguration();
var builder = new ConfidentialClientApplicationBuilder(config).WithOptions(options);
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/ConfidentialClientApplicationBuilder.cs#L42
All the hooks seem to be there so I feel like I'm missing some configuration but it also could be a feature / bug request.
This was an actual defect that the Microsoft.Identity.Web team has fixed. I asked the same question to the team:
https://github.com/AzureAD/microsoft-identity-web/discussions/1202
And they created an issue:
https://github.com/AzureAD/microsoft-identity-web/issues/1212
So this was fixed with build 1.13.

Nuget api issue

I need to automatically collect the information from the nuget packages of a series of projects. For this purpose I use the API that miscrosoft makes available.
Making the call:
https://api.nuget.org/v3/registration3/epplus/index.json
I get the most recent version: v.4.5.3.1 while on the nuget website it is: v. 5.1.2.
To make the call I use the following code:
static void GetNuGetIndex(Model.Package package)
{
string uri = "https://api.nuget.org/v3/registration3/" + package.Name.ToLower() + "/index.json";
string json = new WebClient().DownloadString(uri);
var packageIndex = JsonConvert.DeserializeObject<JSONModel.NuGetPackageIndex>(json);
int packageIndexItemCounter = 0;
if (packageIndex.Items.Count > 0)
foreach (var packageItem in packageIndex.Items)
{
packageIndexItemCounter++;
List<JSONModel.NuGetPackageItem> items = packageItem.Items;
if (packageItem.Items == null)
{
string lookupjson = new WebClient().DownloadString(packageItem.LookupUrl);
items = JsonConvert.DeserializeObject<JSONModel.NuGetPackageItems>(lookupjson).Items;
}
GetNuGetItems(package, items, package.Name, package.Version, (packageIndexItemCounter.Equals(packageIndex.Items.Count) ? packageItem.Upper : "" ));
}
}
Can anyone give me an explanation of why I have this problem and how can it be solved?
Thanks
I believe this is because this endpoint has been discontinued.
Consulting to the service index api, available at: https://api.nuget.org/v3/index.json (DOC) you can see that the address you are using is not returned.
When consulting the endpoint https://api.nuget.org/v3/registration5-semver1/epplus/index.json provided by the index api, the "upper" field will now return the most current version
I looked here, which suggests you need a different query to return packages:
https://api.nuget.org/v3/registration5-semver1/epplus/index.json
As Kelvin mentioned, that registration hive has been discontinued. I would recommend using the NuGet client SDK to interact with the NuGet API: https://learn.microsoft.com/en-us/nuget/reference/nuget-client-sdk#list-package-versions
If you still would like to use the NuGet APIs directly, I recommend reading through the following resources:
https://learn.microsoft.com/en-us/nuget/api/overview
https://learn.microsoft.com/en-us/nuget/api/service-index
https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource
TLDR: You have to "discover" the latest location of the registration endpoint using the V3 Service Index API at https://api.nuget.org/v3/index.json.

Get AWS caller Identity with C# SDK

When I execute this with the aws cli, i.ex. inside a fargate task, I can see the UserId that my application is going to use
aws sts get-caller-identity
with this output on the console
{
"Arn": "arn:aws:sts::643518765421:assumed-role/url_process_role/6ae81f92-66f3-30de-1eaa-3a7d1902bad9",
"UserId": "ARDYOAZLVOAQXTT5ZXTV4:4ea81f97-66f3-40de-beaa-3a7d1902bad9",
"Account": "692438514791"
}
I would like to get the same information but using the C# SDK. I tried with the methods exposed in this doc but I can see some account related details but not the UserId assigned.
So far I've tried with this but I cannot see any profile when running in a Fargate task.
var awsChain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();
System.Console.WriteLine($"Found {awsChain.ListProfiles().Count} AWS profiles.");
My final goal is to get it and add to some task processed with Fargate to save a correlation Id in the database when something fails and easily find the Fargate log stream.
IAmazonSecurityTokenService will provide the same information when executed with .netcore. Notice that the above example will only work inside the AWS domain as the endpoint is not publicly available if testing from a development machine.
var getSessionTokenRequest = new GetSessionTokenRequest
{
DurationSeconds = 7200
};
var stsClient = hostContext.Configuration.GetAWSOptions().CreateServiceClient<IAmazonSecurityTokenService>();
var iden = stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest { }).Result;
System.Console.WriteLine($"A={iden.Account} ARN={iden.Arn} U={iden.UserId}");

TF400813: Resource not available for anonymous access. Client authentication required

I am working on the CodedUI Test Automation project. i am developing a framework in which i am trying to access Test Cases in VSTS through RestAPI. I have worked on an MVC application previously in which i did the same thing to pull data from VSTS using RestAPI.
Now the problem is i am not able to access the VSTS. Everytime i am trying to access the VSTS, i got the exception TF400813: Resource not available for anonymous access. Client authentication required.
I am using the same PAT token. I have all the required access on my team project. I am able to access all work items in my project from browser. I have tried all the option mentioned in below thread but still its not working.
Client authentication error when starting Visual Studio 2015.3Any leads will be appreciated.Below is my code to get data from VSTS:
public static List<WorkItem> GetWorkItemsWithSpecificFields(IEnumerable<int> ids)
{
var collectionUri = "https://<name>.visualstudio.com";
var fields = new string[] {
"System.Id",
"System.Title",
"System.WorkItemType",
"Microsoft.VSTS.Scheduling.RemainingWork"
};
using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(new Uri(collectionUri), new VssBasicCredential("", System.Configuration.ConfigurationManager.AppSettings["PATToken"])))
{
// Exception is coming on below line
List<WorkItem> results = workItemTrackingHttpClient.GetWorkItemsAsync(ids, fields).Result;
return results;
}
}

Categories