public async Task <AnalysisResponse> ProcessAsync(string input, Message messageOriginator, CancellationToken cancellationToken) { var request = new AnalysisRequest { Text = input }; var analysisResponse = await _artificialIntelligenceExtension.AnalyzeAsync(request, cancellationToken); var bestIntention = analysisResponse .Intentions .OrderByDescending(i => i.Score) .FirstOrDefault(); var bestIntentionAnswer = bestIntention.Answer.Value.ToString(); if (HasLowConfidence(bestIntention)) { await SendCommandToMPAAsync(DontKnowCommand, messageOriginator, cancellationToken); return(analysisResponse); } //Send to MPA await _sender.SendMessageAsync(bestIntentionAnswer, messageOriginator.From, cancellationToken); await Task.Delay(_settings.MPASettings.WaitBetweenSends); await SendCommandToMPAAsync(InitialFlowCommand, messageOriginator, cancellationToken); return(analysisResponse); }
/// <summary> /// Initiates an asynchronous operation for running the Smart Detector analysis on the specified resources. /// </summary> /// <param name="analysisRequest">The analysis request data.</param> /// <param name="tracer"> /// A tracer used for emitting telemetry from the Smart Detector's execution. This telemetry will be used for troubleshooting and /// monitoring the Smart Detector's executions. /// </param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for a task to complete.</param> /// <returns> /// A <see cref="Task"/> that represents the asynchronous operation, returning the Alerts detected for the target resources. /// </returns> public async Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { tracer.TraceInformation("Analyzing the specified resources..."); // Get the metrics client IMetricClient metricsClient = await analysisRequest.AnalysisServicesFactory.CreateMetricClientAsync(analysisRequest.TargetResources.First(), cancellationToken); // Get the resource metrics. In the example below, the requested metric values are the total number of messages // in the storage queue over the last day, in hourly interval var parameters = new QueryParameters() { StartTime = DateTime.UtcNow.Date.AddDays(-1), EndTime = DateTime.UtcNow.Date, Aggregations = new List <Aggregation> { Aggregation.Total }, MetricName = "QueueMessageCount", Interval = TimeSpan.FromMinutes(60) }; IEnumerable <MetricQueryResult> metrics = (await metricsClient.GetResourceMetricsAsync(ServiceType.AzureStorageQueue, parameters, default(CancellationToken))); // Process the resource metric values and create alerts List <Alert> alerts = new List <Alert>(); if (metrics.Count() > 0) { alerts.Add(new $alertName$("Title", analysisRequest.RequestParameters.First())); } tracer.TraceInformation($"Created {alerts.Count()} alerts"); return(alerts); }
public async Task Analyze_SingleLayerOnly_FluidC() { var request = new AnalysisRequest() { CreateDate = new DateTime(2020, 12, 01), DataSet = DataSetHelper.LouvainTest, SelectedLayer = 0, Approach = AnalysisApproach.SingleLayerOnly, AnalysisAlgorithm = AnalysisAlgorithm.FluidC, AnalysisAlgorithmParameters = new Dictionary <string, string>() { { "k", "2" }, { "maxIterations", "100" }, }, FlatteningAlgorithm = FlatteningAlgorithm.BasicFlattening, FlatteningAlgorithmParameters = new Dictionary <string, string>(), }; using (var ctx = InitCtx(nameof(Analyze_SingleLayerOnly_FluidC))) { var service = InitService(ctx); var analysis = await service.Analyze(1, 1, request); Assert.NotNull(analysis); Assert.NotNull(analysis.Result); Assert.NotNull(analysis.Request); } }
private async Task TestLoadSmartDetectorFromDll(string smartDetectorId, string expectedTitle) { ISmartDetectorLoader loader = new SmartDetectorLoader(this.tempFolder, this.tracerMock.Object); Dictionary <string, byte[]> packageContent = this.assemblies[smartDetectorId]; packageContent["manifest.json"] = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(this.manifests[smartDetectorId])); SmartDetectorPackage package = new SmartDetectorPackage(packageContent); ISmartDetector detector = loader.LoadSmartDetector(package); Assert.IsNotNull(detector, "Smart Detector is NULL"); var resource = new ResourceIdentifier(ResourceType.VirtualMachine, "someSubscription", "someGroup", "someVM"); var analysisRequest = new AnalysisRequest( new AnalysisRequestParameters( DateTime.UtcNow, new List <ResourceIdentifier> { resource }, TimeSpan.FromDays(1), null, null), new Mock <IAnalysisServicesFactory>().Object, new Mock <IStateRepository>().Object); List <Alert> alerts = await detector.AnalyzeResourcesAsync(analysisRequest, this.tracerMock.Object, default(CancellationToken)); Assert.AreEqual(1, alerts.Count, "Incorrect number of alerts returned"); Assert.AreEqual(expectedTitle, alerts.Single().Title, "Alert title is wrong"); Assert.AreEqual(resource, alerts.Single().ResourceIdentifier, "Alert resource identifier is wrong"); }
/// <summary> /// Initiates an asynchronous operation for running the Smart Detector analysis on the specified resources. /// </summary> /// <param name="analysisRequest">The analysis request data.</param> /// <param name="tracer"> /// A tracer used for emitting telemetry from the Smart Detector's execution. This telemetry will be used for troubleshooting and /// monitoring the Smart Detector's executions. /// </param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for a task to complete.</param> /// <returns> /// A <see cref="Task"/> that represents the asynchronous operation, returning the Alerts detected for the target resources. /// </returns> public async Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { tracer.TraceInformation("Analyzing the specified resources..."); $if$("$dataType$" == "Log Analytics") // Get the Log Analytics client ITelemetryDataClient dataClient = await analysisRequest.AnalysisServicesFactory.CreateLogAnalyticsTelemetryDataClientAsync(new List <ResourceIdentifier>() { analysisRequest.TargetResources.First() }, cancellationToken); $else$ // Get the Application Insights client ITelemetryDataClient dataClient = await analysisRequest.AnalysisServicesFactory.CreateApplicationInsightsTelemetryDataClientAsync(new List <ResourceIdentifier>() { analysisRequest.TargetResources.First() }, cancellationToken); $endif$ // Run the query IList <DataTable> dataTables = await dataClient.RunQueryAsync(@"$tableName$ | count", cancellationToken); // Process the query results and create alerts List <Alert> alerts = new List <Alert>(); if (dataTables[0].Rows.Count > 0) { alerts.Add(new $alertName$("Title", analysisRequest.TargetResources.First(), Convert.ToInt32(dataTables[0].Rows[0]["Count"]))); } tracer.TraceInformation($"Created {alerts.Count()} alerts"); return(alerts); }
public Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { List <Alert> alerts = new List <Alert>(); alerts.Add(new TestAlert("test title", analysisRequest.TargetResources.First(), AlertState.Active)); return(Task.FromResult(alerts)); }
/// <summary> /// Initiates an asynchronous operation for running the Smart Detector analysis on the specified resources. /// </summary> /// <param name="analysisRequest">The analysis request data.</param> /// <param name="tracer"> /// A tracer used for emitting telemetry from the Smart Detector's execution. This telemetry will be used for troubleshooting and /// monitoring the Smart Detector's executions. /// </param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for a task to complete.</param> /// <returns> /// A <see cref="Task"/> that represents the asynchronous operation, returning the Alerts detected for the target resources. /// </returns> public async Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { tracer.TraceInformation("Analyzing the specified resources..."); // Get the Log Analytics client ILogAnalyticsClient dataClient = await analysisRequest.AnalysisServicesFactory.CreateLogAnalyticsClientAsync(analysisRequest.RequestParameters.TargetResources.First(), cancellationToken); // Run the query IList <DataTable> dataTables = await dataClient.RunQueryAsync(@"$tableName$ | count", TimeSpan.FromDays(1), cancellationToken); // Process the query results and create alerts List <Alert> alerts = new List <Alert>(); if (dataTables[0].Rows.Count > 0) { // Query the count over time chart IList <DataTable> countOverTimeDataTables = await dataClient.RunQueryAsync("$query$", TimeSpan.FromDays(1), cancellationToken); // And create the alert var alert = new $alertName$("Title", analysisRequest.RequestParameters.TargetResources.First(), Convert.ToInt32(dataTables[0].Rows[0]["Count"])) { CountChart = countOverTimeDataTables[0].Rows.Cast <DataRow>().Select(row => new ChartPoint(row["timestamp"], row["Count"])).ToList() }; alerts.Add(alert); } tracer.TraceInformation($"Created {alerts.Count()} alerts"); return(alerts); } }
public Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { List <Alert> alerts = new List <Alert>(); alerts.Add(new TestAlert(typeof(T).Name, analysisRequest.RequestParameters.TargetResources.Single())); return(Task.FromResult(alerts)); }
private async Task TestLoadSignalSimple(Type signalType, string expectedTitle = "test test test") { ISmartSignalLoader loader = new SmartSignalLoader(this.tracerMock.Object); SmartSignalManifest manifest = new SmartSignalManifest("3", "simple", "description", Version.Parse("1.0"), signalType.Assembly.GetName().Name, signalType.FullName, new List <ResourceType>() { ResourceType.Subscription }, new List <int> { 60 }); SmartSignalPackage package = new SmartSignalPackage(manifest, this.assemblies["3"]); ISmartSignal signal = loader.LoadSignal(package); Assert.IsNotNull(signal, "Signal is NULL"); var resource = new ResourceIdentifier(ResourceType.VirtualMachine, "someSubscription", "someGroup", "someVM"); var analysisRequest = new AnalysisRequest( new List <ResourceIdentifier> { resource }, DateTime.UtcNow.AddDays(-1), TimeSpan.FromDays(1), new Mock <IAnalysisServicesFactory>().Object); SmartSignalResult signalResult = await signal.AnalyzeResourcesAsync(analysisRequest, this.tracerMock.Object, default(CancellationToken)); Assert.AreEqual(1, signalResult.ResultItems.Count, "Incorrect number of result items returned"); Assert.AreEqual(expectedTitle, signalResult.ResultItems.Single().Title, "Result item title is wrong"); Assert.AreEqual(resource, signalResult.ResultItems.Single().ResourceIdentifier, "Result item resource identifier is wrong"); }
private async void OnCreateGraph() { IsReady = false; Save(); var request = new AnalysisRequest { Spec = Document.Text, PackagesToAnalyze = PackagesToAnalyze != null?PackagesToAnalyze.ToArray() : null, UsedTypesOnly = UsedTypesOnly, AllEdges = AllEdges, CreateClustersForNamespaces = CreateClustersForNamespaces }; try { myCTS = new CancellationTokenSource(); var doc = await myAnalysisClient.AnalyseAsync(request, myCTS.Token); myCTS.Dispose(); myCTS = null; if (doc != null) { BuildGraph(doc); } } finally { IsReady = true; } }
private Network GetNetworkToAnalyze(AnalysisRequest request) { request = request ?? throw new ArgumentNullException(nameof(request)); var network = NetworkReaderHelper.ReadDataSet(request.DataSet); if (request.Approach == AnalysisApproach.SingleLayerOnly) { var errors = ValidateSingleLayerAnalysis(request, network); if (errors.Count > 0) { throw new ArgumentException(string.Join('\n', errors)); } var selected = request.SelectedLayer; var layer = network.Layers[selected]; return(new Network(layer, network.Actors)); } if (request.Approach == AnalysisApproach.SingleLayerFlattening) { return(Flattening[request.FlatteningAlgorithm].Flatten(network, request.FlatteningAlgorithmParameters)); } return(network); }
public Task <SmartSignalResult> AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { SmartSignalResult smartSignalResult = new SmartSignalResult(); smartSignalResult.ResultItems.Add(new TestSignalResultItem("test title", analysisRequest.TargetResources.First())); return(Task.FromResult(smartSignalResult)); }
public Guid Start(AnalysisRequest request) { InitAnalysis(request.PlatformId); Task.Run(async() => { try { var platform = GetPlatform(request.PlatformId); var processor = new AnalysisProcessor { AnalysisRequest = request, RequestUrl = platform.Url, ExecuteRequestFunc = ExecuteRequestAsync }; var tasks = await processor.StartAsync(); await Task .WhenAll(tasks) .ContinueWith(async t => await SaveAnalysisAsync(request.PlatformId)); } catch (Exception ex) { _logger.LogError(ex, $"Starting analysis failed for Platform: {request.PlatformId}, AnalysisId: {_analysisId}"); _analysisId = default; } }); return(_analysisId); }
public Task <SmartSignalResult> AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { SmartSignalResult smartSignalResult = new SmartSignalResult(); smartSignalResult.ResultItems.Add(new TestResultItem(typeof(T).Name, analysisRequest.TargetResources.Single())); return(Task.FromResult(smartSignalResult)); }
private async Task TestLoadSmartDetectorSimple(SmartDetectorPackage package, string expectedTitle) { ISmartDetectorLoader loader = new SmartDetectorLoader(this.tempFolder, this.tracerMock.Object); ISmartDetector detector = loader.LoadSmartDetector(package); Assert.IsNotNull(detector, "Smart Detector is NULL"); var resource = new ResourceIdentifier(ResourceType.VirtualMachine, "someSubscription", "someGroup", "someVM"); var analysisRequest = new AnalysisRequest( new AnalysisRequestParameters( DateTime.UtcNow, new List <ResourceIdentifier> { resource }, TimeSpan.FromDays(1), null, null), new Mock <IAnalysisServicesFactory>().Object, new Mock <IStateRepository>().Object); List <Alert> alerts = await detector.AnalyzeResourcesAsync(analysisRequest, this.tracerMock.Object, default(CancellationToken)); Assert.AreEqual(1, alerts.Count, "Incorrect number of alerts returned"); Assert.AreEqual(expectedTitle, alerts.Single().Title, "Alert title is wrong"); Assert.AreEqual(resource, alerts.Single().ResourceIdentifier, "Alert resource identifier is wrong"); }
public async Task Analyze_MultiLayer_CLECC() { var request = new AnalysisRequest() { CreateDate = new DateTime(2020, 12, 01), DataSet = DataSetHelper.Florentine, SelectedLayer = 0, Approach = AnalysisApproach.MultiLayer, AnalysisAlgorithm = AnalysisAlgorithm.CLECC, AnalysisAlgorithmParameters = new Dictionary <string, string>() { { "k", "2" }, { "alpha", "1" }, }, FlatteningAlgorithm = FlatteningAlgorithm.BasicFlattening, FlatteningAlgorithmParameters = new Dictionary <string, string>(), }; using (var ctx = InitCtx(nameof(Analyze_MultiLayer_CLECC))) { var service = InitService(ctx); var analysis = await service.Analyze(1, 1, request); Assert.NotNull(analysis); Assert.NotNull(analysis.Result); Assert.NotNull(analysis.Request); } }
public async Task ValidContentAssistantRequest_ShouldSucceedAsync() { //Arrange var minimumIntentScore = 0.5; var settings = new ProcessContentAssistantSettings { Text = "Test case", OutputVariable = "responseVariable", Score = 55 }; Context.Flow.BuilderConfiguration.MinimumIntentScore = minimumIntentScore; var contentAssistantResource = new AnalysisRequest { Text = settings.Text, Score = settings.Score.Value / 100 }; var contentResult = new ContentResult { Combinations = new ContentCombination[] { new ContentCombination { Entities = new string[] { "teste" }, Intent = "Teste" }, }, Name = "Name", Result = new Message { Content = "Answer" } }; var contentResultResponse = JsonConvert.SerializeObject(new ContentAssistantActionResponse { HasCombination = true, Entities = contentResult.Combinations.First().Entities.ToList(), Intent = contentResult.Combinations.First().Intent, Value = contentResult.Result.Content.ToString() }); //Act _artificialIntelligenceExtension.GetContentResultAsync(Arg.Is <AnalysisRequest>( ar => ar.Score == contentAssistantResource.Score && ar.Text == contentAssistantResource.Text), Arg.Any <CancellationToken>()).Returns(contentResult); await _processContentAssistantAction.ExecuteAsync(Context, JObject.FromObject(settings), CancellationToken); //Assert await Context.Received(1).SetVariableAsync(settings.OutputVariable, contentResultResponse, CancellationToken); }
public IDiskAnalyzer Create(AnalysisRequest request, IAnalysisExport analysisExport) { return(new DiskAnalyzer { RootPath = request.RootPath, AnalysisExport = analysisExport, BlackList = request.BlackList }); }
public void AddActivityToAnalysisRequest(AnalysisRequest request, AnalysisRequestActivity activity) { request.Activities.Add(activity); activity.Date = DateTime.Now; activity.AnalysisRequest = request; context.SaveChanges(); }
/// <summary> /// Initiates an asynchronous operation for analyzing the Smart Detector on the specified resources. /// </summary> /// <param name="analysisRequest">The analysis request data.</param> /// <param name="tracer"> /// A tracer used for emitting telemetry from the Smart Detector's execution. This telemetry will be used for troubleshooting and /// monitoring the Smart Detector's executions. /// </param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for a task to complete.</param> /// <returns> /// A <see cref="Task"/> that represents the asynchronous operation, returning the Alerts detected for the target resources. /// </returns> public Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { var alerts = new List <Alert> { { new $alertName$("title", analysisRequest.TargetResources.First()) } }; return(Task.FromResult(alerts)); }
public Task <SmartSignalResult> AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { int[] obj = { 1, 2, 3 }; var dependent = new DependentClass(); SmartSignalResult smartSignalResult = new SmartSignalResult(); smartSignalResult.ResultItems.Add(new TestSignalResultItem( "test title - " + dependent.GetString() + " - " + dependent.ObjectToString(obj), analysisRequest.TargetResources.First())); return(Task.FromResult(smartSignalResult)); }
private bool ShouldCreateAnMonthlyAnalysisRequest(AnalysisRequest homologation, DateTime refDate) { bool hasMonthlyRequestThisMount = (context.AnalysisRequest.Count(r => r.CreateDate.Month == refDate.Month && r.CreateDate.Year == refDate.Year && r.Supplier.Id == homologation.Supplier.Id && r.Type == AnalysisRequest.MonthlyAnalysis) > 0); bool hasHomologationHappenedThisMount = (homologation.CreateDate.Month == refDate.Month && homologation.CreateDate.Year == refDate.Year); return(!hasMonthlyRequestThisMount && !hasHomologationHappenedThisMount); }
public Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken) { int[] obj = { 1, 2, 3 }; var dependent = new DependentClass(); List <Alert> alerts = new List <Alert>(); alerts.Add(new TestAlert( "test title - " + dependent.GetString() + " - " + dependent.ObjectToString(obj), analysisRequest.TargetResources.First())); return(Task.FromResult(alerts)); }
public async Task <IActionResult> StartAnalysis([FromBody] AnalysisRequest request) { if (_analysisService.IsAnalysisInProgress()) { return(new BadRequestObjectResult("An analysis is already in progress. Please try again later.")); } var analysisId = _analysisService.Start(request); return(new OkObjectResult(analysisId)); }
public async Task <AnalysisResponse> PerformAnalysisAsync(AnalysisRequest request, MerchantCredentials credentials = null) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (_credentials == null && credentials == null) { throw new InvalidOperationException("Credentials are null"); } var currentCredentials = credentials ?? _credentials; if (string.IsNullOrWhiteSpace(currentCredentials.MerchantId)) { throw new InvalidOperationException("Invalid credentials: MerchantId is null"); } if (string.IsNullOrWhiteSpace(currentCredentials.AccessToken)) { throw new InvalidOperationException("Invalid credentials: AccessToken is null"); } var httpRequest = new RestRequest(@"analysis/v2/", Method.POST) { RequestFormat = DataFormat.Json }; httpRequest.AddHeader("Content-Type", "application/json"); httpRequest.AddHeader("MerchantId", currentCredentials.MerchantId); httpRequest.AddHeader("Authorization", $"Bearer {currentCredentials.AccessToken}"); httpRequest.AddHeader("RequestId", Guid.NewGuid().ToString()); httpRequest.AddBody(new { request.Transaction, request.Card, request.Customer }); var cancellationTokenSource = new CancellationTokenSource(); var httpResponse = await RestClient.ExecuteTaskAsync(httpRequest, cancellationTokenSource.Token); if (httpResponse.StatusCode != HttpStatusCode.Created) { return(new AnalysisResponse { HttpStatus = httpResponse.StatusCode, ErrorDataCollection = JsonDeserializer.Deserialize <List <ErrorData> >(httpResponse) }); } var jsonResponse = JsonDeserializer.Deserialize <AnalysisResponse>(httpResponse); jsonResponse.HttpStatus = httpResponse.StatusCode; return(jsonResponse); }
/// <summary> /// Runs the smart signal. /// </summary> /// <param name="resources">The resources which the signal should run on.</param> /// <param name="analysisCadence">The analysis cadence.</param> /// <returns>A task that runs the smart signal.</returns> public async Task RunAsync(List <ResourceIdentifier> resources, TimeSpan analysisCadence) { this.cancellationTokenSource = new CancellationTokenSource(); this.Results.Clear(); var analysisRequest = new AnalysisRequest(resources, null, analysisCadence, this.analysisServicesFactory); try { // Run Signal this.IsSignalRunning = true; SmartSignalResult signalResults = await this.smartSignal.AnalyzeResourcesAsync( analysisRequest, this.Tracer, this.cancellationTokenSource.Token); // Create signal result items List <SignalResultItem> signalResultItems = new List <SignalResultItem>(); foreach (var resultItem in signalResults.ResultItems) { // Create result item presentation var resourceIds = resources.Select(resource => resource.ResourceName).ToList(); var smartSignalsSettings = new SmartSignalSettings(); var smartSignalRequest = new SmartSignalRequest(resourceIds, this.smartSignalManifes.Id, null, analysisCadence, smartSignalsSettings); SmartSignalResultItemQueryRunInfo queryRunInfo = await this.queryRunInfoProvider.GetQueryRunInfoAsync(new List <ResourceIdentifier>() { resultItem.ResourceIdentifier }, this.cancellationTokenSource.Token); SmartSignalResultItemPresentation resultItemPresentation = SmartSignalResultItemPresentation.CreateFromResultItem( smartSignalRequest, this.smartSignalManifes.Name, resultItem, queryRunInfo); // Create Azure resource identifier ResourceIdentifier resourceIdentifier = ResourceIdentifier.CreateFromResourceId(resultItemPresentation.ResourceId); signalResultItems.Add(new SignalResultItem(resultItemPresentation, resourceIdentifier)); } this.Results = new ObservableCollection <SignalResultItem>(signalResultItems); this.tracer.TraceInformation($"Found {this.Results.Count} results"); } catch (OperationCanceledException) { this.Tracer.TraceError("Signal run was canceled."); } catch (Exception e) { this.Tracer.ReportException(e); } finally { this.IsSignalRunning = false; this.cancellationTokenSource?.Dispose(); } }
public async Task <ICollection <Entity> > AnalyzeEntities(string sentence) { var request = new AnalysisRequest() { Document = new Document() { Text = sentence } }; var r = await client.AnalyzePostAsync("standard", Language2.En, Analysis.Entities, request); return(r.Success ? r.Data.Entities : throw new Exception(r.Errors.Select(e => e.Message).Aggregate((s1, s2) => s1 + Environment.NewLine + s2))); }
public async Task <CategorizeDocument> AnalyzeBehavioralTraits(string sentence) { var request = new AnalysisRequest() { Document = new Document() { Text = sentence } }; var r = await client.CategorizeAsync("behavioral-traits", Language3.En, request); return(r.Success ? r.Data : throw new Exception(r.Errors.Select(e => e.Message).Aggregate((s1, s2) => s1 + Environment.NewLine + s2))); }
private void SendCreateMonthlyAnalysisNotification(AnalysisRequest request) { using (var client = new SmtpClient()) { var mail = new MailMessage(); mail.IsBodyHtml = true; mail.To.Add(new MailAddress(request.Supplier.MainContactEmail)); mail.Subject = string.Format("Requisição de Análise Mensal"); mail.Body = string.Format("<html><body><p>A SAAD Consult solicita o envio dos documentos para acompanhamento mensal de suas atividades</p><p>CNPJ: {0}</p><p>Razão Social: {1}</p></body></html>", request.Supplier.CNPJ, request.Supplier.Name); client.Send(mail); } }
private static AnalysisRequest GetAppSettingValues() { var request = new AnalysisRequest(); var outputFolder = ConfigurationManager.AppSettings["OutputFolder"]; if (!string.IsNullOrWhiteSpace(outputFolder)) { request.LogOutputFolderLocation = outputFolder; } var outputFile = ConfigurationManager.AppSettings["OutputFile"]; if (!string.IsNullOrWhiteSpace(outputFile)) { request.LogOutputFileLocation = outputFile; } var loggerType = ConfigurationManager.AppSettings["LoggerType"]; if (!string.IsNullOrWhiteSpace(loggerType)) { if (Enum.IsDefined(typeof(LogType), loggerType)) { request.LogType = (LogType)Enum.Parse(typeof(LogType), loggerType, true); } } var loggerLevel = ConfigurationManager.AppSettings["LoggerLevel"]; if (!string.IsNullOrWhiteSpace(loggerLevel)) { if (Enum.IsDefined(typeof(LogLevel), loggerLevel)) { request.LogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), loggerLevel, true); } } var includeExternalRefs = ConfigurationManager.AppSettings["IncludeExternalReferences"]; if (!string.IsNullOrWhiteSpace(includeExternalRefs)) { bool result; if (bool.TryParse(includeExternalRefs, out result)) { request.IncludeExternalReferences = result; } } return(request); }