Esempio n. 1
0
        /// <summary>
        /// Snapshot sends a snapshot of the entire backend from a member over a stream to a client.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="method"></param>
        /// <param name="token"></param>
        public async void Snapshot(SnapshotRequest request, Action <SnapshotResponse> method, CancellationToken token, Metadata headers = null)
        {
            bool success    = false;
            int  retryCount = 0;

            while (!success)
            {
                try
                {
                    using (AsyncServerStreamingCall <SnapshotResponse> snapshotter = _balancer.GetConnection().maintenanceClient.Snapshot(request, headers))
                    {
                        Task snapshotTask = Task.Run(async() =>
                        {
                            while (await snapshotter.ResponseStream.MoveNext(token))
                            {
                                SnapshotResponse update = snapshotter.ResponseStream.Current;
                                method(update);
                            }
                        });

                        await snapshotTask;
                    }
                    success = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw ex;
                    }
                }
            }
        }
        public async Task <SnapshotResponse> WaitForSnapshotResponse(string sessionId, int fileSessionId)
        {
            var client                        = new HttpAuthClient();
            var snapshotStatusUrl             = $"https://studioapi.bluebeam.com/publicapi/v1/sessions/{sessionId}/files/{fileSessionId}/snapshot";
            SnapshotResponse snapshotResponse = null;

            while (true)
            {
                var response = await client.Get(snapshotStatusUrl, User, _userManager);

                snapshotResponse = JsonConvert.DeserializeObject <SnapshotResponse>(response);
                Console.WriteLine("Snapshot Response: " + snapshotResponse.Status);

                if (snapshotResponse.Status == "Complete")
                {
                    break;
                }
                else if (snapshotResponse.Status == "Error")
                {
                    break;
                }

                Thread.Sleep(5000);
            }

            return(snapshotResponse);
        }
        public ActionResult GetSnapShotHistory()
        {
            logger.LogInformation("Getting all snapshot history");
            try
            {
                var snapShotHistory = inventoryService.GetSnapShotHistory();
                // get distinct points in timeline was collected
                var timeLineMarkers = snapShotHistory.Select(i => i.SnapShotTime).Distinct().ToList();
                // get qunatities grouped by id
                var snapshots = snapShotHistory.GroupBy(hist => hist.Product, hist => hist.QuantityOnHand,
                                                        (key, g) => new ProductInventorySnapshotModel
                {
                    ProductId      = key.Id,
                    QuantityOnHand = g.ToList()
                }).OrderBy(hist => hist.ProductId)
                                .ToList();

                var viewModel = new SnapshotResponse
                {
                    TimeLine = timeLineMarkers,
                    ProductInventorySnapshots = snapshots
                };
                return(Ok(viewModel));
            }
            catch (Exception e)
            {
                logger.LogError("Error getting snapshot history");
                logger.LogError(e.StackTrace);
                return(BadRequest("Error Retrieving History"));
            }
        }
Esempio n. 4
0
        public ActionResult GetSnapshotHistory()
        {
            _logger.LogInformation("Getting snapshot history information");
            try
            {
                var snapshotHistory = _stockService.GetSnapshotHistory();
                var timelineMarkers = snapshotHistory.Select(t => t.SnapshotTime).Distinct().ToList();
                var snapshots       = snapshotHistory.GroupBy(hist => hist.Material, hist => hist.AvailableQuantity, (key, g) => new MaterialStockSnapshotModel
                {
                    MaterialId        = key.Id,
                    AvailableQuantity = g.ToList()
                }).OrderBy(hist => hist.MaterialId).ToList();

                var viewModel = new SnapshotResponse
                {
                    Timeline = timelineMarkers,
                    MaterialStockSnapshots = snapshots
                };
                return(Ok(viewModel));
            }catch (Exception e)
            {
                _logger.LogError("error getting snapshot history.");
                _logger.LogError(e.StackTrace);
                return(BadRequest("Error retrieving history"));
            }
        }
        public ActionResult getSnapshotHistory()
        {
            _logger.LogInformation("Получение истории поставок");

            try {
                var snapshotHistory = _inventoryService.GetSnapshotsHistory();

                var timelineMarkers = snapshotHistory
                                      .Select(t => t.CreatedSnapshotOn)
                                      .Distinct()
                                      .ToList();

                var snapshots = snapshotHistory
                                .GroupBy(hist => hist.Product, hist => hist.QuantityOnHand,
                                         (key, g) => new InventorySnapshotViewModel {
                    ProductName    = key.Name,
                    QuantityOnHand = g.ToList()
                })
                                .OrderBy(hist => hist.ProductName)
                                .ToList();

                var snapshotsModel = new SnapshotResponse
                {
                    InventorySnapshots = snapshots,
                    Timeline           = timelineMarkers
                };

                return(Ok(snapshotsModel));
            } catch (Exception e) {
                _logger.LogError("Ошибка получения истории поставок");
                _logger.LogError(e.StackTrace);
                return(BadRequest("Ошибка получения истории поставок"));
            }
        }
Esempio n. 6
0
        public ActionResult GetSnapshotHistory()
        {
            _logger.LogInformation("Getting snapshot history");
            try
            {
                var snapshotHistory = _inventoryService.GetSnapshotHistory();
                var timelineMarkers = snapshotHistory.Select(t => t.SnapshotTime).Distinct().ToList();

                var snapshots = snapshotHistory
                                .GroupBy(hist => hist.Product, hist => hist.QuantityOnHand, (key, g) => new ProductInventorySnapshotModel
                {
                    ProductId      = key.Id,
                    QuantityOnHand = g.ToList()
                })
                                .OrderBy(h => h.ProductId)
                                .ToList();

                var viewModel = new SnapshotResponse
                {
                    Timeline = timelineMarkers,
                    ProductInventorySnapshots = snapshots
                };

                return(Ok(viewModel));
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting snapshot history.");
                _logger.LogError(ex.StackTrace);
                return(BadRequest("Error retriving history"));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Gets the projects and integration queues snapshot from this server.
        /// </summary>
        public CruiseServerSnapshot GetCruiseServerSnapshot()
        {
            SnapshotResponse resp = cruiseServer.GetCruiseServerSnapshot(GenerateServerRequest());

            ValidateResponse(resp);
            return(resp.Snapshot);
        }
Esempio n. 8
0
        public async Task SyncTracksAsync(PlaylistGenerationContext context)
        {
            FullTrack[] toDelete = context.TargetTracks
                                   .Where(t => !context.SourceTracks.Any(s => s.Id == t.Id))
                                   .ToArray();

            FullTrack[] toAdd = context.SourceTracks
                                .Where(s => !context.TargetTracks.Any(t => t.Id == s.Id))
                                .ToArray();

            foreach (IEnumerable <FullTrack> batch in toDelete.Batch(100))
            {
                PlaylistRemoveItemsRequest req = new PlaylistRemoveItemsRequest
                {
                    Tracks = batch.Select(o => new PlaylistRemoveItemsRequest.Item {
                        Uri = o.Uri
                    }).ToList()
                };

                SnapshotResponse res = await context.Client.Playlists.RemoveItems(context.TargetPlaylist.Id, req);
            }

            foreach (IEnumerable <FullTrack> batch in toAdd.Batch(100))
            {
                SnapshotResponse res = await context.Client.Playlists.AddItems(context.TargetPlaylist.Id, new PlaylistAddItemsRequest(batch.Select(o => o.Uri).ToList()));
            }

            context.TargetTracks = context.TargetTracks
                                   .Except(toDelete)
                                   .Concat(toAdd)
                                   .ToList();
        }
Esempio n. 9
0
        /// <summary>
        /// Snapshot sends a snapshot of the entire backend from a member over a stream to a client.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="methods"></param>
        /// <param name="token"></param>
        public async void Snapshot(SnapshotRequest request, Action <SnapshotResponse>[] methods, CancellationToken token)
        {
            try
            {
                using (AsyncServerStreamingCall <SnapshotResponse> snapshotter = _maintenanceClient.Snapshot(request, _headers))
                {
                    Task snapshotTask = Task.Run(async() =>
                    {
                        while (await snapshotter.ResponseStream.MoveNext(token))
                        {
                            SnapshotResponse update = snapshotter.ResponseStream.Current;
                            foreach (Action <SnapshotResponse> method in methods)
                            {
                                method(update);
                            }
                        }
                    });

                    await snapshotTask;
                }
            }
            catch (RpcException ex)
            {
                ResetConnection(ex);
                throw;
            }
            catch
            {
                throw;
            }
        }
Esempio n. 10
0
        public void InitialiseNewResponseSetsTheDefaultValues()
        {
            DateTime         now      = DateTime.Now;
            SnapshotResponse response = new SnapshotResponse();

            Assert.AreEqual(ResponseResult.Unknown, response.Result, "Result wasn't set to failure");
            Assert.IsTrue((now <= response.Timestamp), "Timestamp was not set");
        }
Esempio n. 11
0
        public void GetCruiseServerSnapshot()
        {
            SnapshotResponse response = new SnapshotResponse();

            response.Result = ResponseResult.Success;
            CruiseServerClient client = new CruiseServerClient(
                new ServerStub("GetCruiseServerSnapshot", typeof(ServerRequest), null, response));

            client.GetCruiseServerSnapshot();
        }
Esempio n. 12
0
        public void InitialiseResponseFromRequestSetsTheDefaultValues()
        {
            DateTime         now      = DateTime.Now;
            ServerRequest    request  = new ServerRequest();
            SnapshotResponse response = new SnapshotResponse(request);

            Assert.AreEqual(ResponseResult.Unknown, response.Result, "Result wasn't set to failure");
            Assert.AreEqual(request.Identifier, response.RequestIdentifier, "RequestIdentifier wasn't set to the identifier of the request");
            Assert.IsTrue((now <= response.Timestamp), "Timestamp was not set");
        }
Esempio n. 13
0
        private bool FillPlaylistWithTracks(string playlistId, List <FullTrack> tracksAddedToPlaylist)
        {
            List <string> trackUris = new List <string>();

            tracksAddedToPlaylist.ForEach(i => trackUris.Add(i.Uri));

            SnapshotResponse response = new SnapshotResponse();

            SplitList <string>(trackUris, 99).ForEach(i => response = _spotify.Playlists.AddItems(playlistId, new PlaylistAddItemsRequest(i)).Result);
            return(response.SnapshotId == null ? false : true);
        }
Esempio n. 14
0
        public void ToStringSerialisesDefaultValues()
        {
            SnapshotResponse response = new SnapshotResponse();
            string           actual   = response.ToString();
            string           expected = string.Format(System.Globalization.CultureInfo.CurrentCulture, "<snapshotResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
                                                      "timestamp=\"{1:yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz}\" result=\"{0}\" />",
                                                      response.Result,
                                                      response.Timestamp);

            XDocument.Parse(actual).Should().BeEquivalentTo(XDocument.Parse(expected));
        }
Esempio n. 15
0
        /// <summary>
        ///     Instructs Chrome to capture a snapshot from the loaded page
        /// </summary>
        /// <param name="countdownTimer">If a <see cref="CountdownTimer"/> is set then
        /// the method will raise an <see cref="ConversionTimedOutException"/> in the
        /// <see cref="CountdownTimer"/> reaches zero before finishing the printing to pdf</param>
        /// <remarks>
        ///     See https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureSnapshot
        /// </remarks>
        /// <returns></returns>
        internal async Task <SnapshotResponse> CaptureSnapshot(CountdownTimer countdownTimer = null)
        {
            var message = new Message {
                Method = "Page.captureSnapshot"
            };

            var result = countdownTimer == null
                ? await _pageConnection.SendAsync(message)
                : await _pageConnection.SendAsync(message).Timeout(countdownTimer.MillisecondsLeft);

            return(SnapshotResponse.FromJson(result));
        }
Esempio n. 16
0
        public void ToStringSerialisesAllValues()
        {
            QueueSnapshot queueSnapshot = new QueueSnapshot("queue1");

            queueSnapshot.Requests.Add(new QueuedRequestSnapshot("test project", ProjectActivity.Pending));
            QueueSetSnapshot queueSetSnapshot = new QueueSetSnapshot();

            queueSetSnapshot.Queues.Add(queueSnapshot);
            ProjectStatus        projectStatus = new ProjectStatus("test project", IntegrationStatus.Success, DateTime.Now);
            CruiseServerSnapshot snapshot      = new CruiseServerSnapshot(
                new ProjectStatus[] { projectStatus },
                queueSetSnapshot);
            SnapshotResponse response = new SnapshotResponse();

            response.ErrorMessages.Add(new ErrorMessage("Error 1"));
            response.ErrorMessages.Add(new ErrorMessage("Error 2"));
            response.RequestIdentifier = "request";
            response.Result            = ResponseResult.Success;
            response.Timestamp         = DateTime.Now;
            response.Snapshot          = snapshot;
            string actual   = response.ToString();
            string expected = string.Format(System.Globalization.CultureInfo.CurrentCulture, "<snapshotResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
                                            "timestamp=\"{2:yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz}\" identifier=\"{0}\" result=\"{1}\">" +
                                            "<error>Error 1</error>" +
                                            "<error>Error 2</error>" +
                                            "<snapshot>" +
                                            "<projects>" +
                                            "<projectStatus showForceBuildButton=\"true\" showStartStopButton=\"true\" serverName=\"{6}\" status=\"Running\" buildStatus=\"Success\" name=\"test project\" " +
                                            "queuePriority=\"0\" lastBuildDate=\"{3:yyyy-MM-ddTHH:mm:ss.FFFFFFF}\" nextBuildTime=\"{4:yyyy-MM-ddTHH:mm:ss.FFFFFFF}\">" +
                                            "<activity type=\"Sleeping\" />" +
                                            "<parameters />" +
                                            "</projectStatus>" +
                                            "</projects>" +
                                            "<queueSet>" +
                                            "<queue name=\"queue1\">" +
                                            "<queueRequest projectName=\"test project\" time=\"{5:yyyy-MM-ddTHH:mm:ss.FFFFFFF}\">" +
                                            "<activity type=\"Pending\" />" +
                                            "</queueRequest>" +
                                            "</queue>" +
                                            "</queueSet>" +
                                            "</snapshot>" +
                                            "</snapshotResponse>",
                                            response.RequestIdentifier,
                                            response.Result,
                                            response.Timestamp,
                                            projectStatus.LastBuildDate,
                                            projectStatus.NextBuildTime,
                                            DateTime.MinValue,
                                            Environment.MachineName);

            XDocument.Parse(actual).Should().BeEquivalentTo(XDocument.Parse(expected));
        }
Esempio n. 17
0
 /// <summary>
 /// Snapshot sends a snapshot of the entire backend from a member over a stream to a client.
 /// </summary>
 /// <param name="request">The request to send to the server.</param>
 /// <param name="method"></param>
 /// <param name="cancellationToken"></param>
 /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
 /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
 public async Task Snapshot(SnapshotRequest request, Action <SnapshotResponse> method,
                            CancellationToken cancellationToken, Grpc.Core.Metadata headers = null, DateTime?deadline = null) => await CallEtcdAsync(async (connection) =>
 {
     using (AsyncServerStreamingCall <SnapshotResponse> snapshotter = connection
                                                                      ._maintenanceClient.Snapshot(request, headers, deadline, cancellationToken))
     {
         while (await snapshotter.ResponseStream.MoveNext(cancellationToken).ConfigureAwait(false))
         {
             SnapshotResponse update = snapshotter.ResponseStream.Current;
             method(update);
         }
     }
 }).ConfigureAwait(false);
        public void ImportDecks_Standard_NoDelete()
        {
            var response = new SnapshotResponse();

            response.DeckTiers = new List <DeckSnapshot>()
            {
                new DeckSnapshot()
                {
                    Name = "Mage Deck",
                    Deck = new Deck()
                    {
                        PlayerClass = "Mage",
                        Cards       = new List <Card>()
                        {
                            new Card()
                            {
                                Quantity = 1,
                                Detail   = new CardDetail()
                                {
                                    Name = "Fireball"
                                }
                            },
                            new Card()
                            {
                                Quantity = 2,
                                Detail   = new CardDetail()
                                {
                                    Name = "Ice Block"
                                }
                            }
                        }
                    }
                }
            };

            var mock = new Mock <SnapshotImporter>(_http.Object, _data.Object, _log.Object);

            mock.Setup(x => x.GetSnapshotSlug(It.IsAny <string>()))
            .ReturnsAsync(new Tuple <string, string>("standard", "2017-02-01"));
            mock.Setup(x => x.GetSnapshot(It.IsAny <Tuple <string, string> >()))
            .ReturnsAsync(response);
            mock.CallBase = true;

            Assert.That(async() => await mock.Object.ImportDecks(false, true, false, true),
                        Is.EqualTo(1));

            _data.Verify(x => x.AddDeck(
                             It.Is <string>(s => s == "Deck"), It.Is <string>(s => s == "Mage"),
                             It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string[]>()),
                         Times.Once);
        }
Esempio n. 19
0
        public void InitialiseResponseFromResponseSetsTheDefaultValues()
        {
            DateTime         now       = DateTime.Now;
            SnapshotResponse response1 = new SnapshotResponse();

            response1.Result            = ResponseResult.Success;
            response1.RequestIdentifier = "original id";
            response1.Timestamp         = DateTime.Now.AddMinutes(-1);
            SnapshotResponse response2 = new SnapshotResponse(response1);

            Assert.AreEqual(ResponseResult.Success, response2.Result, "Result wasn't set to failure");
            Assert.AreEqual("original id", response2.RequestIdentifier, "RequestIdentifier wasn't set to the identifier of the request");
            Assert.IsTrue((response1.Timestamp == response2.Timestamp), "Timestamp was not set");
        }
        public ActionResult GetSnapshotHistory()
        {
            // ReSharper disable once InvalidXmlDocComment

            /**
             * {
             *     timeline: [1, 2, 3 .. n],
             *     inventory: [{ id: 1, qty: [43, 21, 32 .. n ] }, { id: 2, qty: [43, 12, 43 .. n]}]
             * }
             */

            _logger.LogInformation("Getting snapshot history");

            try
            {
                var snapshotHistory = _inventoryService.GetSnapshotHistory();

                // Get distinct points in time a snapshot was collected
                var timelineMarkers = snapshotHistory
                                      .Select(t => t.SnapshotTime)
                                      .Distinct()
                                      .ToList();

                // Get quantities grouped by id.
                var snapshots = snapshotHistory
                                .GroupBy(hist => hist.Product, hist => hist.QuantityOnHand,
                                         (key, g) => new ProductInventorySnapshotModel
                {
                    ProductId      = key.Id,
                    QuantityOnHand = g.ToList()
                })
                                .OrderBy(hist => hist.ProductId)
                                .ToList();

                var viewModel = new SnapshotResponse
                {
                    Timeline = timelineMarkers,
                    ProductInventorySnapshots = snapshots
                };

                return(Ok(viewModel));
            }
            catch (Exception e)
            {
                _logger.LogError("Error getting snapshot history.");
                _logger.LogError(e.StackTrace);
                return(BadRequest("Error retrieving history"));
            }
        }
        public ActionResult GetSnapshotHistory()
        {
            /**
             * {
             *  timeline: [1,2,3,...n],
             *  inventory: [{id:1,qty:[43,21,32,...n]}, {id:2,qty:[12,24,45,...n]}]
             * }
             */

            _logger.LogInformation("Getting snapshot history");

            try
            {
                var snapshotHistory = _inventoryService.GetSnapshotHistory();

                // get distinct points in time a snapshot was collected
                var timelineMarkers = snapshotHistory
                                      .Select(hist => hist.SnapshotTime)
                                      .Distinct()
                                      .ToList();

                // get quantities grouped by id
                var snapshots = snapshotHistory
                                .GroupBy(
                    hist => hist.Product,
                    hist => hist.QuantityOnHand,
                    (key_product, grouping_qtyOnHand) => new ProductInventorySnapshotModel
                {
                    ProductId      = key_product.Id,
                    QuantityOnHand = grouping_qtyOnHand.ToList()
                })
                                .OrderBy(snap_hs => snap_hs.ProductId)
                                .ToList();

                var viewModel = new SnapshotResponse
                {
                    Timeline = timelineMarkers,
                    ProductInventorySnapshots = snapshots
                };

                return(Ok(viewModel));
            }
            catch (System.Exception ex)
            {
                _logger.LogError("Error getting snapshot history.");
                _logger.LogError(ex.StackTrace);
                return(BadRequest("Error retrieving snapshot history"));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Snapshot sends a snapshot of the entire backend from a member over a stream to a client.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="method"></param>
        /// <param name="token"></param>
        public async void Snapshot(SnapshotRequest request, Action <SnapshotResponse> method, CancellationToken token, Metadata headers = null)
        {
            using (AsyncServerStreamingCall <SnapshotResponse> snapshotter = _balancer.GetConnection().maintenanceClient.Snapshot(request, headers))
            {
                Task snapshotTask = Task.Run(async() =>
                {
                    while (await snapshotter.ResponseStream.MoveNext(token))
                    {
                        SnapshotResponse update = snapshotter.ResponseStream.Current;
                        method(update);
                    }
                });

                await snapshotTask;
            }
        }
 public virtual Task OnFailure(string snapshotName, SnapshotResponse response, TimeSpan duration)
 {
     _logger.LogErrorRequest(response, "Failed snapshot {SnapshotName} in {Repository} after {Duration:g}", snapshotName, Repository, duration);
     return(Task.CompletedTask);
 }