public ListChangedCommand(CollectionObserver collection, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
     {
         foreach (var item in e.NewItems)
         {
             snapshot = new Snapshot()
             {
                 Collection = collection,
                 NewState = DataState.Created,
                 NewValue = item,
                 Index = e.NewStartingIndex
             };
         }
     }
     else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
     {
         foreach (var item in e.OldItems)
         {
             snapshot = new Snapshot()
             {
                 Collection = collection,
                 NewState = DataState.Deleted,
                 OldValue = item,
                 Index = e.OldStartingIndex
             };
         }
     }
 }
 public void Save(Snapshot snapshot)
 {
     if(snapshot.Version == 0)
         FirstSaved = true;
     SavedVersion = snapshot.Version;
     _snapshot = snapshot;
 }
        public void ChainBuilderContinuesIfYouAskForAStoreOrSinkThatDoesntExist()
        {
            var snapshot = new Snapshot { new MetricData(0.5, DateTime.Parse("12 Aug 2008"), new List<string> { "value" }) };

            var configs = new List<ChainElement>
                {
                    new ChainElement("id", "storageChain", "testSourceId", "testBufferId", ""),
                };

            var source = MockRepository.GenerateMock<ISnapshotProvider>();
            source.Expect(s => s.Snapshot()).Return(snapshot).Repeat.Any();
            source.Expect(s => s.Name).Return("testSource").Repeat.Any();
            source.Expect(s => s.Id).Return("testSourceId").Repeat.Any();

            var sources = new HashSet<ISnapshotProvider> { source };

            var sourceChains = ChainBuilder.Build(sources, new HashSet<ISnapshotConsumer>(), new HashSet<IMultipleSnapshotConsumer>(), configs);

            Assert.AreEqual(0, sourceChains.Count());

            var buffer = MockRepository.GenerateMock<ISnapshotConsumer>();
            buffer.Expect(b => b.Update(snapshot));
            buffer.Expect(s => s.Name).Return("testBuffer").Repeat.Any();
            buffer.Expect(s => s.Id).Return("testBufferId").Repeat.Any();

            var sinks = new HashSet<ISnapshotConsumer> { buffer };

            var sinkChains = ChainBuilder.Build(new HashSet<ISnapshotProvider>(), sinks, new HashSet<IMultipleSnapshotConsumer>(), configs);

            Assert.AreEqual(0, sinkChains.Count());
        }
        public bool TryLoadFromSnapshot(Type aggregateRootType, Snapshot snapshot, CommittedEventStream committedEventStream, out Domain.AggregateRoot aggregateRoot)
        {
            aggregateRoot = null;

            if (snapshot == null) return false;

            if (AggregateSupportsSnapshot(aggregateRootType, snapshot.Payload.GetType()))
            {
                try
                {
                    Log.DebugFormat("Reconstructing aggregate root {0}[{1}] from snapshot", aggregateRootType.FullName,
                                    snapshot.EventSourceId.ToString("D"));
                    aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                    aggregateRoot.InitializeFromSnapshot(snapshot);
                    aggregateRoot.RestoreFromSnapshot(snapshot.Payload);

                    Log.DebugFormat("Applying remaining historic event to reconstructed aggregate root {0}[{1}]",
                        aggregateRootType.FullName, snapshot.EventSourceId.ToString("D"));
                    aggregateRoot.InitializeFromHistory(committedEventStream);
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat("Cannot load snapshot for '{0}' aggregate. {1}",
                        aggregateRoot.GetType().FullName, ex.Message);
                    aggregateRoot = null;
                    return false;
                }

                return true;
            }

            return false;
        }
 public CollectionChangedCommand(IStatefulCollection collection, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
     {
         foreach (StatefulObject obj in e.NewItems)
         {
             snapshot = new Snapshot()
             {
                 Collection = collection,
                 OldState = obj.DataState,
                 NewState = DataState.Created,
                 NewValue = obj
             };
         }
     }
     else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
     {
         foreach (StatefulObject obj in e.OldItems)
         {
             snapshot = new Snapshot()
             {
                 Collection = collection,
                 OldState = obj.DataState,
                 NewState = DataState.Deleted,
                 OldValue = obj
             };
         }
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static List<BusinessCriteriaDTO> GetBusinessCriteriaGradesModules(Snapshot snapshot, bool Round)
        {
            if (snapshot != null && snapshot.BusinessCriteriaResults != null)
            {
                List<BusinessCriteriaDTO> result = new List<BusinessCriteriaDTO>();

                var modules = snapshot.BusinessCriteriaResults.SelectMany(_ => _.ModulesResult).Select(_ => _.Module).Distinct();

                result = modules.Select(module => new BusinessCriteriaDTO
                                                {
                                                        Name = module.Name,

                                                        TQI = GetBusinessCriteriaModuleGrade(snapshot, module.Href, Constants.BusinessCriteria.TechnicalQualityIndex, Round),

                                                        Robustness = GetBusinessCriteriaModuleGrade(snapshot, module.Href, Constants.BusinessCriteria.Robustness, Round),

                                                        Performance = GetBusinessCriteriaModuleGrade(snapshot, module.Href, Constants.BusinessCriteria.Performance, Round),

                                                        Security = GetBusinessCriteriaModuleGrade(snapshot, module.Href, Constants.BusinessCriteria.Security, Round),

                                                        Changeability = GetBusinessCriteriaModuleGrade(snapshot, module.Href, Constants.BusinessCriteria.Changeability, Round),

                                                        Transferability = GetBusinessCriteriaModuleGrade(snapshot, module.Href, Constants.BusinessCriteria.Transferability, Round),
                                                                                    })
                                .ToList();

                return result;
            }
            return null;
        }
        // ChainWorkerBuilder -> ChainThreadBuilder -> ChainTaskBuilder -> SnapshotUpdaterBuilder
        // -> TimedSnapshotUpdaterBuilder -> SnapshotScheduleBuilder -> DelayedScheduleBuilder
        // -> ScheduleBuilder
        public void ScheduleBuilderCanBuildAScheduleForMultipleChains()
        {
            var scheduleName = "testSchedule";
            var delay = 10;

            var snapshot = new Snapshot { new MetricData(0.5, DateTime.Parse("12 Aug 2008"), new List<string>()) };

            var configs = new List<ChainElement>
                {
                    new ChainElement("id1", "firstTestChain", "testSourceId", "testBufferId", ""),
                    new ChainElement("id2", "secondTestChain", "testSourceId", "testBufferId", "")
                };                   

            var source = MockRepository.GenerateMock<ISnapshotProvider>();
            source.Expect(s => s.Snapshot()).Return(snapshot).Repeat.Any();
            source.Expect(s => s.Name).Return("testSource").Repeat.Any();
            source.Expect(s => s.Id).Return("testSourceId").Repeat.Any();

            var buffer = MockRepository.GenerateMock<ISnapshotConsumer>();
            buffer.Expect(b => b.Update(snapshot));
            buffer.Expect(s => s.Name).Return("testBuffer").Repeat.Any();
            buffer.Expect(s => s.Id).Return("testBufferId").Repeat.Any();

            var sources = new HashSet<ISnapshotProvider> { source };

            var sinks = new HashSet<ISnapshotConsumer> { buffer };

            var chains = ChainBuilder.Build(sources, sinks, new HashSet<IMultipleSnapshotConsumer>(), configs);

            var schedule = ScheduleBuilder.Build(scheduleName, delay, chains);

            Assert.IsInstanceOf<ISchedule>(schedule);
            Assert.AreEqual(scheduleName, schedule.Name);
            Assert.AreEqual(2, schedule.Chains.Count());
        }
Example #8
0
        public void ChainCanBeConfiguredWithMultipleSourcesAndASingleSink()
        {
            var firstSnapshot = new Snapshot { new MetricData(0.5, DateTime.Parse("12 Aug 2008"), new List<string> { "value" }) };
            var secondSnapshot = new Snapshot { new MetricData(0.5, DateTime.Parse("12 Aug 2008"), new List<string> { "value" }) };

            var name = "testChain";

            var firstSource = MockRepository.GenerateMock<ISnapshotProvider>();
            firstSource.Expect(s => s.Snapshot()).Return(firstSnapshot);

            var secondSource = MockRepository.GenerateMock<ISnapshotProvider>();
            secondSource.Expect(s => s.Snapshot()).Return(secondSnapshot);

            var sink = MockRepository.GenerateMock<IMultipleSnapshotConsumer>();
            sink.Expect(b => b.Update(null)).IgnoreArguments();

            var chain = new MultipleSourceChain("id", name, sink, firstSource, secondSource); 

            chain.Update();

            sink.VerifyAllExpectations();

            secondSource.VerifyAllExpectations();

            firstSource.VerifyAllExpectations();
        }   
        public void CanBeReset()
        {
            var firstSnapshot = new Snapshot { Name = "first" };
            firstSnapshot.Add(new MetricData(10, DateTime.Now.AddMinutes(-2), new List<string> { "value" }));
            firstSnapshot.Add(new MetricData(11, DateTime.Now.AddMinutes(-1.5), new List<string> { "value" }));
            firstSnapshot.Add(new MetricData(15, DateTime.Now.AddMinutes(-1), new List<string> { "value" }));

            var secondSnapshot = new Snapshot { Name = "second" };
            secondSnapshot.Add(new MetricData(10, DateTime.Now.AddMinutes(-2), new List<string> { "value2" }));
            secondSnapshot.Add(new MetricData(5, DateTime.Now.AddMinutes(-1.5), new List<string> { "value2" }));
            secondSnapshot.Add(new MetricData(6, DateTime.Now.AddMinutes(-1), new List<string> { "value2" }));

            var name = "testPlotter";

            var config = new PlotterElement("id", name, ".", 0, 15, 1, "");

            var sink = new MultiPlotter(config);

            sink.ResetWith(new [] { firstSnapshot, secondSnapshot });

            var plotFile = Path.Combine(".", Path.ChangeExtension(name, "png"));

            Assert.IsTrue(File.Exists(plotFile));

            File.Delete(plotFile);
        }
Example #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="snapshot"></param>
        /// <returns></returns>
        public static String GetSnapshotVersionNumber(Snapshot snapshot)
        {
            if (snapshot != null  && snapshot.Annotation != null && snapshot.Annotation.Version != null)
                return snapshot.Annotation.Version;

            return null;
        }
Example #11
0
        public void SetRight(Snapshot right)
        {
            Right = new Snapshot(right);

            Debug.Assert(Left != null);
            CalculateDiff();
        }
Example #12
0
        public void ChainCanBeConfiguredWithASingleSourceAndMultipleSinks()
        {
            var snapshot = new Snapshot { new MetricData(0.5, DateTime.Parse("12 Aug 2008"), new List<string>()) };

            var name = "testChain";

            var source = MockRepository.GenerateMock<ISnapshotProvider>();
            source.Expect(s => s.Snapshot()).Return(snapshot);

            var buffer = MockRepository.GenerateMock<ISnapshotConsumer>();
            buffer.Expect(b => b.Update(snapshot));

            var store = MockRepository.GenerateMock<ISnapshotConsumer>();
            store.Expect(s => s.Update(snapshot));

            var chain = new MultipleSinkChain("id", name, source, buffer, store);

            chain.Update();

            store.VerifyAllExpectations();

            buffer.VerifyAllExpectations();

            source.VerifyAllExpectations();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="snapshot"></param>
        /// <param name="CategorieIndex"></param>
        /// <param name="Metricindex"></param>
        /// <returns></returns>
        public static string GetCostComplexityName(Snapshot snapshot, int categorieId)
        {
            var result = snapshot.CostComplexityResults.Where(_ => _.Reference.Key == categorieId)
                                                       .FirstOrDefault();

            return (result != null && result.Reference!=null) ? result.Reference.Name : null;
        }
    static void Main(string[] args)
    {
      // Null-conditional operator.

      string name = null;
      var nameLength = name?.Length;
      List<string> names = null;
      nameLength = names?[0].Length;

      var notifier = new Notifier();
      notifier.ChangeState();
      notifier.StateChanged += (sender, e) => WriteLine("StateChanged notification received...");
      notifier.ChangeState();

      // await in catch/finally blocks.
      notifier.ChangeStateAsync().Wait();

      // Auto-property initializers + expression-bodied members + string interpolation.
      var snapshot = new Snapshot();
      WriteLine(snapshot);
      WriteLine($"{snapshot.UserName} created on {snapshot.Timestamp} with name length of {name?.Length ?? 0}");

      // nameof expressions.
      WriteLine(nameof(args));
      WriteLine(nameof(notifier));
      WriteLine(nameof(Main));
      WriteLine(nameof(Program));

      ReadLine();
    }
        public bool TryLoadFromSnapshot(Type aggregateRootType, Snapshot snapshot, CommittedEventStream committedEventStream, out AggregateRoot aggregateRoot)
        {
            aggregateRoot = null;

            if (snapshot == null) return false;

            if (AggregateSupportsSnapshot(aggregateRootType, snapshot.Payload.GetType()))
            {
                Log.DebugFormat("Reconstructing aggregate root {0}[{1}] from snapshot", aggregateRootType.FullName,
                                snapshot.EventSourceId.ToString("D"));
                aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                aggregateRoot.InitializeFromSnapshot(snapshot);

                var memType = aggregateRoot.GetType().GetSnapshotInterfaceType();
                var restoreMethod = memType.GetMethod("RestoreFromSnapshot");

                restoreMethod.Invoke(aggregateRoot, new[] { snapshot.Payload });

                Log.DebugFormat("Applying remaining historic event to reconstructed aggregate root {0}[{1}]",
                    aggregateRootType.FullName, snapshot.EventSourceId.ToString("D"));
                aggregateRoot.InitializeFromHistory(committedEventStream);

                return true;
            }

            return false;
        }
Example #16
0
    /// <summary>
    /// Adds the interactor to the given snapshot.
    /// </summary>
    /// <param name="snapshot">Interaction snapshot.</param>
    /// <param name="windowId">ID of the game window.</param>
    /// <param name="viewportPosition">Position of the game window in screen coordinates.</param>
    public void AddToSnapshot(Snapshot snapshot, string windowId, Vector2 viewportPosition, Vector2 viewportPixelsPerDesktopPixel)
    {
        using (var interactor = snapshot.CreateInteractor(_id, _parentId, windowId))
        {
            using (var bounds = interactor.CreateBounds(BoundsType.Rectangular))
            {
                // Location.rect is in GUI space.
                bounds.SetRectangularData(
                    viewportPosition.x + Location.rect.x / viewportPixelsPerDesktopPixel.x,
                    viewportPosition.y + Location.rect.y / viewportPixelsPerDesktopPixel.y,
                    Location.rect.width / viewportPixelsPerDesktopPixel.x,
                    Location.rect.height / viewportPixelsPerDesktopPixel.y);
            }

            interactor.Z = Location.relativeZ;

            if (Mask != null &&
                Mask.Type != EyeXMaskType.None)
            {
                var mask = interactor.CreateMask(MaskType.Default, Mask.Size, Mask.Size, Mask.MaskData);
                mask.Dispose();
            }

            foreach (var behavior in EyeXBehaviors)
            {
                behavior.AssignBehavior(interactor);
            }
        }
    }
Example #17
0
 public void stats_should_be_zero_for_empty_snapshot() {
   var snapshot = new Snapshot(new long[] {});
   Assert.That(snapshot.Min, Is.EqualTo(0));
   Assert.That(snapshot.Max, Is.EqualTo(0));
   Assert.That(snapshot.Mean, Is.EqualTo(0));
   Assert.That(snapshot.StdDev, Is.EqualTo(0));
 }
        public void SnapshotList()
        {
            Configure();
            var list = snapshotApi.FindAll(depth: 5);

            Assert.IsTrue(list.Items.Count > 0);
            snapshot = list.Items.FirstOrDefault();
        }
        public virtual bool AddSnapshot(Snapshot snapshot)
        {
            var result = this.persistence.AddSnapshot(snapshot);
            if (result)
                this.counters.CountSnapshot();

            return result;
        }
Example #20
0
        public void SendSnapshot(Snapshot snapshot, DateTime currentTime)
        {
            if (!NeedsSnapshot (currentTime))
                throw new Exception ("Sending more snapshots than the clients UpdateRate.");

            lastSendTime = currentTime;
            Connection.Send (new EntitySnapshotMessage (snapshot));
        }
        public Snapshot Snapshot()
        {
            Log.Debug("Querying " + Name);

            var snapshot = new Snapshot { Name = Name };
            snapshot.Add(new MetricData( _counter.NextValue(), DateTime.Now, new List<string> { Name }));

            return snapshot;
        }
Example #22
0
 public AggregateRoot Load(Type aggreateRootType, Snapshot snapshot, CommittedEventStream eventStream)
 {
     AggregateRoot aggregate;
     if (!_aggregateSnapshotter.TryLoadFromSnapshot(aggreateRootType, snapshot, eventStream, out aggregate))
     {
         aggregate = GetByIdFromScratch(aggreateRootType, eventStream);
     }
     return aggregate;
 }
 protected override object Snapshot_Create()
 {
     Snapshot ser = new Snapshot();
     ser.Id = Id;
     ser.Forname = Forname;
     ser.Surname = Surname;
     ser.Joined = Joined;
     return ser;
 }
        private dotMemoryUnit(bool collectAllocations, bool autoGetSnapshots)
        {
            if(!IsEnabled) return;

              this.autoGetSnapshots = autoGetSnapshots;
              dotMemoryApi.CollectAllocations = collectAllocations;
              if (autoGetSnapshots)
            firstSnapshot = dotMemoryApi.GetSnapshot();
        }
        protected override void GetParticlePositionAndOrientation(Snapshot snap, ref Vector2 position, ref Vector2 orientation)
        {
            SpraySnapshot spraySnap = (SpraySnapshot)snap;

            float angle = spraySnap.Direction + ((float)Rnd.NextDouble() * spraySnap.Spread) - (spraySnap.Spread / 2f);

            orientation.X = (float)Math.Sin(angle);
            orientation.Y = (float)Math.Cos(angle);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="snapshot"></param>
        /// <param name="onlyFailedChecks"></param>
        /// <returns></returns>
        public static Int32? GetNbRuleWithViolations(Snapshot snapshot,
                                                     Constants.RulesViolation rulesViolationType,
                                                     Constants.BusinessCriteria businessCriteriaId,
                                                     bool onlyFailedChecks)
        {
            var query = GetQueryRuleViolations(snapshot, rulesViolationType, businessCriteriaId, onlyFailedChecks);

            return (query != null) ? query.Select(_ => _.Reference.HRef).Distinct().Count() : (Int32?)null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="snapshot"></param>
        /// <param name="ruleExplorer"></param>
        /// <param name="businessCriteriasIds"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static List<RuleViolationResultDTO> GetNbViolationByRule(Snapshot snapshot, IRuleExplorer ruleExplorer, List<int> businessCriteriasIds, Int32 count)
        {
            if (snapshot == null || snapshot.TechnicalCriteriaResults == null) return null;

            //Get rules
            List<RuleDetails> rules = new List<RuleDetails>();
            foreach (var metricId in businessCriteriasIds)
            {
                var bcRules = ruleExplorer.GetRulesDetails(snapshot.DomainId, metricId.ToString(), snapshot.Id.ToString());

                rules.AddRange(bcRules);
            }

            rules = rules.GroupBy(_ => new { _.Key, _.Href, _.Name })
                         .Select(_ => new RuleDetails {
                                                         Key = _.Key.Key,
                                                         Href = _.Key.Href,
                                                         Name = _.Key.Name,
                                                         CompoundedWeight = _.Sum(x => x.CompoundedWeight),
                                                         Critical = _.Max(x => x.Critical)
                                                     })
                         .ToList();

            //Get result by technical criterias
            List<RuleViolationResultDTO> reslutByTechnicalCriterias = new List<RuleViolationResultDTO>();
            foreach (var rule in rules)
            {
                RuleViolationResultDTO ruleViolationResult = new RuleViolationResultDTO();

                var technicalCriterias = snapshot.TechnicalCriteriaResults
                                                 .Where(_ => _.RulesViolation!=null && _.RulesViolation.Where(p => p.Reference.Key.ToString() == rule.Key).Any())
                                                 .FirstOrDefault();

                if (technicalCriterias != null)
                {
                    ruleViolationResult.Rule = new RuleDetailsDTO { Name = rule.Name, Critical = rule.Critical, CompoundedWeight = rule.CompoundedWeight };

                    ruleViolationResult.Grade = technicalCriterias.DetailResult.Grade;

                    ruleViolationResult.TechnicalCriteraiName = technicalCriterias.Reference.Name;

                    var violationRatio = technicalCriterias.RulesViolation.Where(_ => _.Reference.Key.ToString() == rule.Key)
                                                                          .Select(_ => _.DetailResult.ViolationRatio)
                                                                          .FirstOrDefault();
                    if (violationRatio != null)
                    {
                        ruleViolationResult.TotalFailed = violationRatio.FailedChecks;
                        ruleViolationResult.TotalChecks = violationRatio.TotalChecks;
                    }

                    reslutByTechnicalCriterias.Add(ruleViolationResult);
                }
            }

            return reslutByTechnicalCriterias.OrderBy(_ => _.Rule.Name).Take(count).ToList();
        }
Example #28
0
        public IAggregateRoot RestoreFromSnapshot(Snapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException("snapshot"); ;
            }

            var aggregateRootType = _aggregateRootTypeCodeProvider.GetType<IAggregateRoot>(snapshot.AggregateRootTypeCode);
            return _binarySerializer.Deserialize(snapshot.Payload, aggregateRootType) as IAggregateRoot;
        }
        public void ResetWith(Snapshot snapshot)
        {
            var fileName = FileName(Name);

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            Update(snapshot);
        }
 public bool TryTakeSnapshot(AggregateRoot aggregateRoot, out Snapshot snapshot)
 {
     snapshot = null;
     MethodInfo createMethod = aggregateRoot.GetType().GetSnapshotCreateMethod();
     if (createMethod != null)
     {
         object payload = createMethod.Invoke(aggregateRoot, new object[0]);
         snapshot = new Snapshot(aggregateRoot.EventSourceId, aggregateRoot.Version, payload);
         return true;
     }
     return false;
 }
Example #31
0
 public IEnumerable <(ECPoint PublicKey, BigInteger Votes)> GetRegisteredValidators(Snapshot snapshot)
 {
     byte[] prefix_key = StorageKey.CreateSearchPrefix(Hash, new[] { Prefix_Validator });
     return(snapshot.Storages.Find(prefix_key).Select(p =>
                                                      (
                                                          p.Key.Key.Skip(1).ToArray().AsSerializable <ECPoint>(),
                                                          ValidatorState.FromByteArray(p.Value.Value).Votes
                                                      )));
 }
Example #32
0
 protected override Snapshot LerpSnapshots(Snapshot from, Snapshot to, float t)
 {
     return(Snapshot.Lerp(from, to, t));
 }
Example #33
0
 bool IInventory.Verify(Snapshot snapshot)
 {
     return(Verify(snapshot, Enumerable.Empty <Transaction>()));
 }
        private int ProcessSelections(bool modifySelections, bool clearSelections, ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            int result = VSConstants.S_OK;

            if (!Selector.Dte.UndoContext.IsOpen)
            {
                Selector.Dte.UndoContext.Open(Vsix.Name);
            }

            foreach (var selection in Selector.Selections)
            {
                if (selection.IsSelection())
                {
                    view.Selection.Select(
                        new SnapshotSpan(
                            selection.Start.GetPoint(Snapshot),
                            selection.End.GetPoint(Snapshot)
                            ),
                        Selector.IsReversing
                        );
                }

                view.Caret.MoveTo(selection.Caret.GetPoint(Snapshot));

                result = NextCommandTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

                selection.Caret = Snapshot.CreateTrackingPoint(
                    view.Caret.Position.BufferPosition.Position,
                    PointTrackingMode.Positive
                    );

                if (view.Selection.IsEmpty)
                {
                    selection.Start  = null;
                    selection.End    = null;
                    modifySelections = false;
                }

                if (modifySelections)
                {
                    var newSpan = view.Selection.StreamSelectionSpan;

                    selection.Start = Snapshot.CreateTrackingPoint(
                        newSpan.Start.Position.Position > newSpan.End.Position.Position ?
                        newSpan.End.Position.Position
                        : newSpan.Start.Position.Position,
                        PointTrackingMode.Positive
                        );

                    selection.End = Snapshot.CreateTrackingPoint(
                        newSpan.Start.Position.Position > newSpan.End.Position.Position ?
                        newSpan.Start.Position.Position
                        : newSpan.End.Position.Position,
                        PointTrackingMode.Positive
                        );

                    view.Selection.Clear();
                }
            }

            if (Selector.Dte.UndoContext.IsOpen)
            {
                Selector.Dte.UndoContext.Close();
            }

            // Set new searchtext needed if selection is modified
            if (modifySelections)
            {
                var startPosition = Selector.Selections.Last().Start.GetPosition(Snapshot);
                var endPosition   = Selector.Selections.Last().End.GetPosition(Snapshot);

                Selector.SearchText = Snapshot.GetText(
                    startPosition,
                    endPosition - startPosition
                    );
            }

            // Goes to caret-only mode
            if (clearSelections)
            {
                Selector.Selections.ForEach(s =>
                {
                    s.Start = null;
                    s.End   = null;
                }
                                            );
            }

            return(result);
        }
Example #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TrackingCallMergeStructureWorker"/> class.
        /// </summary>
        /// <param name="factories">The factories.</param>
        /// <param name="targetSnapshot">The target snapshot.</param>
        /// <param name="callSnapshot">The call snapshot.</param>
        /// <param name="sourceSnapshots">The source snapshots.</param>
        public TrackingCallMergeStructureWorker(ModularMemoryModelFactories factories, Snapshot targetSnapshot, Snapshot callSnapshot, List <Snapshot> sourceSnapshots)
            : base(factories, targetSnapshot, sourceSnapshots, true)
        {
            this.callSnapshot = callSnapshot;

            MemoryAliases = new Dictionary <MemoryIndex, MemoryAliasInfo>();
            Factories     = factories;
        }
        internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string snapshotName, Snapshot snapshot)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;

            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();

            uri.Reset(endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Compute/snapshots/", false);
            uri.AppendPath(snapshotName, true);
            uri.AppendQuery("api-version", "2019-11-01", true);
            request.Uri = uri;
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();

            content.JsonWriter.WriteObjectValue(snapshot);
            request.Content = content;
            return(message);
        }
Example #37
0
        /// <inheritdoc />
        public void CopyMemory(Snapshot snapshot, MemoryIndex sourceIndex, MemoryIndex targetIndex, bool isMust)
        {
            CopyWithinSnapshotWorker worker = new CopyWithinSnapshotWorker(snapshot, isMust);

            worker.Copy(sourceIndex, targetIndex);
        }
 public FileDuplicate(Tuple <string, HFile> tuple1, Tuple <string, HFile> tuple2, bool checkFilesExist, Snapshot snapshot1, Snapshot snapshot2)
 {
     this.tuple1          = tuple1 ?? throw new ArgumentNullException(nameof(tuple1));
     this.tuple2          = tuple2 ?? throw new ArgumentNullException(nameof(tuple2));
     this.checkFilesExist = checkFilesExist;
     this.snapshot1       = snapshot1 ?? throw new ArgumentNullException(nameof(snapshot1));
     this.snapshot2       = snapshot2 ?? throw new ArgumentNullException(nameof(snapshot2));
 }
Example #39
0
 /// <summary>
 /// 获取需要签名的交易的hash。包括交易输入的地址和申请人的公钥地址。
 /// </summary>
 /// <param name="snapshot">数据库快照</param>
 /// <returns>包括交易输入的地址和申请人的公钥地址。</returns>
 public override UInt160[] GetScriptHashesForVerifying(Snapshot snapshot)
 {
     return(base.GetScriptHashesForVerifying(snapshot).Union(new UInt160[] { ScriptHash }).OrderBy(p => p).ToArray());
 }
Example #40
0
 /// <summary>
 /// 校验该交易。已弃用该交易。拒绝新的交易。所以固定返回false
 /// </summary>
 /// <param name="snapshot">数据库快照</param>
 /// <param name="mempool">内存池交易</param>
 /// <returns>返回false,已弃用该交易。拒绝新的交易。</returns>
 public override bool Verify(Snapshot snapshot, IEnumerable <Transaction> mempool)
 {
     return(false);
 }
        protected async Task Snapshot_List_Execute(string diskCreateOption, string methodName, int?diskSizeGB = null)
        {
            EnsureClientsInitialized(DefaultLocation);

            // Data
            var  rgName1       = Recording.GenerateAssetName(TestPrefix);
            var  rgName2       = Recording.GenerateAssetName(TestPrefix);
            var  diskName1     = Recording.GenerateAssetName(DiskNamePrefix);
            var  diskName2     = Recording.GenerateAssetName(DiskNamePrefix);
            var  snapshotName1 = Recording.GenerateAssetName(DiskNamePrefix);
            var  snapshotName2 = Recording.GenerateAssetName(DiskNamePrefix);
            Disk disk1         = await GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB);

            Disk disk2 = await GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB);

            // **********
            // SETUP
            // **********
            // Create resource groups
            await ResourceGroupsOperations.CreateOrUpdateAsync(rgName1, new ResourceGroup(DiskRPLocation));

            await ResourceGroupsOperations.CreateOrUpdateAsync(rgName2, new ResourceGroup(DiskRPLocation));

            // Put 4 disks, 2 in each resource group
            Disk diskOut11 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName1, diskName1, disk1));

            Disk diskOut12 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName1, diskName2, disk2));

            Disk diskOut21 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName2, diskName1, disk1));

            Disk diskOut22 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName2, diskName2, disk2));

            // Generate 4 snapshots using disks info
            Snapshot snapshot11 = GenerateDefaultSnapshot(diskOut11.Id);
            Snapshot snapshot12 = GenerateDefaultSnapshot(diskOut12.Id, SnapshotStorageAccountTypes.StandardZRS.ToString());
            Snapshot snapshot21 = GenerateDefaultSnapshot(diskOut21.Id);
            Snapshot snapshot22 = GenerateDefaultSnapshot(diskOut22.Id);

            // Put 4 snapshots, 2 in each resource group
            await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName1, snapshotName1, snapshot11));
            await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName1, snapshotName2, snapshot12));
            await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName2, snapshotName1, snapshot21));
            await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName2, snapshotName2, snapshot22));

            // **********
            // TEST
            // **********
            // List snapshots under resource group
            //IPage<Snapshot> snapshotsOut = await SnapshotsClient.ListByResourceGroupAsync(rgName1);
            var snapshotsOut = await SnapshotsOperations.ListByResourceGroupAsync(rgName1).ToEnumerableAsync();

            Assert.AreEqual(2, snapshotsOut.Count());
            //Assert.Null(snapshotsOut.NextPageLink);

            snapshotsOut = await SnapshotsOperations.ListByResourceGroupAsync(rgName2).ToEnumerableAsync();

            Assert.AreEqual(2, snapshotsOut.Count());
            //Assert.Null(snapshotsOut.NextPageLink);

            // List snapshots under subscription
            snapshotsOut = await SnapshotsOperations.ListAsync().ToEnumerableAsync();

            Assert.True(snapshotsOut.Count() >= 4);
            //if (snapshotsOut.NextPageLink != null)
            //{
            //    snapshotsOut = await SnapshotsClient.ListNext(snapshotsOut.NextPageLink);
            //    Assert.True(snapshotsOut.Any());
            //}
        }
Example #42
0
 public void Reset(byte viewNumber)
 {
     if (viewNumber == 0)
     {
         Snapshot?.Dispose();
         Snapshot = Blockchain.Singleton.GetSnapshot();
         Block    = new Block
         {
             PrevHash      = Snapshot.CurrentBlockHash,
             Index         = Snapshot.Height + 1,
             NextConsensus = Blockchain.GetConsensusAddress(NativeContract.NEO.GetValidators(Snapshot))
         };
         var pv = Validators;
         Validators = NativeContract.NEO.GetNextBlockValidators(Snapshot);
         if (_witnessSize == 0 || (pv != null && pv.Length != Validators.Length))
         {
             // Compute the expected size of the witness
             using (ScriptBuilder sb = new ScriptBuilder())
             {
                 for (int x = 0; x < M; x++)
                 {
                     sb.EmitPush(new byte[64]);
                 }
                 _witnessSize = new Witness
                 {
                     InvocationScript   = sb.ToArray(),
                     VerificationScript = Contract.CreateMultiSigRedeemScript(M, Validators)
                 }.Size;
             }
         }
         MyIndex                = -1;
         ChangeViewPayloads     = new ConsensusPayload[Validators.Length];
         LastChangeViewPayloads = new ConsensusPayload[Validators.Length];
         CommitPayloads         = new ConsensusPayload[Validators.Length];
         if (LastSeenMessage == null)
         {
             LastSeenMessage = new int[Validators.Length];
             for (int i = 0; i < Validators.Length; i++)
             {
                 LastSeenMessage[i] = -1;
             }
         }
         keyPair = null;
         for (int i = 0; i < Validators.Length; i++)
         {
             WalletAccount account = wallet?.GetAccount(Validators[i]);
             if (account?.HasKey != true)
             {
                 continue;
             }
             MyIndex = i;
             keyPair = account.GetKey();
             break;
         }
     }
     else
     {
         for (int i = 0; i < LastChangeViewPayloads.Length; i++)
         {
             if (ChangeViewPayloads[i]?.GetDeserializedMessage <ChangeView>().NewViewNumber >= viewNumber)
             {
                 LastChangeViewPayloads[i] = ChangeViewPayloads[i];
             }
             else
             {
                 LastChangeViewPayloads[i] = null;
             }
         }
     }
     ViewNumber          = viewNumber;
     Block.ConsensusData = new ConsensusData
     {
         PrimaryIndex = GetPrimaryIndex(viewNumber)
     };
     Block.MerkleRoot    = null;
     Block.Timestamp     = 0;
     Block.Transactions  = null;
     TransactionHashes   = null;
     PreparationPayloads = new ConsensusPayload[Validators.Length];
     if (MyIndex >= 0)
     {
         LastSeenMessage[MyIndex] = (int)Block.Index;
     }
 }
Example #43
0
 public void Dispose()
 {
     Snapshot?.Dispose();
 }
Example #44
0
 /// <summary>ストリーム書き込み</summary>
 public abstract void Save(Stream stream, Snapshot snapshot);
        public async Task <Response> CreateOrUpdateAsync(string resourceGroupName, string snapshotName, Snapshot snapshot, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (snapshotName == null)
            {
                throw new ArgumentNullException(nameof(snapshotName));
            }
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            using var message = CreateCreateOrUpdateRequest(resourceGroupName, snapshotName, snapshot);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            case 202:
                return(message.Response);

            default:
                throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }
Example #46
0
 /// <summary>ファイル書き込み</summary>
 public void Save(string filepath, Snapshot snapshot)
 {
     using (FileStream stream = new FileStream(filepath, FileMode.Create)) {
         Save(stream, snapshot);
     }
 }
        protected async Task Snapshot_CRUD_Execute(string diskCreateOption, string methodName, int?diskSizeGB = null, string location = null, bool incremental = false)
        {
            EnsureClientsInitialized(DefaultLocation);
            DiskRPLocation = location ?? DiskRPLocation;

            // Data
            var  rgName       = Recording.GenerateAssetName(TestPrefix);
            var  diskName     = Recording.GenerateAssetName(DiskNamePrefix);
            var  snapshotName = Recording.GenerateAssetName(DiskNamePrefix);
            Disk sourceDisk   = await GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB);

            // **********
            // SETUP
            // **********
            // Create resource group
            await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(DiskRPLocation));

            // Put disk
            Disk diskOut = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName, diskName, sourceDisk));

            Validate(sourceDisk, diskOut, DiskRPLocation);

            // Generate snapshot using disk info
            Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id, incremental: incremental);

            // **********
            // TEST
            // **********
            // Put
            Snapshot snapshotOut = await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName, snapshotName, snapshot));

            Validate(snapshot, snapshotOut, incremental: incremental);

            // Get
            snapshotOut = (await SnapshotsOperations.GetAsync(rgName, snapshotName)).Value;
            Validate(snapshot, snapshotOut, incremental: incremental);

            // Get access
            AccessUri accessUri = await WaitForCompletionAsync((await SnapshotsOperations.StartGrantAccessAsync(rgName, snapshotName, new GrantAccessData(AccessDataDefault.Access, AccessDataDefault.DurationInSeconds))));

            Assert.NotNull(accessUri.AccessSAS);

            // Get
            snapshotOut = (await SnapshotsOperations.GetAsync(rgName, snapshotName)).Value;
            Validate(snapshot, snapshotOut, incremental: incremental);

            const string tagKey = "tageKey";
            // Patch
            var updatesnapshot = new SnapshotUpdate()
            {
                Tags = { { tagKey, "tagvalue" } }
            };

            snapshotOut = await WaitForCompletionAsync(await SnapshotsOperations.StartUpdateAsync(rgName, snapshotName, updatesnapshot));

            Validate(snapshot, snapshotOut, incremental: incremental);

            // Get
            snapshotOut = (await SnapshotsOperations.GetAsync(rgName, snapshotName)).Value;
            Validate(snapshot, snapshotOut, incremental: incremental);

            // End access
            await WaitForCompletionAsync(await SnapshotsOperations.StartRevokeAccessAsync(rgName, snapshotName));

            // Delete
            await WaitForCompletionAsync(await SnapshotsOperations.StartDeleteAsync(rgName, snapshotName));

            try
            {
                // Ensure it was really deleted
                await SnapshotsOperations.GetAsync(rgName, snapshotName);

                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.NotNull(ex);
                //Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
            }
        }
Example #48
0
        private static string UploadSnapshot(SnapshotServiceClient client, string snapshotPath, string projectName,
                                             string deploymentName, bool useChinaPlatform)
        {
            Console.WriteLine($"Uploading {snapshotPath} to project {projectName}");

            // Read snapshot.
            var bytes = File.ReadAllBytes(snapshotPath);

            if (bytes.Length == 0)
            {
                Console.Error.WriteLine($"Unable to load {snapshotPath}. Does the file exist?");
                return(string.Empty);
            }

            // Create HTTP endpoint to upload to.
            var snapshotToUpload = new Snapshot
            {
                ProjectName    = projectName,
                DeploymentName = deploymentName
            };

            using (var md5 = MD5.Create())
            {
                snapshotToUpload.Checksum = Convert.ToBase64String(md5.ComputeHash(bytes));
                snapshotToUpload.Size     = bytes.Length;
            }

            var uploadSnapshotResponse =
                client.UploadSnapshot(new UploadSnapshotRequest {
                Snapshot = snapshotToUpload
            });

            snapshotToUpload = uploadSnapshotResponse.Snapshot;

            // Upload content.
            var httpRequest = WebRequest.Create(uploadSnapshotResponse.UploadUrl) as HttpWebRequest;

            httpRequest.Method        = "PUT";
            httpRequest.ContentLength = snapshotToUpload.Size;
            httpRequest.Headers.Add("Content-MD5", snapshotToUpload.Checksum);

            if (useChinaPlatform)
            {
                httpRequest.Headers.Add("x-amz-server-side-encryption", "AES256");
            }

            using (var dataStream = httpRequest.GetRequestStream())
            {
                dataStream.Write(bytes, 0, bytes.Length);
            }

            // Block until we have a response.
            httpRequest.GetResponse();

            // Confirm that the snapshot was uploaded successfully.
            var confirmUploadResponse = client.ConfirmUpload(new ConfirmUploadRequest
            {
                DeploymentName = snapshotToUpload.DeploymentName,
                Id             = snapshotToUpload.Id,
                ProjectName    = snapshotToUpload.ProjectName
            });

            return(confirmUploadResponse.Snapshot.Id);
        }
 internal void UpdateSnapshot() => _currentSnapshot = new Snapshot(_provider, Properties, FilePath);
 private void OnSnapshotToggleChanged(Snapshot snapshot, bool isOn)
 {
     snapshot.mapLayer.Show(isOn);
 }
Example #51
0
        private int ReverifyTransactions(SortedSet <PoolItem> verifiedSortedTxPool,
                                         SortedSet <PoolItem> unverifiedSortedTxPool, int count, double millisecondsTimeout, Snapshot snapshot)
        {
            DateTime        reverifyCutOffTimeStamp = DateTime.UtcNow.AddMilliseconds(millisecondsTimeout);
            List <PoolItem> reverifiedItems         = new List <PoolItem>(count);
            List <PoolItem> invalidItems            = new List <PoolItem>();

            // Since unverifiedSortedTxPool is ordered in an ascending manner, we take from the end.
            foreach (PoolItem item in unverifiedSortedTxPool.Reverse().Take(count))
            {
                if (item.Tx.Reverify(snapshot, _unsortedTransactions.Select(p => p.Value.Tx)))
                {
                    reverifiedItems.Add(item);
                }
                else // Transaction no longer valid -- it will be removed from unverifiedTxPool.
                {
                    invalidItems.Add(item);
                }

                if (DateTime.UtcNow > reverifyCutOffTimeStamp)
                {
                    break;
                }
            }

            _txRwLock.EnterWriteLock();
            try
            {
                int blocksTillRebroadcast = Object.ReferenceEquals(unverifiedSortedTxPool, _sortedTransactions)
                    ? BlocksTillRebroadcastHighPriorityPoolTx : BlocksTillRebroadcastLowPriorityPoolTx;

                if (Count > RebroadcastMultiplierThreshold)
                {
                    blocksTillRebroadcast = blocksTillRebroadcast * Count / RebroadcastMultiplierThreshold;
                }

                var rebroadcastCutOffTime = DateTime.UtcNow.AddMilliseconds(
                    -Blockchain.MillisecondsPerBlock * blocksTillRebroadcast);
                foreach (PoolItem item in reverifiedItems)
                {
                    if (_unsortedTransactions.TryAdd(item.Tx.Hash, item))
                    {
                        verifiedSortedTxPool.Add(item);

                        if (item.LastBroadcastTimestamp < rebroadcastCutOffTime)
                        {
                            _system.LocalNode.Tell(new LocalNode.RelayDirectly {
                                Inventory = item.Tx
                            }, _system.Blockchain);
                            item.LastBroadcastTimestamp = DateTime.UtcNow;
                        }
                    }

                    _unverifiedTransactions.Remove(item.Tx.Hash);
                    unverifiedSortedTxPool.Remove(item);
                }

                foreach (PoolItem item in invalidItems)
                {
                    _unverifiedTransactions.Remove(item.Tx.Hash);
                    unverifiedSortedTxPool.Remove(item);
                }
            }
            finally
            {
                _txRwLock.ExitWriteLock();
            }

            var invalidTransactions = invalidItems.Select(p => p.Tx).ToArray();

            foreach (IMemoryPoolTxObserverPlugin plugin in Plugin.TxObserverPlugins)
            {
                plugin.TransactionsRemoved(MemoryPoolTxRemovalReason.NoLongerValid, invalidTransactions);
            }

            return(reverifiedItems.Count);
        }
    private void CreateSnapshot(int i, GridData gridData = null)
    {
        var id            = i + 1;
        var snapshotLabel = Translator.Get("Snapshot") + "\n" + id;
        var snapshotName  = Regex.Replace(snapshotLabel, @"\n|\r", "");

        // Create Snapshot
        var snapshot = new Snapshot
        {
            id   = "S" + i,
            name = snapshotName
        };

        snapshot.uiTransform      = Instantiate(snapshotPrefab, SnapshotList, false);
        snapshot.uiTransform.name = snapshotName;
        snapshot.uiTransform.SetSiblingIndex(i);

        // Setup toggle button
        var toggleButton = snapshot.uiTransform.GetComponentInChildren <Toggle>();

        toggleButton.onValueChanged.AddListener((isOn) => OnSnapshotToggleChanged(snapshot, isOn));

        // Setup delete button
        var deleteButton = snapshot.uiTransform.GetComponentInChildren <Button>();

        deleteButton.gameObject.SetActive(false);
        deleteButton.onClick.AddListener(() => OnRemoveSnapshot(snapshot));

        // Setup label
        snapshot.uiTransform.GetComponentInChildren <Text>().text = id.ToString();

        // Setup intput text
        var input = snapshot.uiTransform.GetComponentInChildren <InputField>();

        input.text = snapshotLabel;
        input.onEndEdit.AddListener((value) => OnEndEdit(value, input, snapshot));

        // Create snapshot's map layer
        snapshot.mapLayer = toolLayers.CreateGridMapLayer(snapshotLayerPrefab, $"ContoursSnapshot_{snapshot.id}", gridData);

        // Set Snapshot color
        SetColorsToSnapshot(snapshot.mapLayer, toggleButton, deleteButton);

        // Update output and legend panel
        string titleLabel    = $"{LocalizationManager.Instance.Get("Snapshot")} {i + 1}";
        Color  snapshotColor = toggleButton.image.color;
        string snapshotID    = snapshot.id;

        InfoPanel.AddEntry(snapshotID, titleLabel, true);
        LegendPanl.AddSnapshotItem(snapshotID, snapshotColor, titleLabel);

        if (gridData != null)
        {
            var sqm = ContourUtils.GetContoursSquareMeters(gridData);
            InfoPanel.UpdateEntry(snapshotID, sqm);
        }
        InfoPanel.SetSnapshotProperties(snapshotID, i + 1, toggleButton.image.color);

        snapshots[i] = snapshot;
        editColourPanel.AddSnapshotColour(i, toggleButton.image.color);
        usedSnapshots++;
        editToggle.gameObject.SetActive(usedSnapshots >= 1);

        runningSnapshotCounter++;

        InfoPanel.UpdateRelativeToSnapshotDropdown();

        GuiUtils.RebuildLayout(SnapshotList);
    }
Example #53
0
 public override BigInteger TotalSupply(Snapshot snapshot)
 {
     return(TotalAmount);
 }
Example #54
0
 public override void ApplyEvent(Envelope <IEvent> @event)
 {
     ApplySnapshot(Snapshot.Apply(@event));
 }
Example #55
0
 protected internal override void SetPosition(Snapshot snapshot, int position)
 {
     this.position = position;
 }
Example #56
0
 /// <summary>
 /// 初始化状态,必须实现
 /// </summary>
 /// <returns></returns>
 protected virtual ValueTask CreateState()
 {
     Snapshot = new Snapshot <PrimaryKey, State>(GrainId);
     return(Consts.ValueTaskDone);
 }
Example #57
0
 public static PrePaidAccount Restore(Snapshot snapshot) => new PrePaidAccount(
     PrePaidAccountId.Of(snapshot.Id),
     snapshot.AmountAvailable,
     snapshot.DebtLimit,
     snapshot.Debt);
Example #58
0
 /// <summary>
 /// Verifies the specified Snapshot instance against the current settings of the SnapshotVerifier instance.
 /// </summary>
 /// <param name="image">The image to be verified.</param>
 /// <returns>The verification result based on the supplied image and the current settings of the SnapshotVerifier instance.</returns>
 public abstract VerificationResult Verify(Snapshot image);
Example #59
0
 public override void CustomApply(Snapshot <TPrimaryKey, TSnapshot> snapshot, FullyEvent <TPrimaryKey> fullyEvent)
 {
     Apply(snapshot.State, fullyEvent.Event);
 }
        protected Snapshot GenerateDefaultSnapshot(string sourceDiskId, string snapshotStorageAccountTypes = "Standard_LRS", bool incremental = false)
        {
            Snapshot snapshot = GenerateBaseSnapshot(sourceDiskId, snapshotStorageAccountTypes, incremental);

            return(snapshot);
        }