public void ValidateBatchId_false() { // Arrange var batchId = "ABC123"; var apiResponse = @"{ 'errors': [ { 'field': null, 'message': 'invalid batch id' } ] }" ; var mockRepository = new MockRepository(MockBehavior.Strict); var mockClient = mockRepository.Create <IClient>(); mockClient .Setup(c => c.GetAsync($"{ENDPOINT}/{batchId}", It.IsAny <CancellationToken>())) .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(apiResponse) }) .Verifiable(); var batches = new Batches(mockClient.Object, ENDPOINT); // Act var result = batches.ValidateBatchIdAsync(batchId).Result; // Assert result.ShouldBeFalse(); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Batch,Year")] Batches batches) { if (id != batches.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(batches); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BatchesExists(batches.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(batches)); }
/// <summary> /// Number修正 /// </summary> public void CorrectNumber() { if (HaveBatch) { Number = Batches.Sum(x => x.Number); } }
public async Task DispatchedEventsWillKeepBeingProcessed_ButUpdatedWillBeDelayedUntilARenderIsAcknowledged() { // Arrange var baseUri = new Uri(ServerFixture.RootUri, "/subdir"); await ConnectAutomaticallyAndWait(baseUri); await Client.SelectAsync("test-selector-select", "BasicTestApp.LimitCounterComponent"); Client.ConfirmRenderBatch = false; for (var i = 0; i < 10; i++) { await Client.ClickAsync("increment"); } await Client.ClickAsync("increment", expectRenderBatch : false); Assert.Single(Logs, l => (LogLevel.Debug, "The queue of unacknowledged render batches is full.") == (l.LogLevel, l.Message)); Assert.Equal("10", ((TextNode)Client.FindElementById("the-count").Children.Single()).TextContent); var fullCount = Batches.Count; // Act await Client.ClickAsync("increment", expectRenderBatch : false); Assert.Contains(Logs, l => (LogLevel.Debug, "The queue of unacknowledged render batches is full.") == (l.LogLevel, l.Message)); Assert.Equal(fullCount, Batches.Count); Client.ConfirmRenderBatch = true; // This will resume the render batches. await Client.ExpectRenderBatch(() => Client.ConfirmBatch(Batches.Last().Id)); // Assert Assert.Equal("12", ((TextNode)Client.FindElementById("the-count").Children.Single()).TextContent); Assert.Equal(fullCount + 1, Batches.Count); }
/// <summary> /// Gets the list of submitted batch-processing jobs. /// /// Gets the list of batch-processing jobs submitted by users. /// </summary> /// <param name="customData">Custom data object to pass data including custom request headers.</param> /// <returns><see cref="Batches" />Batches</returns> public Batches ListBatches(Dictionary <string, object> customData = null) { if (string.IsNullOrEmpty(VersionDate)) { throw new ArgumentNullException("versionDate cannot be null."); } Batches result = null; try { IClient client = this.Client.WithAuthentication(_tokenManager.GetToken()); var restRequest = client.GetAsync($"{this.Endpoint}/v1/batches"); restRequest.WithArgument("version", VersionDate); if (customData != null) { restRequest.WithCustomData(customData); } restRequest.WithHeader("X-IBMCloud-SDK-Analytics", "service_name=compare-comply;service_version=v1;operation_id=ListBatches"); result = restRequest.As <Batches>().Result; if (result == null) { result = new Batches(); } result.CustomData = restRequest.CustomData; } catch (AggregateException ae) { throw ae.Flatten(); } return(result); }
public void ValidateBatchId_false() { // Arrange var batchId = "ABC123"; var apiResponse = @"{ 'errors': [ { 'field': null, 'message': 'invalid batch id' } ] }" ; var mockHttp = new MockHttpMessageHandler(); mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT, batchId)).Respond(HttpStatusCode.BadRequest, "application/json", apiResponse); var client = Utils.GetFluentClient(mockHttp); var batches = new Batches(client); // Act var result = batches.ValidateBatchIdAsync(batchId).Result; // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); result.ShouldBeFalse(); }
private Client(string apiKey, string username, string password, string baseUri, string apiVersion, HttpClient httpClient) { _mustDisposeHttpClient = httpClient == null; _httpClient = httpClient; #if DEBUG Version = "DEBUG"; #else var assemblyVersion = typeof(Client).GetTypeInfo().Assembly.GetName().Version; Version = $"{assemblyVersion.Major}.{assemblyVersion.Minor}.{assemblyVersion.Build}"; #endif _fluentClient = new FluentClient(new Uri($"{baseUri.TrimEnd('/')}/{apiVersion.TrimStart('/')}"), httpClient) .SetUserAgent($"StrongGrid/{Version} (+https://github.com/Jericho/StrongGrid)") .SetRequestCoordinator(new SendGridRetryStrategy()); _fluentClient.Filters.Remove <DefaultErrorFilter>(); _fluentClient.Filters.Add(new DiagnosticHandler()); _fluentClient.Filters.Add(new SendGridErrorHandler()); if (!string.IsNullOrEmpty(apiKey)) { _fluentClient.SetBearerAuthentication(apiKey); } if (!string.IsNullOrEmpty(username)) { _fluentClient.SetBasicAuthentication(username, password); } AccessManagement = new AccessManagement(_fluentClient); Alerts = new Alerts(_fluentClient); ApiKeys = new ApiKeys(_fluentClient); Batches = new Batches(_fluentClient); Blocks = new Blocks(_fluentClient); Bounces = new Bounces(_fluentClient); Campaigns = new Campaigns(_fluentClient); Categories = new Categories(_fluentClient); Contacts = new Contacts(_fluentClient); CustomFields = new CustomFields(_fluentClient); GlobalSuppressions = new GlobalSuppressions(_fluentClient); InvalidEmails = new InvalidEmails(_fluentClient); IpAddresses = new IpAddresses(_fluentClient); IpPools = new IpPools(_fluentClient); Lists = new Lists(_fluentClient); Mail = new Mail(_fluentClient); Segments = new Segments(_fluentClient); SenderIdentities = new SenderIdentities(_fluentClient); Settings = new Settings(_fluentClient); SpamReports = new SpamReports(_fluentClient); Statistics = new Statistics(_fluentClient); Subusers = new Subusers(_fluentClient); Suppressions = new Suppressions(_fluentClient); Teammates = new Teammates(_fluentClient); Templates = new Templates(_fluentClient); UnsubscribeGroups = new UnsubscribeGroups(_fluentClient); User = new User(_fluentClient); WebhookSettings = new WebhookSettings(_fluentClient); WebhookStats = new WebhookStats(_fluentClient); Whitelabel = new Whitelabel(_fluentClient); }
/// <summary> /// Exports to ILR /// </summary> /// <param name="usingSource">using source.</param> /// <param name="inContext">in context.</param> /// <param name="forProvider">for provider.</param> /// <returns> /// the currently running task /// </returns> public async Task Export(IInputDataSource usingSource, IConnectionDetail inContext, int forProvider) { It.IsNull(usingSource) .AsGuard <ArgumentNullException>(nameof(usingSource)); It.IsNull(inContext) .AsGuard <ArgumentNullException>(nameof(inContext)); await Task.Run(async() => { using (Timing.BeginScope($"Export file for {forProvider}")) { var schema = Schemas.GetSchema(usingSource.OperatingYear); var schemaPath = Path.Combine(Location.OfAssets, schema.Message); var templatePath = Path.Combine(Location.OfAssets, schema.BulkExport); var candidate = await FileManager.Load(templatePath); var batch = Batches.GetBatch(BatchProcessName.ExportSourceDataToILRFile, usingSource.OperatingYear); candidate = candidate.Replace(Token.ForNamespace, schema.Namespace); batch.Scripts .ForEach(script => RunScript(script, inContext, forProvider, ref candidate)); var outputPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "exportILR.xml"); await FileManager.Save(outputPath, candidate); await StripEmptyTags(outputPath); Emitter.Publish(Indentation.FirstLevel, CommonLocalised.Completed); //(!await Validator.IsValid(outputPath, schemaPath)) // .AsGuard<OperationCanceledException, CommonLocalised>(CommonLocalised.SchemaValidationFailed); } }); }
public void SetBatches(IEnumerable <Batch> batches) { if (batches == null || !batches.Any()) { return; } if (batches.Any(p => p.ProducerId != ProducerId)) { throw SheaftException.BadRequest("Une observation est liée au producteur, les lots doivent donc lui être liés."); } var existingBatchIds = Batches?.Select(b => b.BatchId).ToList() ?? new List <Guid>(); var newBatchIds = batches.Select(b => b.Id); var batchIdsToRemove = existingBatchIds.Except(newBatchIds); if (batchIdsToRemove.Any()) { RemoveBatches(Batches?.Where(b => batchIdsToRemove.Contains(b.BatchId)).Select(b => b.Batch).ToList()); } existingBatchIds = Batches?.Select(b => b.BatchId).ToList() ?? new List <Guid>(); var batchIdsToAdd = newBatchIds.Except(existingBatchIds); if (batchIdsToAdd.Any()) { AddBatches(batches.Where(b => batchIdsToAdd.Contains(b.Id)).ToList()); } Refresh(); }
public static int UpdateBatch(Batches batch) { using (VedantaEntities ve = new VedantaEntities()) { //Batches oldBatch = ve.Batches.FirstOrDefault(bt => bt.Id != batch.Id && !bt.BatchCode.Equals(batch.BatchCode, StringComparison.OrdinalIgnoreCase)); //if (oldBatch == null) //{ Batches currentBatch = ve.Batches.FirstOrDefault(bt => bt.Id == batch.Id); if (currentBatch != null) { currentBatch.BatchCode = batch.BatchCode; currentBatch.BatchStartTime = batch.BatchStartTime; currentBatch.BatchEndTime = batch.BatchEndTime; currentBatch.BatchName = batch.BatchName; currentBatch.StudentStrength = batch.StudentStrength; int result = ve.SaveChanges(); if (result > 0) { return(result); } } //} return(0); } }
public async Task ValidateBatchIdAsync_false() { // Arrange var batchId = "ABC123"; var apiResponse = @"{ ""errors"": [ { ""field"": null, ""message"": ""invalid batch id"" } ] }" ; var mockHttp = new MockHttpMessageHandler(); mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT, batchId)).Respond(HttpStatusCode.BadRequest, "application/json", apiResponse); var client = Utils.GetFluentClient(mockHttp); var batches = new Batches(client); // Act var result = await batches.ValidateBatchIdAsync(batchId).ConfigureAwait(false); // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); result.ShouldBeFalse(); }
/// <summary> /// 开始称重 /// </summary> /// <returns></returns> public string SaveBatchInfo(Batches dto) { dto.originalPlace = string.Empty; dto.istrace = false; dto.upload = false; dto.weighingBeginTime = DateTime.Now; dto.weighingFinishedTime = TimeHelper.GetMinDateTime(); try { var stime = new DateTime(dto.weighingBeginTime.Year, dto.weighingBeginTime.Month, dto.weighingBeginTime.Day); using (var sql = SugarDbContext.GetInstance()) { int sort = sql.Queryable <Batches>().Where(s => s.weighingBeginTime > stime) .OrderBy(s => s.sort, OrderByType.Desc).Select(s => s.sort).First(); sort += 1; dto.sort = sort; string sortNum = sort.ToString().PadLeft(2, '0'); dto.batchId = dto.yearNum + "-" + sortNum; sql.Insertable(dto).ExecuteCommand(); } return(dto.batchId); } catch (Exception e) { LogNHelper.Exception(e); } return(string.Empty); }
private void OnListBatches(Batches response, Dictionary <string, object> customData) { Log.Debug("TestCompareComplyV1.OnListBatches()", "ListBatches Response: {0}", customData["json"].ToString()); Test(response != null); Test(response._Batches != null); listBatchesTested = true; }
private Client(string apiKey, string username, string password, HttpClient httpClient, bool disposeClient, StrongGridClientOptions options) { _mustDisposeHttpClient = disposeClient; _httpClient = httpClient; _options = options ?? GetDefaultOptions(); _fluentClient = new FluentClient(new Uri(SENDGRID_V3_BASE_URI), httpClient) .SetUserAgent(Client.UserAgent) .SetRequestCoordinator(new SendGridRetryStrategy()); _fluentClient.Filters.Remove <DefaultErrorFilter>(); // Order is important: DiagnosticHandler must be first. // Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project. _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls)); _fluentClient.Filters.Add(new SendGridErrorHandler()); if (!string.IsNullOrEmpty(apiKey)) { _fluentClient.SetBearerAuthentication(apiKey); } if (!string.IsNullOrEmpty(username)) { _fluentClient.SetBasicAuthentication(username, password); } AccessManagement = new AccessManagement(_fluentClient); Alerts = new Alerts(_fluentClient); ApiKeys = new ApiKeys(_fluentClient); Batches = new Batches(_fluentClient); Blocks = new Blocks(_fluentClient); Bounces = new Bounces(_fluentClient); Campaigns = new Campaigns(_fluentClient); Categories = new Categories(_fluentClient); Contacts = new Contacts(_fluentClient); CustomFields = new CustomFields(_fluentClient); Designs = new Designs(_fluentClient); EmailActivities = new EmailActivities(_fluentClient); EmailValidation = new EmailValidation(_fluentClient); GlobalSuppressions = new GlobalSuppressions(_fluentClient); InvalidEmails = new InvalidEmails(_fluentClient); IpAddresses = new IpAddresses(_fluentClient); IpPools = new IpPools(_fluentClient); Lists = new Lists(_fluentClient); Mail = new Mail(_fluentClient); Segments = new Segments(_fluentClient); SenderIdentities = new SenderIdentities(_fluentClient); Settings = new Settings(_fluentClient); SpamReports = new SpamReports(_fluentClient); Statistics = new Statistics(_fluentClient); Subusers = new Subusers(_fluentClient); Suppressions = new Suppressions(_fluentClient); Teammates = new Teammates(_fluentClient); Templates = new Templates(_fluentClient); UnsubscribeGroups = new UnsubscribeGroups(_fluentClient); User = new User(_fluentClient); WebhookSettings = new WebhookSettings(_fluentClient); WebhookStats = new WebhookStats(_fluentClient); SenderAuthentication = new SenderAuthentication(_fluentClient); }
public async Task ValidateBatchIdAsync_problem() { // Arrange var batchId = "ABC123"; var apiResponse = @"{ 'errors': [ { 'field': null, 'message': 'an error has occured' } ] }" ; var mockHttp = new MockHttpMessageHandler(); mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT, batchId)).Respond(HttpStatusCode.BadRequest, "application/json", apiResponse); var client = Utils.GetFluentClient(mockHttp); var batches = new Batches(client); // Act var result = await Should.ThrowAsync <Exception>(async() => await batches.ValidateBatchIdAsync(batchId).ConfigureAwait(false)).ConfigureAwait(false); // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); result.Message.ShouldBe("an error has occured"); }
/// <summary> /// Store exists, a cleanse routine will be executed /// </summary> /// <param name="usingContext">using context.</param> /// <param name="forProvider">for provider.</param> /// <param name="inYear">in year.</param> public override void StoreExists(IContainSessionContext usingContext, int forProvider, BatchOperatingYear inYear) { var batch = Batches.GetBatch(BatchProcessName.CleanseProcessingDataStore, inYear); Emitter.Publish(batch.Description); Context.Run(batch.Scripts, usingContext.ProcessingLocation, x => Token.DoSecondaryPass(x, forProvider)); }
public void CompareSegments(CancellationToken token) { var allSegments = Batches.SelectMany(b => b.Pieces.SelectMany(p => p.Segments)).ToArray(); var groups = allSegments.GroupBy(s => s.IsPointy).ToArray(); Comparisons = new List <SegmentComparison>(); var hardTofillSegments = allSegments.ToDictionary(s => s, s => 0); if (groups.Length != 2) { Log.Error($"Expected 2 groups but was {groups.Length}"); return; } foreach (var a in groups.First()) { foreach (var b in groups.Last()) { if (a.Piece != b.Piece && hardTofillSegments[a] <= 1 && hardTofillSegments[b] <= 1) { if (token.IsCancellationRequested) { return; } var sw = new Stopwatch(); sw.Start(); Comparisons.Add(new SegmentComparison(a, b)); if (sw.Elapsed > TimeSpan.FromSeconds(3)) { hardTofillSegments[a]++; hardTofillSegments[b]++; } } } } Comparisons = Comparisons.OrderBy(c => c.Distance).ToList(); //var displayImage = Batches.First().GetDisplayImage(); //var colors = new[] { Color.Yellow, Color.Red, Color.Orange, Color.Cyan, Color.Indigo, Color.Chartreuse }; //for (var i = 0; i < Math.Min(colors.Length, Comparisons.Count); i++) //{ // var comp = Comparisons[i]; // CvInvoke.PutText(displayImage, i.ToString(), comp.A.Centroid, FontFace.HersheySimplex, 1.0, // new Bgr(colors[i]).MCvScalar, 2); // CvInvoke.PutText(displayImage, i.ToString(), comp.B.Centroid, FontFace.HersheySimplex, 1.0, // new Bgr(colors[i]).MCvScalar, 2); //} }
private IEnumerable <ValueB> GetLivingWorkItems(Batches batchesFull) { return(batchesFull.valueB.Where(x => x.fieldsB.SystemState.ToLower() != "failed" && x.fieldsB.SystemState.ToLower() != "removed" && x.fieldsB.SystemState.ToLower() != "to do" && x.fieldsB.SystemState.ToLower() != "todo" && x.fieldsB.SystemWorkItemType.ToLower() != "task")); }
public void AddTerrain(R_Landblock landblock) { if (CurrentBatch == null || !CurrentBatch.CanAdd(landblock)) { CurrentBatch = new TerrainBatchDraw(OverlayAtlasChain, AlphaAtlasChain); Batches.Add(CurrentBatch); } CurrentBatch.AddTerrain(landblock); }
/// <summary> /// Discard all buffer data. /// </summary> public void Dispose() { foreach (Batch batch in Batches) { batch.Dispose(); } Batches.Clear(); nodes.Clear(); }
public void XmlRead(XmlReader reader) { reader.ReadStartElement(nameof(BatchList)); NextBatchId = reader.ReadElementContentAsInt(nameof(NextBatchId), ""); while (reader.IsStartElement(nameof(Batch))) { Batches.Add(new Batch()); Batches.Last().XmlRead(reader); } }
/// <summary> /// Initializes a new instance of the <see cref="BaseClient" /> class. /// </summary> /// <param name="apiKey">Your api key.</param> /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param> /// <param name="disposeClient">Indicates if the http client should be dispose when this instance of BaseClient is disposed.</param> /// <param name="options">Options for the SendGrid client.</param> /// <param name="logger">Logger.</param> public BaseClient(string apiKey, HttpClient httpClient, bool disposeClient, StrongGridClientOptions options, ILogger logger = null) { _mustDisposeHttpClient = disposeClient; _httpClient = httpClient; _options = options; _logger = logger ?? NullLogger.Instance; _fluentClient = new FluentClient(new Uri(SENDGRID_V3_BASE_URI), httpClient) .SetUserAgent($"StrongGrid/{Version} (+https://github.com/Jericho/StrongGrid)") .SetRequestCoordinator(new SendGridRetryStrategy()); _fluentClient.Filters.Remove <DefaultErrorFilter>(); // Remove all the built-in formatters and replace them with our custom JSON formatter _fluentClient.Formatters.Clear(); _fluentClient.Formatters.Add(new JsonFormatter()); // Order is important: DiagnosticHandler must be first. // Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project. _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls, _logger)); _fluentClient.Filters.Add(new SendGridErrorHandler()); if (string.IsNullOrEmpty(apiKey)) { throw new ArgumentNullException(apiKey); } _fluentClient.SetBearerAuthentication(apiKey); AccessManagement = new AccessManagement(FluentClient); Alerts = new Alerts(FluentClient); ApiKeys = new ApiKeys(FluentClient); Batches = new Batches(FluentClient); Blocks = new Blocks(FluentClient); Bounces = new Bounces(FluentClient); Designs = new Designs(FluentClient); EmailActivities = new EmailActivities(FluentClient); EmailValidation = new EmailValidation(FluentClient); GlobalSuppressions = new GlobalSuppressions(FluentClient); InvalidEmails = new InvalidEmails(FluentClient); IpAddresses = new IpAddresses(FluentClient); IpPools = new IpPools(FluentClient); Mail = new Mail(FluentClient); Settings = new Settings(FluentClient); SpamReports = new SpamReports(FluentClient); Statistics = new Statistics(FluentClient); Subusers = new Subusers(FluentClient); Suppressions = new Suppressions(FluentClient); Teammates = new Teammates(FluentClient); Templates = new Templates(FluentClient); UnsubscribeGroups = new UnsubscribeGroups(FluentClient); User = new User(FluentClient); WebhookSettings = new WebhookSettings(FluentClient); WebhookStats = new WebhookStats(FluentClient); SenderAuthentication = new SenderAuthentication(FluentClient); }
public void End(Effect effect) { if (Batches.Count == 0) { return; } if (sortMode != SpriteBatch.SpriteSortMode.Immediate && sortMode != SpriteBatch.SpriteSortMode.Deffered) { Batches.Sort((x, y) => { int first = y.sortingKey.CompareTo(x.sortingKey); return(first); }); } //Array.Sort (Batches, 0, Batches.Count); Texture currentTexture = Batches.First().texture; int batchStart = 0, batchCount = 0; ushort bufferIndex = 0; ushort indicesIndex = 0; foreach (BatchItem item in Batches) { if (item.texture != currentTexture || batchCount == MAX_BATCH) { Flush(effect, currentTexture, batchStart, batchCount); currentTexture = item.texture; batchStart = batchCount = 0; indicesIndex = bufferIndex = 0; } indexData[indicesIndex++] = (ushort)(bufferIndex + 0); indexData[indicesIndex++] = (ushort)(bufferIndex + 1); indexData[indicesIndex++] = (ushort)(bufferIndex + 2); indexData[indicesIndex++] = (ushort)(bufferIndex + 1); indexData[indicesIndex++] = (ushort)(bufferIndex + 3); indexData[indicesIndex++] = (ushort)(bufferIndex + 2); vertexData[bufferIndex++] = new VertexPositionColorTexture(item.positions[0], item.color, item.texTopLeft); vertexData[bufferIndex++] = new VertexPositionColorTexture(item.positions[1], item.color, new Vector2(item.texBottomRight.X, item.texTopLeft.Y)); vertexData[bufferIndex++] = new VertexPositionColorTexture(item.positions[2], item.color, new Vector2(item.texTopLeft.X, item.texBottomRight.Y)); vertexData[bufferIndex++] = new VertexPositionColorTexture(item.positions[3], item.color, item.texBottomRight); batchCount++; } if (batchCount > 0) { Flush(effect, currentTexture, batchStart, batchCount); } }
public async Task <IActionResult> Create([Bind("Id,Batch,Year")] Batches batches) { if (ModelState.IsValid) { _context.Add(batches); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(batches)); }
//Draws the pendulum bobs. public override void Draw(State state) { //Sets width and height to canvas height and width propeties depending on //if the canvas is initialised. var width = Canvas.ActualWidth > 0 ? Canvas.ActualWidth : Canvas.Width; var height = Canvas.ActualHeight > 0 ? Canvas.ActualHeight : Canvas.Height; //Calaculate bob position. BobPosition.X = Length * Math.Sin(state.Displacement); BobPosition.Y = Length * Math.Cos(state.Displacement); PivotPosition = new Vec2 { X = width / 2, Y = height / 2 }; Batches.Add(DrawingMethods.FilledCircle(PivotPosition, 4, Brushes.Black)); //Calculate bob position relative to the canvas coordinates. BobPosCanvas.X = PivotPosition.X + BobPosition.X * PixelsPerMeter; BobPosCanvas.Y = PivotPosition.Y + BobPosition.Y * PixelsPerMeter; //Create line objects for pendulum arm. var arm = new LightLine { X1 = PivotPosition.X, Y1 = PivotPosition.Y, X2 = BobPosCanvas.X - BobRadius * Math.Sin(state.Displacement), Y2 = BobPosCanvas.Y - BobRadius * Math.Cos(state.Displacement) }; var armLineBatch = new LineBatch { LineThickness = 2 }; armLineBatch.Add(arm); Batches.Add(armLineBatch); //Draw origin circles depending on whether interaction is taking place. Batches.Add(IsInteracting ? DrawingMethods.FilledCircle(BobPosCanvas, (int)BobRadius, Brushes.Red) : DrawingMethods.FilledCircle(BobPosCanvas, (int)BobRadius, Brushes.Blue)); //Render the batches. foreach (var batch in Batches) { batch.Render(Canvas); batch.Clear(); } Batches.Clear(); }
/// <summary> /// Loads... /// </summary> /// <param name="intoSource">into source.</param> /// <param name="onMaster">on master.</param> /// <param name="fromInputFile">from input file.</param> /// <returns> /// the currently running task /// </returns> public async Task Load(IConnectionDetail intoSource, IConnectionDetail onMaster, string fromInputFile) { await Task.Run(async () => { It.IsNull(intoSource) .AsGuard<ArgumentNullException>(nameof(intoSource)); It.IsNull(onMaster) .AsGuard<ArgumentNullException>(nameof(onMaster)); It.IsEmpty(fromInputFile) .AsGuard<ArgumentNullException>(nameof(fromInputFile)); //if (Context.DataStoreExists(intoSource.Name, onMaster)) //{ // Context.DropDataStore(intoSource.Name, onMaster); //} Emitter.Publish($"Creating data store: {intoSource.DBName}"); //Context.CreateDataStore(intoSource.Name, onMaster); var content = await FileManager.Load(fromInputFile); // <= very lazy and inefficient.. var messageNamespace = GetHeaderNameSpace(content); It.IsEmpty(messageNamespace) .AsGuard<ArgumentException, Localised>(Localised.UnableToRetrieveMessageNamespace); var buildSchema = await Schema.Generate( messageNamespace, intoSource, (inContext, loadSchemaPath, createTables) => { var loader = GetLoader(inContext, createTables); loader.Execute(loadSchemaPath, fromInputFile); }); Mediator.Publish(ChangeYearMessage.Create(buildSchema.Year, buildSchema.Collection)); var batchList = Batches.GetBatch(BatchProcessName.BuildSourceDataStore, buildSchema.Year); var s = batchList.Scripts.ElementAt(1).Command; if (s.Contains("ILR")) { s = Regex.Replace(s, @"[A-Z]\w+-[0-9]\w+-[0-9]\w+-[0-9]\w+-[0-9]\w+-[0-9]\w+", Path.GetFileNameWithoutExtension(fromInputFile)); } else { s = s.Replace("originalFileName", Path.GetFileNameWithoutExtension(fromInputFile)); } batchList.Scripts.ElementAt(1).Command = s; Emitter.Publish(batchList.Description); Context.Run(batchList.Scripts, intoSource); }); }
private void AddBatches(IEnumerable <Batch> batches) { if (Batches == null) { Batches = new List <ObservationBatch>(); } foreach (var batch in batches) { Batches.Add(new ObservationBatch(batch)); } }
private void Initialize() { Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); ApiKeys = new APIKeys(this); UnsubscribeGroups = new UnsubscribeGroups(this); Suppressions = new Suppressions(this); GlobalSuppressions = new GlobalSuppressions(this); GlobalStats = new GlobalStats(this); Templates = new Templates(this); Versions = new Versions(this); Batches = new Batches(this); }
private void CreateDefaultConfiguration() { Client = new BlazorClient() { DefaultLatencyTimeout = DefaultLatencyTimeout }; Client.RenderBatchReceived += (id, data) => Batches.Add(new Batch(id, data)); Client.OnCircuitError += (error) => Errors.Add(error); _ = _serverFixture.RootUri; // this is needed for the side-effects of getting the URI. TestSink = _serverFixture.Host.Services.GetRequiredService <TestSink>(); TestSink.MessageLogged += LogMessages; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { Logger.Trace("OnActionExecuting"); var batchId = filterContext.ActionParameters["id"].ToString() .ToNullableInt32(); var batch = Batches.GetById(batchId.Value) .Include(b => b.Fund) .FirstOrDefault(); filterContext.Controller.ViewBag.FundContext = batch.Fund; }