SignalR.Client => SelfHost

This commit is contained in:
2023-06-27 10:00:11 -07:00
parent cc4473ffa8
commit 97d1a1c6a7
12 changed files with 124 additions and 119 deletions

View File

@ -0,0 +1,63 @@
using System;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web.Http;
namespace Adaptation.FileHandlers.MoveAllFiles.ApiController;
[Route("api/[controller]")]
public class BarcodeController : System.Web.Http.ApiController
{
#nullable enable
#pragma warning disable CA1822
public string Get()
#pragma warning restore CA1822
{
string results = "record";
return results;
}
private static string? GetJson(System.Net.Http.HttpContent? httpContent)
{
string? result;
if (httpContent is null)
result = null;
else
{
Task<string> task = httpContent.ReadAsStringAsync();
task.Wait();
result = task.Result;
}
return result;
}
private static void Write(string barcodeHostFileShare, string cellInstanceConnectionName, Notification notification)
{
DateTime dateTime = DateTime.Now;
Calendar calendar = new CultureInfo("en-US").Calendar;
string weekOfYear = $"{dateTime:yyyy}_Week_{calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
string directory = Path.Combine(barcodeHostFileShare, weekOfYear, dateTime.ToString("yyyy-MM-dd_HH"));
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, $"{cellInstanceConnectionName}.csv"), notification.LastScanServiceResultValue);
}
[Route("{id}")]
#pragma warning disable CA1822
public void Post(string id)
#pragma warning restore CA1822
{
string? json = GetJson(Request.Content);
if (json is not null)
{
Notification? notification = JsonSerializer.Deserialize<Notification>(json);
if (notification is not null)
Write(FileRead.BarcodeHostFileShare, id, notification.Value);
}
}
}

View File

@ -1,4 +1,4 @@
namespace Adaptation.FileHandlers.TIBCO.SignalR;
namespace Adaptation.FileHandlers.MoveAllFiles.ApiController;
/// <summary>
/// Mapping for this can be found here: https://github.com/torvalds/linux/blob/master/include/uapi/linux/input-event-codes.h

View File

@ -1,6 +1,6 @@
using System;
namespace Adaptation.FileHandlers.TIBCO.SignalR;
namespace Adaptation.FileHandlers.MoveAllFiles.ApiController;
public readonly struct KeyPressEvent
{

View File

@ -0,0 +1,8 @@
namespace Adaptation.FileHandlers.MoveAllFiles.ApiController;
public enum KeyState
{
KeyUp,
KeyDown,
KeyHold
}

View File

@ -1,10 +1,11 @@
namespace Adaptation.FileHandlers.TIBCO.SignalR;
namespace Adaptation.FileHandlers.MoveAllFiles.ApiController;
public readonly struct Notification
{
public KeyPressEvent KeyPressEvent { get; }
public string LastScanServiceResultValue { get; }
[System.Text.Json.Serialization.JsonConstructor]
public Notification(KeyPressEvent keyPressEvent, string lastScanServiceResultValue)
{
KeyPressEvent = keyPressEvent;

View File

@ -7,13 +7,20 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace Adaptation.FileHandlers.MoveAllFiles;
public class FileRead : Shared.FileRead, IFileRead
{
#nullable enable
private long? _TickOffset;
private readonly HttpSelfHostServer? _HttpSelfHostServer;
public const string BarcodeHostFileShare = @"\\messv02ecc1.ec.local\EC_Metrology_Si\BarcodeHost\API"; // GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "BarcodeHost.FileShare");
public FileRead(ISMTP smtp, Dictionary<string, string> fileParameter, string cellInstanceName, int? connectionCount, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList<ModelObjectParameterDefinition> modelObjectParameters, string equipmentDictionaryName, Dictionary<string, List<long>> dummyRuns, Dictionary<long, List<string>> staticRuns, bool useCyclicalForDescription, bool isEAFHosted) :
base(new Description(), false, smtp, fileParameter, cellInstanceName, connectionCount, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, staticRuns, useCyclicalForDescription, isEAFHosted: connectionCount is null)
@ -27,7 +34,21 @@ public class FileRead : Shared.FileRead, IFileRead
throw new Exception(cellInstanceConnectionName);
if (_IsDuplicator)
throw new Exception(cellInstanceConnectionName);
if (!_IsEAFHosted)
_HttpSelfHostServer = null;
else
{
// string propertyName = string.Concat("CellInstance.", cellInstanceName, ".HttpSelfHostConfiguration.BaseAddress");
// string httpSelfHostConfigurationBaseAddress = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, propertyName);
string httpSelfHostConfigurationBaseAddress = "http://localhost:8080/";
HttpSelfHostConfiguration config = new(httpSelfHostConfigurationBaseAddress);
_ = config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
_HttpSelfHostServer = new(config);
_HttpSelfHostServer.OpenAsync().Wait();
}
}
#nullable disable
void IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, Exception exception) => Move(extractResults);

View File

@ -6,6 +6,7 @@ using Adaptation.Shared.Methods;
using Adaptation.Shared.Metrology;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;
@ -16,6 +17,7 @@ public class FileRead : Shared.FileRead, IFileRead
{
private readonly string _OpenInsightMetrologyViewerAPI;
private readonly string _OpenInsightMetrologyViewerFileShare;
public FileRead(ISMTP smtp, Dictionary<string, string> fileParameter, string cellInstanceName, int? connectionCount, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList<ModelObjectParameterDefinition> modelObjectParameters, string equipmentDictionaryName, Dictionary<string, List<long>> dummyRuns, Dictionary<long, List<string>> staticRuns, bool useCyclicalForDescription, bool isEAFHosted) :
base(new Description(), false, smtp, fileParameter, cellInstanceName, connectionCount, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, staticRuns, useCyclicalForDescription, isEAFHosted: connectionCount is null)
@ -29,6 +31,7 @@ public class FileRead : Shared.FileRead, IFileRead
throw new Exception(cellInstanceConnectionName);
if (!_IsDuplicator)
throw new Exception(cellInstanceConnectionName);
_OpenInsightMetrologyViewerFileShare = @"\\messv02ecc1.ec.local\EC_Metrology_Si\MetrologyAttachments\SP1RunHeader_";
_OpenInsightMetrologyViewerAPI = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "OpenInsight.MetrologyViewerAPI");
}
@ -107,11 +110,15 @@ public class FileRead : Shared.FileRead, IFileRead
return results;
}
#pragma warning disable IDE0060
private void SendData(DateTime dateTime, List<txt.Description> descriptions)
#pragma warning restore IDE0060
private void SendData(string reportFullPath, DateTime dateTime, List<txt.Description> descriptions)
{
WSRequest wsRequest = new(this, _Logistics, descriptions);
int weekOfYear = _Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
string directory = Path.Combine(_OpenInsightMetrologyViewerFileShare, dateTime.Year.ToString(), $"WW{weekOfYear:00}", _Logistics.Sequence.ToString());
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
string fullPath = Path.Combine(directory, Path.GetFileName(reportFullPath));
File.Copy(reportFullPath, fullPath);
WSRequest wsRequest = new(this, _Logistics, descriptions, fullPath);
(string json, WS.Results wsResults) = WS.SendData(_OpenInsightMetrologyViewerAPI, wsRequest);
if (!wsResults.Success)
throw new Exception(wsResults.ToString());
@ -134,7 +141,7 @@ public class FileRead : Shared.FileRead, IFileRead
List<txt.Description> descriptions = txt.ProcessData.GetDescriptions(jsonElements);
Test[] tests = (from l in descriptions select (Test)l.Test).ToArray();
if (_IsEAFHosted && _FileConnectorConfiguration.FileScanningIntervalInSeconds > 0)
SendData(dateTime, descriptions);
SendData(reportFullPath, dateTime, descriptions);
results = new Tuple<string, Test[], JsonElement[], List<FileInfo>>(pdsf.Item1, tests, jsonElements, new List<FileInfo>());
return results;
}

View File

@ -267,13 +267,15 @@ public class WSRequest
public string DwnSlipMin { get; set; }
public string DwnSlipStDev { get; set; }
public List<txt.Detail> Details { get; protected set; }
public string ProcessDataStandardFormat { get; set; }
[Obsolete("For json")] public WSRequest() { }
#pragma warning disable IDE0060
internal WSRequest(IFileRead fileRead, Logistics logistics, List<txt.Description> descriptions)
internal WSRequest(IFileRead fileRead, Logistics logistics, List<txt.Description> descriptions, string processDataStandardFormat = null)
#pragma warning restore IDE0060
{
ProcessDataStandardFormat = processDataStandardFormat;
Details = new List<txt.Detail>();
CellName = logistics.MesEntity;
txt.Description x = descriptions[0];
@ -636,7 +638,7 @@ public class WSRequest
{
if (string.IsNullOrEmpty(json))
{
WSRequest wsRequest = new(fileRead, logistics, descriptions);
WSRequest wsRequest = new(fileRead, logistics, descriptions, string.Empty);
(json, WS.Results wsResults) = WS.SendData(openInsightMetrologyViewerAPI, wsRequest);
if (!wsResults.Success)
throw new Exception(wsResults.ToString());

View File

@ -1,31 +1,22 @@
using Adaptation.Eaf.Management.ConfigurationData.CellAutomation;
using Adaptation.FileHandlers.TIBCO.SignalR;
using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using Adaptation.Shared;
using Adaptation.Shared.Duplicator;
using Adaptation.Shared.Methods;
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Adaptation.FileHandlers.TIBCO;
public class FileRead : Shared.FileRead, IFileRead, IAsyncDisposable
public class FileRead : Shared.FileRead, IFileRead
{
#nullable enable
private long? _TickOffset;
private readonly Timer _Timer;
private readonly string _BarcodeHostFileShare;
private readonly HubConnection? _HubConnectionBioRad2;
private readonly HubConnection? _HubConnectionBioRad3;
public FileRead(ISMTP smtp, Dictionary<string, string> fileParameter, string cellInstanceName, int? connectionCount, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList<ModelObjectParameterDefinition> modelObjectParameters, string equipmentDictionaryName, Dictionary<string, List<long>> dummyRuns, Dictionary<long, List<string>> staticRuns, bool useCyclicalForDescription, bool isEAFHosted) :
base(new Description(), false, smtp, fileParameter, cellInstanceName, connectionCount, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, staticRuns, useCyclicalForDescription, isEAFHosted: connectionCount is null)
@ -39,7 +30,6 @@ public class FileRead : Shared.FileRead, IFileRead, IAsyncDisposable
throw new Exception(cellInstanceConnectionName);
if (!_IsDuplicator)
throw new Exception(cellInstanceConnectionName);
_Timer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite);
string metrologyFileShare = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "Metrology.FileShare");
_BarcodeHostFileShare = @"\\messv02ecc1.ec.local\EC_Metrology_Si\BarcodeHost\API"; // GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "BarcodeHost.FileShare");
string lsl2SQLConnectionString = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "ConnectionString.LSL2SQL");
@ -49,8 +39,6 @@ public class FileRead : Shared.FileRead, IFileRead, IAsyncDisposable
string tibcoParameterSubjectPrefix = GetPropertyValue(cellInstanceConnectionName, tibcoParameters, "TIBCO.IFX_SUBJECT_PREFIX");
string tibcoParameterConfigurationLocation = GetPropertyValue(cellInstanceConnectionName, tibcoParameters, "TIBCO.IFX_CONFIGURATION_LOCATION");
string tibcoParameterConfigurationLocationCopy = GetPropertyValue(cellInstanceConnectionName, tibcoParameters, "TIBCO.IFX_CONFIGURATION_LOCATION_LOCAL_COPY");
string hostDomainBioRad2 = "unity4"; // GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "CellInstance.BIORAD2.StaticFileServer");
string hostDomainBioRad3 = "unity5"; // GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "CellInstance.BIORAD3.StaticFileServer");
if (!Directory.Exists(metrologyFileShare))
throw new Exception($"Unable to access file-share <{metrologyFileShare}>");
if (!Directory.Exists(_BarcodeHostFileShare))
@ -62,25 +50,6 @@ public class FileRead : Shared.FileRead, IFileRead, IAsyncDisposable
_ = Transport.Main.Setup(useSleep: true, setIfxTransport: true, tibcoParameterChannel, tibcoParameterSubjectPrefix, tibcoParameterConfigurationLocation, tibcoParameterConfigurationLocationCopy, tibcoParameterSubject);
else
_ = Transport.Main.Setup(useSleep: false, setIfxTransport: false, tibcoParameterChannel, tibcoParameterSubjectPrefix, tibcoParameterConfigurationLocation, tibcoParameterConfigurationLocationCopy, tibcoParameterSubject);
_HubConnectionBioRad2 = new HubConnectionBuilder()
.WithUrl(new Uri($"https://{hostDomainBioRad2}/NotificationHub"))
.WithAutomaticReconnect()
.Build();
_HubConnectionBioRad2.Closed += Closed;
_ = _HubConnectionBioRad2.On<Notification>("NotifyAll", OnNotifyAllBioRad2);
_HubConnectionBioRad3 = new HubConnectionBuilder()
.WithUrl(new Uri($"https://{hostDomainBioRad3}/NotificationHub"))
.WithAutomaticReconnect()
.Build();
_HubConnectionBioRad3.Closed += Closed;
_ = _HubConnectionBioRad3.On<Notification>("NotifyAll", OnNotifyAllBioRad3);
}
if (Debugger.IsAttached || fileConnectorConfiguration.PreProcessingMode == FileConnectorConfiguration.PreProcessingModeEnum.Process || _FileConnectorConfiguration.FileScanningIntervalInSeconds is null)
Callback(null);
else
{
TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks);
_ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite);
}
}
@ -168,66 +137,4 @@ public class FileRead : Shared.FileRead, IFileRead, IAsyncDisposable
return results;
}
private Task Closed(Exception? exception) =>
throw new NotImplementedException();
private void Write(string cellInstanceConnectionName, Notification notification)
{
DateTime dateTime = DateTime.Now;
string weekOfYear = $"{dateTime:yyyy}_Week_{_Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
string directory = Path.Combine(_BarcodeHostFileShare, weekOfYear, dateTime.ToString("yyyy-MM-dd_HH"));
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, $"{cellInstanceConnectionName}.csv"), notification.LastScanServiceResultValue);
}
private void OnNotifyAllBioRad2(Notification notification) =>
Write("BIORAD2", notification);
private void OnNotifyAllBioRad3(Notification notification) =>
Write("BIORAD3", notification);
public async ValueTask DisposeAsync()
{
if (_HubConnectionBioRad2 is not null)
await _HubConnectionBioRad2.DisposeAsync();
if (_HubConnectionBioRad3 is not null)
await _HubConnectionBioRad3.DisposeAsync();
}
private void Callback(object? state)
{
try
{
int modulus = DateTime.Now.Second % 2;
if (modulus == 0 && _HubConnectionBioRad2?.State == HubConnectionState.Disconnected)
_HubConnectionBioRad2.StartAsync().Wait();
if (modulus == 1 && _HubConnectionBioRad3?.State == HubConnectionState.Disconnected)
_HubConnectionBioRad3.StartAsync().Wait();
}
catch (Exception exception)
{
string subject = string.Concat("Exception:", _CellInstanceConnectionName);
string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace);
try
{ _SMTP.SendHighPriorityEmailMessage(subject, body); }
catch (Exception) { }
}
try
{
if (_FileConnectorConfiguration.FileScanningIntervalInSeconds is null)
throw new NullReferenceException(nameof(_FileConnectorConfiguration.FileScanningIntervalInSeconds));
TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks);
_ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite);
}
catch (Exception exception)
{
string subject = string.Concat("Exception:", _CellInstanceConnectionName);
string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace);
try
{ _SMTP.SendHighPriorityEmailMessage(subject, body); }
catch (Exception) { }
}
}
}

View File

@ -1,8 +0,0 @@
namespace Adaptation.FileHandlers.TIBCO.SignalR;
public enum KeyState
{
KeyUp,
KeyDown,
KeyHold
}

View File

@ -43,7 +43,7 @@
<PackageReference Include="IKVM.OpenJDK.XML.API" Version="7.2.4630.5"><NoWarn>NU1701</NoWarn></PackageReference>
<PackageReference Include="IKVM.Runtime" Version="7.2.4630.5"><NoWarn>NU1701</NoWarn></PackageReference>
<PackageReference Include="Instances" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNet.WebApi.SelfHost" Version="5.2.9" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" />

View File

@ -102,6 +102,11 @@
<Compile Include="Adaptation\FileHandlers\CellInstanceConnectionName.cs" />
<Compile Include="Adaptation\FileHandlers\Dummy\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\IQSSi\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\MoveAllFiles\ApiController\BarcodeController.cs" />
<Compile Include="Adaptation\FileHandlers\MoveAllFiles\ApiController\EventCode.cs" />
<Compile Include="Adaptation\FileHandlers\MoveAllFiles\ApiController\KeyPressEvent.cs" />
<Compile Include="Adaptation\FileHandlers\MoveAllFiles\ApiController\KeyState.cs" />
<Compile Include="Adaptation\FileHandlers\MoveAllFiles\ApiController\Notification.cs" />
<Compile Include="Adaptation\FileHandlers\MoveAllFiles\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\MoveMatchingFiles\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\OpenInsightMetrologyViewerAttachments\FileRead.cs" />
@ -112,10 +117,6 @@
<Compile Include="Adaptation\FileHandlers\Processed\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\SPaCe\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\FileRead.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\SignalR\EventCode.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\SignalR\KeyPressEvent.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\SignalR\KeyState.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\SignalR\Notification.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\Transport\Input.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\Transport\Item.cs" />
<Compile Include="Adaptation\FileHandlers\TIBCO\Transport\Job.cs" />
@ -178,8 +179,11 @@
<PackageReference Include="Infineon.EAF.Runtime">
<Version>2.49.2</Version>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client">
<Version>7.0.5</Version>
<PackageReference Include="Microsoft.AspNet.WebApi.SelfHost">
<Version>5.2.7</Version>
</PackageReference>
<PackageReference Include="Microsoft.AspNet.WebApi.Core">
<Version>5.2.7</Version>
</PackageReference>
<PackageReference Include="System.Text.Json">
<Version>6.0.3</Version>