I still work with some legacy solutions in AngularJs. I want to look in parent scope for a object which I know the name of, but it is some levels up by calling multiple $parent calls to get to the correct parent scope.
Here is a small util method I wrote the other day to access a variable inside parent scopes by known name.
Note : Select an element via F12 Developer tools and access its AngularJs scope. In the browser this is done by running in the console :
angular.element($0).scope()
Here is the helper method I wrote :
This article will look at primary constructors in C# 12. It is part of .NET 8 and C# 12.
Primary constructors can be tested on the following website offering a C# compiler which supports .NET 8.
Since .NET 8 is released medio 14th of November, 2023, which is like in two weeks after writing this article, it
will be generally available very soon. You can already also use .NET 8 in preview versions of VS 2022.
Let's look at usage of primary constructor.
The following program defined one primary constructor, note that the constructor is before the class declaration starts inside
the block.
Program.cs
using System;
publicclassPerson(string firstName, string lastName) {
publicoverridestringToString()
{
lastName += " (Primary constructor parameters might be mutated) ";
return$"{lastName}, {firstName}";
}
}
publicclassProgram {
publicstaticvoidMain(){
var p = new Person("Tom", "Cruise");
Console.WriteLine(p.ToString());
}
}
The output of running the small program above gives this output :
Program.cs
Cruise (Primary constructor parameters might be mutated) , Tom
If a class has added a primary constructor, this constructor must be called. If you add another constructor, you must call the primary constructor. For example like in this example,
using a default constructor (empty constructor), calling the primary constructor:
Another example of primary constructors are shown below. We use a record called Distance and pass in two dx and dy components of a vector and calculate its mathematical
distance and direction. We convert to degrees here using PI * radians = 180 expression known from trigonometry. If dy < 0, we are in quadrant 3 or 4 and we add 180 degrees.
using System;
var vector = new Distance(-2, -3);
Console.WriteLine($"The vector {vector} has a magnitude of {vector.Magnitude} with direction {vector.Direction}");
publicrecordDistance(double dx, double dy) {
publicdouble Magnitude { get; } = Math.Round(Math.Sqrt(dx*dx + dy*dy), 2);
publicdouble Direction { get; } = dy < 0 ? 180 + Math.Round(Math.Atan(dy / dx) * 180 / Math.PI, 2) :
Math.Round(Math.Atan(dy / dx) * 180 / Math.PI, 2);
}
This article presents code how to extract Health information from arbitrary text using Azure Health Information extraction in Azure Cognitive Services. This technology uses NLP - natural language processing combined with AI techniques.
A Github repo exists with the code for a running .NET MAUI Blazor demo in .NET 7 here:
A screenshot from the demo shows how it works below.
The demo uses Azure AI Healthcare information extraction to extract entities of the text, such as a person's age, gender, employment and medical history and condition such as diagnosises, procedures and so on.
The returned data in the demo is shown at the bottom of the demo, the raw data shows it is in the format as a json and in a FHIR format. Since we want FHIR format, we must use the REST api to get this information.
Azure AI Healthcare information also extracts relations, which is connecting the entities together for semantic analysis of the text. Also, links exist for each entity for further reading.
These are external systems such as Snomed CT and Snomed codes for each entity.
Let's look at the source code for the demo next.
We define a named http client in the MauiProgram.cs file which starts the application. We could move the code into a middleware extension method, but the code is kept simple in the demo.
MauiProgram.cs
var azureEndpoint = Environment.GetEnvironmentVariable("AZURE_COGNITIVE_SERVICES_LANGUAGE_SERVICE_ENDPOINT");
var azureKey = Environment.GetEnvironmentVariable("AZURE_COGNITIVE_SERVICES_LANGUAGE_SERVICE_KEY");
if (string.IsNullOrWhiteSpace(azureEndpoint))
{
thrownew ArgumentNullException(nameof(azureEndpoint), "Missing system environment variable: AZURE_COGNITIVE_SERVICES_LANGUAGE_SERVICE_ENDPOINT");
}
if (string.IsNullOrWhiteSpace(azureKey))
{
thrownew ArgumentNullException(nameof(azureKey), "Missing system environment variable: AZURE_COGNITIVE_SERVICES_LANGUAGE_SERVICE_KEY");
}
var azureEndpointHost = new Uri(azureEndpoint);
builder.Services.AddHttpClient("Az", httpClient =>
{
string baseUrl = azureEndpointHost.GetLeftPart(UriPartial.Authority); //https://stackoverflow.com/a/18708268/741368
httpClient.BaseAddress = new Uri(baseUrl);
//httpClient..Add("Content-type", "application/json");//httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureKey);
});
The content-type header will be specified instead inside the HttpRequestMessage shown further below and not in this named client. As we see, we must add both the endpoint base url and also the key in the Ocp-Apim-Subscription-key http header.
Let's next look at how to create a POST request to the language resource endpoint that offers the health text analysis below.
HealthAnalyticsTextClientService.cs
using HealthTextAnalytics.Models;
using System.Diagnostics;
using System.Text;
using System.Text.Json.Nodes;
namespaceHealthTextAnalytics.Util
{
publicclassHealthAnalyticsTextClientService : IHealthAnalyticsTextClientService
{
privatereadonly IHttpClientFactory _httpClientFactory;
privateconstint awaitTimeInMs = 500;
privateconstint maxTimerWait = 10000;
publicHealthAnalyticsTextClientService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
publicasync Task<HealthTextAnalyticsResponse> GetHealthTextAnalytics(string inputText)
{
var client = _httpClientFactory.CreateClient("Az");
string requestBodyRaw = HealthAnalyticsTextHelper.CreateRequest(inputText);
//https://learn.microsoft.com/en-us/azure/ai-services/language-service/text-analytics-for-health/how-to/call-api?tabs=nervar stopWatch = Stopwatch.StartNew();
HttpRequestMessage request = CreateTextAnalyticsRequest(requestBodyRaw);
var response = await client.SendAsync(request);
var result = new HealthTextAnalyticsResponse();
var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(awaitTimeInMs));
int timeAwaited = 0;
while (await timer.WaitForNextTickAsync())
{
if (response.IsSuccessStatusCode)
{
result.IsSearchPerformed = true;
var operationLocation = response.Headers.First(h => h.Key?.ToLower() == Constants.Constants.HttpHeaderOperationResultAvailable).Value.FirstOrDefault();
var resultFromHealthAnalysis = await client.GetAsync(operationLocation);
JsonNode resultFromService = await resultFromHealthAnalysis.GetJsonFromHttpResponse();
if (resultFromService.GetValue<string>("status") == "succeeded")
{
result.AnalysisResultRawJson = await resultFromHealthAnalysis.Content.ReadAsStringAsync();
result.ExecutionTimeInMilliseconds = stopWatch.ElapsedMilliseconds;
result.Entities.AddRange(HealthAnalyticsTextHelper.GetEntities(result.AnalysisResultRawJson));
result.CategorizedInputText = HealthAnalyticsTextHelper.GetCategorizedInputText(inputText, result.AnalysisResultRawJson);
break;
}
}
timeAwaited += 500;
if (timeAwaited >= maxTimerWait)
{
result.CategorizedInputText = $"ERR: Timeout. Operation to analyze input text using Azure HealthAnalytics language service timed out after waiting for {timeAwaited} ms.";
break;
}
}
return result;
}
privatestatic HttpRequestMessage CreateTextAnalyticsRequest(string requestBodyRaw)
{
var request = new HttpRequestMessage(HttpMethod.Post, Constants.Constants.AnalyzeTextEndpoint);
request.Content = new StringContent(requestBodyRaw, Encoding.UTF8, "application/json");//CONTENT-TYPE headerreturn request;
}
}
}
The code is using some helper methods to be shown next. As the code above shows, we must poll the Azure service until we get a reply from the service. We poll every 0.5 second up to a maxium of 10 seconds from the service. Typical requests takes about 3-4 seconds to process. Longer input text / 'documents' would need more processing time than 10 seconds, but for this demo, it works great.
HealthAnalyticsTextHelper.CreateRequest method
publicstaticstringCreateRequest(string inputText)
{
//note - the id 1 here in the request is a 'local id' that must be unique per request. only one text is supported in the //request genreated, however the service allows multiple documents and id's if necessary. in this demo, we only will send in one text at a timevar request = new
{
analysisInput = new
{
documents = new[]
{
new { text = inputText, id = "1", language = "en" }
}
},
tasks = new[]
{
new { id = "analyze 1", kind = "Healthcare", parameters = new { fhirVersion = "4.0.1" } }
}
};
return JsonSerializer.Serialize(request, new JsonSerializerOptions { WriteIndented = true });
}
Creating the body of POST we use a template via a new anonymized object shown above which is what the REST service excepts. We could have multiple documents here, that is input texts, in this demo only one text / document is sent in. Note the use of id='1' and 'analyze 1' here.
We have some helper methods in System.Text.Json here to extract the JSON data sent in the response.
I have added the Domain classes from the service using the https://json2csharp.com/ website on the intial responses I got from the REST service using Postman. The REST Api might change in the future, that is, the JSON returned.
In that case, you might want to adjust the domain classes here if the deserialization fails. It seems relatively stable though, I have tested the code for some weeks now.
Finally, the categorized colored text code here had to remove newlines to get a correct indexing of the different entities found in the text. This code shows how to get rid of newlines of the inputted text.