public MainWindow() : base(Gtk.WindowType.Toplevel) { Build(); lcdDrawingarea.SetSizeRequest(178, 128); //Set stubs lcdStub = new LcdStub(lcdDrawingarea); brickStub = new BrickStub(); brickStub.OnShutDown += OnShutDown; Lcd.Instance = lcdStub; Buttons.Instance = buttonsStub; ProgramManager.Instance = programManagerStub; FirmwareSettings.Instance = firmwareSettings; WiFiDevice.Instance = wiFiStub; UpdateHelper.Instance = updateHelperStub; Brick.Instance = brickStub; //Load and apply simulator settings simulatorSettings = new SimulatorSettings(); simulatorSettings.Load(); simulatorSettings.Save(); ApplySettings(); //Setup settings changed handler watcher.Path = Directory.GetCurrentDirectory(); watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.CreationTime; watcher.Filter = simulatorSettings.SettingsFileName; watcher.Changed += OnSettingsFileChanged; watcher.EnableRaisingEvents = true; lcdDrawingarea.ExposeEvent += LcdExposed; }
public async Task Verify(FileInfo kplModelFile, FileInfo outputFile, SimulatorSettings settings, ISimulatorProgressMonitor monitor) { this.settings = settings; this.monitor = monitor; await Task.Run(() => { try { monitor.Start(5, string.Format("Simulates the {0} model using the FLAME simulator...", kplModelFile.Name)); monitor.LogProgress(0, "Translate in the correspoding FLAME model..."); FileInfo tempFolder; TranslateModel(kplModelFile, outputFile, out tempFolder); monitor.LogProgress(2, "Generating the FLAME model..."); GenerateModel(new FileInfo(tempFolder + modelGeneratedFile)); monitor.LogProgress(3, "Compiling the FLAME model..."); CompileModel(tempFolder); Clean(tempFolder); monitor.LogProgress(4, "Simulate the FLAME model..."); Simulate(outputFile); monitor.Done("Finished the simulation process"); } catch (Exception e) { monitor.Terminate("Simulation failed: " + e.Message); } }); }
// ReSharper disable once UnusedMember.Global public async Task InvokeAsync(HttpContext context, SimulatorSettings simulatorSettings, SasKeyValidator sasHeaderValidator, ILogger logger) { if (IsNotificationRequest(context)) { await ValidateNotificationRequest(context, simulatorSettings, sasHeaderValidator, logger); return; } if (IsValidationRequest(context)) { await ValidateSubscriptionValidationRequest(context); return; } if (IsStoreRequest(context)) { await _next(context); return; } // This is the end of the line. await context.Response.ErrorResponse(HttpStatusCode.BadRequest, "Request not supported."); }
public void ConfigureServices(IServiceCollection services) { var settings = new SimulatorSettings(); _configuration.Bind(settings); settings.Validate(); services.AddSingleton(_ => settings); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddHttpClient(); services.AddScoped <SasKeyValidator>(); services.AddSingleton <ValidationIpAddress>(); services.AddControllers(options => { options.EnableEndpointRouting = false; }) .AddJsonOptions(options => { options.JsonSerializerOptions.WriteIndented = true; }) .SetCompatibilityVersion(CompatibilityVersion.Latest); services.AddApiVersioning(config => { config.DefaultApiVersion = new ApiVersion(DateTime.Parse(Constants.SupportedApiVersion, new ApiVersionFormatProvider())); config.AssumeDefaultVersionWhenUnspecified = true; config.ReportApiVersions = true; }); }
public static IServiceCollection AddSimulatorSettings(this IServiceCollection services, IConfiguration configuration) { var settings = new SimulatorSettings(); configuration.Bind(settings); settings.Validate(); services.AddSingleton(_ => settings); return(services); }
public SubscriptionValidationService(SimulatorSettings simulatorSettings, IHttpClientFactory httpClientFactory, ValidationIpAddress validationIpAddress, ILogger logger) { _simulatorSettings = simulatorSettings; _httpClientFactory = httpClientFactory; _validationIpAddress = validationIpAddress; _logger = logger; }
protected override string CurrentFirmwareVersion() { System.Threading.Thread.Sleep(100); SimulatorSettings settings = new SimulatorSettings(); settings.Load(); string runningPath = settings.BootSettings.StartUpDir; return(Assembly.LoadFrom(Path.Combine(runningPath, "MonoBrickFirmware.dll")).GetName().Version.ToString()); }
public ValidateAllSubscriptionsCommandHandler(ILogger <ValidateAllSubscriptionsCommandHandler> logger, IHttpClientFactory httpClientFactory, SimulatorSettings simulatorSettings, ValidationIpAddress validationIpAddress) { _logger = logger; _httpClientFactory = httpClientFactory; _simulatorSettings = simulatorSettings; _validationIpAddress = validationIpAddress; }
public static void LaunchAppleSimulator(this ICakeContext context, string deviceIdentifier, SimulatorSettings settings) { if (string.IsNullOrWhiteSpace(deviceIdentifier)) { throw new ArgumentException(nameof(deviceIdentifier)); } ThrowIfNotRunningOnMac(context); var runner = new SimulatorRunner(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log, settings); runner.LaunchSimulator(deviceIdentifier); }
public async Task InvokeAsync(HttpContext context, SimulatorSettings simulatorSettings, SasKeyValidator aegSasHeaderValidator) { var requestPort = context.Connection.LocalPort; var topic = simulatorSettings.Topics.First(t => t.Port == requestPort); if (!string.IsNullOrWhiteSpace(topic.Key) && !aegSasHeaderValidator.IsValid(context.Request.Headers, topic.Key)) { await context.Response.ErrorResponse(HttpStatusCode.Unauthorized, "The request did not contain a valid aeg-sas-key or aeg-sas-token."); return; } await _next(context); }
public async Task InvokeAsync(HttpContext context, SimulatorSettings simulatorSettings, ILogger logger) { var events = context.RetrieveEvents(); var topicSettings = context.RetrieveTopicSettings(); foreach (var eventGridEvent in events) { eventGridEvent.Topic = $"/subscriptions/{Guid.Empty:D}/resourceGroups/eventGridSimulator/providers/Microsoft.EventGrid/topics/{topicSettings.Name}"; eventGridEvent.MetadataVersion = "1"; } context.SaveEvents(events); context.SaveRequestBodyJson(JsonConvert.SerializeObject(events, Formatting.Indented)); await _next(context); }
public void ConfigureServices(IServiceCollection services) { var settings = new SimulatorSettings(); Configuration.Bind(settings); settings.Validate(); services.AddSingleton(o => settings); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddHttpClient(); services.AddHostedService <SubscriptionValidationService>(); services.AddSingleton(o => _loggerFactory.CreateLogger(nameof(AzureEventGridSimulator))); services.AddScoped <SasKeyValidator>(); services.AddSingleton <ValidationIpAddress>(); services.AddMvc(x => x.EnableEndpointRouting = false) .SetCompatibilityVersion(CompatibilityVersion.Latest); }
public void ConfigureServices(IServiceCollection services) { var settings = new SimulatorSettings(); Configuration.Bind(settings); settings.Validate(); services.AddSingleton(o => settings); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddHttpClient(); services.AddHostedService <SubscriptionValidationService>(); services.AddSingleton(o => _loggerFactory.CreateLogger(nameof(AzureEventGridSimulator))); services.AddScoped <SasKeyValidator>(); services.AddSingleton <ValidationIpAddress>(); services.AddSingleton <EventHistory>(); services.AddControllers().AddNewtonsoftJson(); }
public async Task Verify(FileInfo kplModelFile, FileInfo outputFile, SimulatorSettings settings, ISimulatorProgressMonitor monitor) { this.settings = settings; await Task.Run(() => { try { monitor.Start(1, string.Format("Simulating the {0} model using the kPWorkbench simulator...", kplModelFile.Name)); monitor.LogProgress(0, "Performing simulation..."); Execute(kplModelFile, outputFile); monitor.Done("Finished the simulation process"); } catch (Exception e) { monitor.Terminate("Simulation failed: " + e.Message); } }); }
public override bool UpdateBootFile() { /* Not yet used need some building * XmlDocument doc = new XmlDocument(); * doc.Load("EV3MonoBrickSimulator.exe.config"); * XmlNode node = doc.SelectSingleNode ("configuration/runtime").FirstChild.FirstChild; * node.Attributes [0].Value = GetAvailableFirmware (); * doc.Save ("EV3MonoBrickSimulator.exe.config"); */ string newDir = Path.Combine(Directory.GetCurrentDirectory(), GetAvailableFirmware()); SimulatorSettings settings = new SimulatorSettings(); if (settings.Load()) { settings.BootSettings.StartUpDir = newDir; return(settings.Save()); } return(false); }
public void ConfigureServices(IServiceCollection services) { var settings = new SimulatorSettings(); _configuration.Bind(settings); settings.Validate(); services.AddSingleton(o => settings); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddHttpClient(); services.AddScoped <SasKeyValidator>(); services.AddSingleton <ValidationIpAddress>(); services.AddControllers(options => options.EnableEndpointRouting = false) .AddJsonOptions(options => { options.JsonSerializerOptions.WriteIndented = true; }) .SetCompatibilityVersion(CompatibilityVersion.Latest); }
public async Task InvokeAsync(HttpContext context, SimulatorSettings simulatorSettings, ILogger logger) { if (context.Request.Method != HttpMethods.Post || !string.Equals(context.Request.Path, "/api/events", StringComparison.OrdinalIgnoreCase)) { await context.Response.ErrorResponse(HttpStatusCode.BadRequest, "Not supported."); return; } var requestBody = await EnsureRequestBodyStreamIsWritable(context); var events = JsonConvert.DeserializeObject <EventGridEvent[]>(requestBody); var requestPort = context.Connection.LocalPort; var topicSettings = simulatorSettings.Topics.First(t => t.Port == requestPort); context.SaveRequestBodyJson(requestBody); context.SaveEvents(events); context.Items["TopicSettings"] = topicSettings; await _next(context); }
// ReSharper disable once UnusedMember.Global public async Task InvokeAsync(HttpContext context, SimulatorSettings simulatorSettings, ILogger logger) { var events = context.RetrieveEvents(); foreach (var evt in events) { try { evt.Validate(); } catch (InvalidOperationException ex) { logger.LogError(ex, "Event was not valid."); await context.Response.ErrorResponse(HttpStatusCode.BadRequest, ex.Message); return; } } await _next(context); }
public async Task InvokeAsync(HttpContext context, SimulatorSettings simulatorSettings, ILogger logger) { var requestBody = context.RetrieveRequestBodyJson(); var requestBodyLength = requestBody.Length; logger.LogDebug("Message is {Bytes} in length.", requestBody.Length); if (requestBodyLength > MaximumAllowedOverallMessageSizeInBytes) { logger.LogError("Payload is larger than the allowed maximum."); await context.Response.ErrorResponse(HttpStatusCode.RequestEntityTooLarge, "Payload is larger than the allowed maximum."); return; } var events = context.RetrieveEvents(); foreach (var evt in events) { var eventJson = JsonConvert.SerializeObject(evt, Formatting.Indented); var eventJsonLength = eventJson.Length; logger.LogDebug("Event is {Bytes} in length.", eventJsonLength); if (eventJsonLength > MaximumAllowedEventGridEventSizeInBytes) { logger.LogError("Event is larger than the allowed maximum."); await context.Response.ErrorResponse(HttpStatusCode.RequestEntityTooLarge, "Event is larger than the allowed maximum."); return; } } await _next(context); }
private async void bPerformSimulation_Click(object sender, EventArgs e) { FileInfo kplModelFile = new FileInfo(tbModelSimulation.Text); string output = tbOutputSimulation.Text; if (output.Substring(output.Length - 1, 1) != @"\") { output = output + @"\"; } FileInfo outputFile = new FileInfo(output); SimulatorSettings settings = new SimulatorSettings(); settings.Steps = (int)nudStepsSimulation.Value; settings.SkipSteps = (int)nudSkipStepsSimulation.Value; settings.Seed = (int)nudSeedSimulation.Value; settings.RecordRuleSelection = cbRecordRuleSelection.Checked; settings.RecordTargetSelection = cbRecordTargetSelection.Checked; settings.RecordInstanceCreation = cbRecordInstanceCreation.Checked; settings.RecordConfigurations = cbRecordConfigurations.Checked; settings.ConfigurationsOnly = cbConfigurationsOnly.Checked; if (TestPaths() == false) { return; } if (cbSimulatorSimulation.SelectedItem.ToString() == GetTypeDescription(SimulatorTarget.Kpw)) { await SimulatorManager.Instance.Verify(kplModelFile, outputFile, settings, SimulatorTarget.Kpw, new UiProgressMonitor(lMessageProgressMonitorSimulation, lDetailsProgressMonitorSimulation, pbProgressMonitorSimulation)); } else if (cbSimulatorSimulation.SelectedItem.ToString() == GetTypeDescription(SimulatorTarget.Flame)) { await SimulatorManager.Instance.Verify(kplModelFile, outputFile, settings, SimulatorTarget.Flame, new UiProgressMonitor(lMessageProgressMonitorSimulation, lDetailsProgressMonitorSimulation, pbProgressMonitorSimulation)); } }
/// <summary> /// Creates a subsequence from a source sequence given the settings provided /// </summary> /// <param name="index"></param> /// <param name="sequenceToSplit"></param> /// <param name="simulatorSettings"></param> /// <returns></returns> private ISequence CreateSubsequence(long index, ISequence sequenceToSplit, SimulatorSettings simulatorSettings) { double err = simulatorSettings.ErrorFrequency; // Set the length using the appropriate random number distribution type long subLength = simulatorSettings.SequenceLength; switch (simulatorSettings.DistributionType) { case (int)Distribution.Uniform: subLength += _seqRandom.Next(simulatorSettings.LengthVariation * 2) - simulatorSettings.LengthVariation; break; case (int)Distribution.Normal: subLength = (long)Math.Floor(Bio.Util.Helper.GetNormalRandom(simulatorSettings.SequenceLength, simulatorSettings.LengthVariation)); break; } // Quick sanity checks on the length of the subsequence if (subLength <= 0) subLength = 1; if (subLength > sequenceToSplit.Count) subLength = sequenceToSplit.Count; // Set the start position long startPosition = (long)Math.Floor(_seqRandom.NextDouble() * (sequenceToSplit.Count - subLength)); byte[] sequenceBytes = new byte[subLength]; IAlphabet resultSequenceAlphabet = sequenceToSplit.Alphabet; // Get ambiguity symbols if (simulatorSettings.AllowAmbiguities && (sequenceToSplit.Alphabet == DnaAlphabet.Instance || sequenceToSplit.Alphabet == RnaAlphabet.Instance || sequenceToSplit.Alphabet == ProteinAlphabet.Instance)) { resultSequenceAlphabet = Alphabets.AmbiguousAlphabetMap[sequenceToSplit.Alphabet]; } List<byte> errorSource = resultSequenceAlphabet.GetValidSymbols().ToList(); // remove gap and termination symbol HashSet<byte> gaps, terminations; sequenceToSplit.Alphabet.TryGetGapSymbols(out gaps); sequenceToSplit.Alphabet.TryGetTerminationSymbols(out terminations); if (gaps != null) errorSource.RemoveAll(a => gaps.Contains(a)); if (terminations != null) errorSource.RemoveAll(a => terminations.Contains(a)); for (long i = 0; i < subLength; i++) { // Apply Errors if applicable sequenceBytes[i] = _seqRandom.NextDouble() < err ? errorSource[_seqRandom.Next(errorSource.Count - 1)] : sequenceToSplit[startPosition + i]; } ISequence generatedSequence = new Sequence(resultSequenceAlphabet, sequenceBytes.ToArray()); generatedSequence.ID = sequenceToSplit.ID + " (Split " + (index + 1) + ", " + generatedSequence.Count + "bp)"; // Reverse Sequence if applicable return simulatorSettings.ReverseHalf && _seqRandom.NextDouble() < 0.5f ? new DerivedSequence(generatedSequence, true, true) : generatedSequence; }
protected SimulatorController(SimulatorSettings simulatorSettings) { _simulatorSettings = simulatorSettings; }
public SubscriptionValidationController(SimulatorSettings simulatorSettings, IMediator mediator) { _simulatorSettings = simulatorSettings; _mediator = mediator; }
private static void FeedAddFiles(string folderPath, Dictionary <DateTime, string> dictAllFileNames, SimulatorSettings simulatorSettings) { var fileNames = Directory.GetFiles(folderPath).ToList(); var lstFileDates = new List <string>(); foreach (var fileName in fileNames) { var fileDate = File.GetCreationTime(fileName); if (fileDate.Date == TDAStreamerData.simulatorSettings.runDateDate.Date) { if (fileDate.TimeOfDay >= TDAStreamerData.simulatorSettings.startTime.TimeOfDay && fileDate.TimeOfDay <= TDAStreamerData.simulatorSettings.endTime.TimeOfDay) { /// Since GetLastAccessTime is only to the second, add millis to make fileDate unique while (dictAllFileNames.ContainsKey(fileDate)) { fileDate = fileDate.AddMilliseconds(1); } dictAllFileNames.Add(fileDate, fileName); } } } }
private async Task ValidateNotificationRequest(HttpContext context, SimulatorSettings simulatorSettings, SasKeyValidator sasHeaderValidator, ILogger <EventGridMiddleware> logger) { var topic = simulatorSettings.Topics.First(t => t.Port == context.Connection.LocalPort); // // Validate the key/ token supplied in the header. // if (!string.IsNullOrWhiteSpace(topic.Key) && !sasHeaderValidator.IsValid(context.Request.Headers, topic.Key)) { await context.Response.ErrorResponse(HttpStatusCode.Unauthorized, "The request did not contain a valid aeg-sas-key or aeg-sas-token.", null); return; } context.Request.EnableBuffering(); var requestBody = await context.RequestBody(); var events = JsonConvert.DeserializeObject <EventGridEvent[]>(requestBody); // // Validate the overall body size and the size of each event. // const int maximumAllowedOverallMessageSizeInBytes = 1536000; const int maximumAllowedEventGridEventSizeInBytes = 66560; logger.LogTrace("Message is {Bytes} in length.", requestBody.Length); if (requestBody.Length > maximumAllowedOverallMessageSizeInBytes) { logger.LogError("Payload is larger than the allowed maximum."); await context.Response.ErrorResponse(HttpStatusCode.RequestEntityTooLarge, "Payload is larger than the allowed maximum.", null); return; } foreach (var evt in events) { // ReSharper disable once MethodHasAsyncOverload var eventSize = JsonConvert.SerializeObject(evt, Formatting.None).Length; logger.LogTrace("Event is {Bytes} in length.", eventSize); if (eventSize > maximumAllowedEventGridEventSizeInBytes) { logger.LogError("Event is larger than the allowed maximum."); await context.Response.ErrorResponse(HttpStatusCode.RequestEntityTooLarge, "Event is larger than the allowed maximum.", null); return; } } // // Validate the properties of each event. // foreach (var eventGridEvent in events) { try { eventGridEvent.Validate(); } catch (InvalidOperationException ex) { logger.LogError(ex, "Event was not valid."); await context.Response.ErrorResponse(HttpStatusCode.BadRequest, ex.Message, null); return; } } await _next(context); }
public async Task Verify(FileInfo kplModelFile, FileInfo outputFile, SimulatorSettings settings, SimulatorTarget target, ISimulatorProgressMonitor monitor) { var executor = GetExecutor(target); await executor.Verify(kplModelFile, outputFile, settings, monitor); }
/// <summary> /// Needs to read filenames from 3 folders and return one list in time order /// </summary> /// <param name="TDAStreamerData.simulatorSettings"></param> /// <returns></returns> internal static Dictionary <DateTime, string> GetFeedFileNames(string symbol, SimulatorSettings simulatorSettings) { /// Get all file times, names into one dictionary var dictAllFileNames = new Dictionary <DateTime, string>(); var folderPath = $"D:\\MessageQs\\Inputs\\CHART_EQUITY\\{symbol}\\{TDAStreamerData.simulatorSettings.runDate}\\"; FeedAddFiles(folderPath, dictAllFileNames, TDAStreamerData.simulatorSettings); folderPath = $"D:\\MessageQs\\Inputs\\TIMESALE_EQUITY\\{symbol}\\{TDAStreamerData.simulatorSettings.runDate}\\"; FeedAddFiles(folderPath, dictAllFileNames, TDAStreamerData.simulatorSettings); folderPath = $"D:\\MessageQs\\Inputs\\NASDAQ_BOOK\\{symbol}\\{TDAStreamerData.simulatorSettings.runDate}\\"; FeedAddFiles(folderPath, dictAllFileNames, TDAStreamerData.simulatorSettings); /// Get all times into a sorted list var lstAllTimes = new List <DateTime>(); lstAllTimes = dictAllFileNames.Keys.ToList(); lstAllTimes.Sort(); /// Create sorted dictionary var dictFinalFilesNames = new Dictionary <DateTime, string>(); foreach (var time in lstAllTimes) { dictFinalFilesNames.Add(time, dictAllFileNames[time]); } return(dictFinalFilesNames); }
public SubscriptionValidationController(SimulatorSettings simulatorSettings, IMediator mediator) : base(simulatorSettings) { _mediator = mediator; }
public SimulatorSettings() { instance = this; }
/// <summary> /// Constructor /// </summary> public SimulatorController() { _seqRandom = new Random(); Settings = new SimulatorSettings(); }
public NotificationController(SimulatorSettings simulatorSettings, IMediator mediator) : base(simulatorSettings) { _mediator = mediator; }
public NotificationController(SimulatorSettings simulatorSettings, IMediator mediator) { _mediator = mediator; _simulatorSettings = simulatorSettings; }