public void Set_All_Fast_Sorted_Ensure_LastChildContentId()
    {
        // see https://github.com/umbraco/Umbraco-CMS/issues/6353
        IEnumerable <ContentNodeKit> GetKits()
        {
            var paths = new Dictionary <int, string> {
                { -1, "-1" }
            };

            yield return(CreateInvariantKit(1, -1, 1, paths));

            yield return(CreateInvariantKit(2, 1, 1, paths));
        }

        InitializedCache(GetKits(), _contentTypes);

        var snapshotService = (PublishedSnapshotService)SnapshotService;
        var contentStore    = snapshotService.GetContentStore();

        var parentNodes = contentStore.Test.GetValues(1);
        var parentNode  = parentNodes[0];

        AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 2);

        SnapshotService.Notify(new[] { new ContentCacheRefresher.JsonPayload(2, Guid.Empty, TreeChangeTypes.Remove) }, out _, out _);

        parentNodes = contentStore.Test.GetValues(1);
        parentNode  = parentNodes[0];

        AssertLinkedNode(parentNode.contentNode, -1, -1, -1, -1, -1);
    }
示例#2
0
        public DatabaseFixture()
        {
            Secret       = "KeGPyghP5CSoSwPpzkBvKG2k";
            InstanceName = "Hawkeye";

            DbContextOptions <ExilenceContext> options;
            var builder = new DbContextOptionsBuilder <ExilenceContext>();

            builder.UseInMemoryDatabase("Exilence");
            options = builder.Options;

            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AccountProfileMapper());
                cfg.AddProfile(new CharacterProfileMapper());
                cfg.AddProfile(new ConnectionProfileMapper());
                cfg.AddProfile(new GroupProfileMapper());
                cfg.AddProfile(new LeagueProfileMapper());
                cfg.AddProfile(new PricedItemProfileMapper());
                cfg.AddProfile(new SnapshotProfileMapper());
                cfg.AddProfile(new SnapshotProfileProfileMapper());
                cfg.AddProfile(new StashtabProfileMapper());
            });
            var mapper = mockMapper.CreateMapper();

            var context = new ExilenceContext(options);

            var accountRepository  = new AccountRepository(context);
            var snapshotRepository = new SnapshotRepository(context);
            var groupRepository    = new GroupRepository(context);

            AccountService  = new AccountService(snapshotRepository, accountRepository, mapper);
            SnapshotService = new SnapshotService(snapshotRepository, accountRepository, mapper);
            GroupService    = new GroupService(groupRepository, accountRepository, mapper);
        }
    public void MoveFromRootTest()
    {
        InitializedCache(GetInvariantKits(), _contentTypes);

        // get snapshot
        var snapshot = GetPublishedSnapshot();

        // do some changes
        var kit = NuCacheContentService.ContentKits[1];

        NuCacheContentService.ContentKits[1] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            "-1,3,10,1",
            1,
            1,
            10,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        // notify
        SnapshotService.Notify(
            new[] { new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.RefreshBranch) }, out _, out _);

        // changes that *I* make are immediately visible on the current snapshot
        var documents = snapshot.Content.GetAtRoot().ToArray();

        AssertDocuments(documents, "N2", "N3");

        documents = snapshot.Content.GetById(10).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N1");

        Assert.AreEqual(10, snapshot.Content.GetById(1).Parent?.Id);
    }
示例#4
0
 public static async Task Main()
 {
     BuildConfigRoot();
     BuildServiceProvider();
     snapshotService = serviceProvider.GetService <SnapshotService>();
     logger          = serviceProvider.GetService <Logger>();
     await TryCaptureSnapshots();
 }
示例#5
0
 /// <summary>
 /// Creates internal services.
 /// </summary>
 private void createServices()
 {
     LoadService                = new LoadService(this);
     ProtocolService            = new ProtocolService(this, LoadService);
     MessagingService           = new MessagingService(this);
     ProtocolReplicationService = new ProtocolReplicationService(this);
     SnapshotService            = new SnapshotService(this);
     PackService                = new PackService(this);
 }
    public void Refresh_Node_Ensures_Linked_list()
    {
        // NOTE: these tests are not using real scopes, in which case a Scope does not control
        // how the snapshots generations work. We are forcing new snapshot generations manually.
        IEnumerable <ContentNodeKit> GetKits()
        {
            var paths = new Dictionary <int, string> {
                { -1, "-1" }
            };

            // root
            yield return(CreateInvariantKit(100, -1, 1, paths));

            // site
            yield return(CreateInvariantKit(2, 100, 1, paths));

            yield return(CreateInvariantKit(1, 100, 2, paths)); // middle child

            yield return(CreateInvariantKit(3, 100, 3, paths));

            // children of 1
            yield return(CreateInvariantKit(20, 1, 1, paths));

            yield return(CreateInvariantKit(30, 1, 2, paths));

            yield return(CreateInvariantKit(40, 1, 3, paths));
        }

        InitializedCache(GetKits(), _contentTypes);

        var snapshotService = (PublishedSnapshotService)SnapshotService;
        var contentStore    = snapshotService.GetContentStore();

        Assert.AreEqual(1, contentStore.Test.LiveGen);
        Assert.IsTrue(contentStore.Test.NextGen);

        var middleNode = contentStore.Test.GetValues(1)[0];

        Assert.AreEqual(1, middleNode.gen);
        AssertLinkedNode(middleNode.contentNode, 100, 2, 3, 20, 40);

        // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify)
        contentStore.CreateSnapshot();

        Assert.IsFalse(contentStore.Test.NextGen);

        SnapshotService.Notify(
            new[] { new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.RefreshNode) }, out _, out _);

        Assert.AreEqual(2, contentStore.Test.LiveGen);
        Assert.IsTrue(contentStore.Test.NextGen);

        middleNode = contentStore.Test.GetValues(1)[0];
        Assert.AreEqual(2, middleNode.gen);
        AssertLinkedNode(middleNode.contentNode, 100, 2, 3, 20, 40);
    }
    public void ReOrderTest()
    {
        InitializedCache(GetInvariantKits(), _contentTypes);

        // get snapshot
        var snapshot = GetPublishedSnapshot();

        // do some changes
        var kit = NuCacheContentService.ContentKits[7];

        NuCacheContentService.ContentKits[7] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            kit.Node.Path,
            1,
            kit.Node.Level,
            kit.Node.ParentContentId,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        kit = NuCacheContentService.ContentKits[8];
        NuCacheContentService.ContentKits[8] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            kit.Node.Path,
            3,
            kit.Node.Level,
            kit.Node.ParentContentId,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        kit = NuCacheContentService.ContentKits[9];
        NuCacheContentService.ContentKits[9] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            kit.Node.Path,
            2,
            kit.Node.Level,
            kit.Node.ParentContentId,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        // notify
        SnapshotService.Notify(
            new[]
        {
            new ContentCacheRefresher.JsonPayload(kit.Node.ParentContentId, Guid.Empty, TreeChangeTypes.RefreshBranch),
        },
            out _,
            out _);

        // changes that *I* make are immediately visible on the current snapshot
        var documents = snapshot.Content.GetById(kit.Node.ParentContentId).Children(VariationContextAccessor).ToArray();

        AssertDocuments(documents, "N7", "N9", "N8");
    }
示例#8
0
 public static async Task Main()
 {
     BuildConfigRoot();
     BuildServiceProvider();
     snapshotService = serviceProvider.GetService <SnapshotService>();
     using (logger = new Logger(configRoot[AppInsightsKeyConfig]))
     {
         await CaptureSnapshots(BatchSize);
     }
 }
    public void RemoveTest()
    {
        InitializedCache(GetInvariantKits(), _contentTypes);

        // get snapshot
        var snapshot = GetPublishedSnapshot();

        var documents = snapshot.Content.GetAtRoot().ToArray();

        AssertDocuments(documents, "N1", "N2", "N3");

        documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N4", "N5", "N6");

        documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N9", "N8", "N7");

        // notify
        SnapshotService.Notify(
            new[]
        {
            new ContentCacheRefresher.JsonPayload(3, Guid.Empty, TreeChangeTypes.Remove), // remove last
            new ContentCacheRefresher.JsonPayload(5, Guid.Empty, TreeChangeTypes.Remove), // remove middle
            new ContentCacheRefresher.JsonPayload(9, Guid.Empty, TreeChangeTypes.Remove), // remove first
        },
            out _,
            out _);

        documents = snapshot.Content.GetAtRoot().ToArray();
        AssertDocuments(documents, "N1", "N2");

        documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N4", "N6");

        documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N8", "N7");

        // notify
        SnapshotService.Notify(
            new[]
        {
            new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.Remove), // remove first
            new ContentCacheRefresher.JsonPayload(8, Guid.Empty, TreeChangeTypes.Remove), // remove
            new ContentCacheRefresher.JsonPayload(7, Guid.Empty, TreeChangeTypes.Remove), // remove
        },
            out _,
            out _);

        documents = snapshot.Content.GetAtRoot().ToArray();
        AssertDocuments(documents, "N2");

        documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents);
    }
    public void UpdateTest()
    {
        InitializedCache(GetInvariantKits(), _contentTypes);

        // get snapshot
        var snapshot = GetPublishedSnapshot();

        var snapshotService = (PublishedSnapshotService)SnapshotService;
        var contentStore    = snapshotService.GetContentStore();

        var parentNodes = contentStore.Test.GetValues(1);
        var parentNode  = parentNodes[0];

        AssertLinkedNode(parentNode.contentNode, -1, -1, 2, 4, 6);
        Assert.AreEqual(1, parentNode.gen);

        var documents = snapshot.Content.GetAtRoot().ToArray();

        AssertDocuments(documents, "N1", "N2", "N3");

        documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N4", "N5", "N6");

        documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N9", "N8", "N7");

        // notify
        SnapshotService.Notify(
            new[]
        {
            new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.RefreshBranch),
            new ContentCacheRefresher.JsonPayload(2, Guid.Empty, TreeChangeTypes.RefreshNode),
        },
            out _,
            out _);

        parentNodes = contentStore.Test.GetValues(1);
        Assert.AreEqual(2, parentNodes.Length);
        parentNode = parentNodes[1];                               // get the first gen
        AssertLinkedNode(parentNode.contentNode, -1, -1, 2, 4, 6); // the structure should have remained the same
        Assert.AreEqual(1, parentNode.gen);
        parentNode = parentNodes[0];                               // get the latest gen
        AssertLinkedNode(parentNode.contentNode, -1, -1, 2, 4, 6); // the structure should have remained the same
        Assert.AreEqual(2, parentNode.gen);

        documents = snapshot.Content.GetAtRoot().ToArray();
        AssertDocuments(documents, "N1", "N2", "N3");

        documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N4", "N5", "N6");

        documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N9", "N8", "N7");
    }
        public void ShouldGetAllSnapshots()
        {
            var snapshots = GetTestSnapshots();
            var snapshotRepository = new Mock<ISnapshotRepository>();
            snapshotRepository.Setup(rep => rep.GetSnapshots()).Returns(snapshots);

            var service = new SnapshotService(snapshotRepository.Object);
            var returnedSnapshots = service.GetSnapshots();

            Assert.AreEqual(2, returnedSnapshots.Count, "There should be 2 snapshots.");
            Assert.AreEqual(1, returnedSnapshots.Count(shot => shot.Name == "first"), "There should be a snapshot called first");
            Assert.AreEqual(1, returnedSnapshots.Count(shot => shot.Name == "second"), "There should be a snapshot called second");
        }
    public void Clear_Branch_Locked()
    {
        // This test replicates an issue we saw here https://github.com/umbraco/Umbraco-CMS/pull/7907#issuecomment-610259393
        // The data was sent to me and this replicates it's structure
        var paths = new Dictionary <int, string> {
            { -1, "-1" }
        };

        InitializedCache(
            new List <ContentNodeKit>
        {
            CreateInvariantKit(1, -1, 1, paths), // first level
            CreateInvariantKit(2, 1, 1, paths),  // second level
            CreateInvariantKit(3, 2, 1, paths),  // third level

            CreateInvariantKit(4, 3, 1, paths),  // fourth level (we'll copy this one to the same level)

            CreateInvariantKit(5, 4, 1, paths),  // 6th level

            CreateInvariantKit(6, 5, 2, paths),  // 7th level
            CreateInvariantKit(7, 5, 3, paths),
            CreateInvariantKit(8, 5, 4, paths),
            CreateInvariantKit(9, 5, 5, paths),
            CreateInvariantKit(10, 5, 6, paths),
        },
            _contentTypes);

        // get snapshot
        var snapshot = GetPublishedSnapshot();

        var snapshotService = (PublishedSnapshotService)SnapshotService;
        var contentStore    = snapshotService.GetContentStore();

        // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify)
        contentStore.CreateSnapshot();

        // notify - which ensures there are 2 generations in the cache meaning each LinkedNode has a Next value.
        SnapshotService.Notify(
            new[] { new ContentCacheRefresher.JsonPayload(4, Guid.Empty, TreeChangeTypes.RefreshBranch) }, out _, out _);

        // refresh the branch again, this used to show the issue where a null ref exception would occur
        // because in the ClearBranchLocked logic, when SetValueLocked was called within a recursive call
        // to a child, we null out the .Value of the LinkedNode within the while loop because we didn't capture
        // this value before recursing.
        Assert.DoesNotThrow(() =>
                            SnapshotService.Notify(
                                new[] { new ContentCacheRefresher.JsonPayload(4, Guid.Empty, TreeChangeTypes.RefreshBranch) }, out _, out _));
    }
示例#13
0
        public static async Task Main(string[] args)
        {
            var mapDAO      = new MapDAO(Constants.MapSQLConnection);
            var logDAO      = new LogDAO(Constants.NOSQLConnection);
            var userDAO     = new UserDAO(Constants.SQLConnection);
            var uploadDAO   = new UploadDAO(Constants.SQLConnection);
            var snapshotDAO = new SnapshotDAO(Constants.NOSQLConnection);

            var maskService      = new MaskingService(mapDAO);
            var ffLoggingService = new FlatFileLoggingService(maskService);

            var dsLoggingService = new DataStoreLoggingService(logDAO, maskService);
            var snapshotService  = new SnapshotService(logDAO, userDAO, uploadDAO, snapshotDAO);

            var loggingManager    = new LoggingManager(ffLoggingService, dsLoggingService);
            var createSnapManager = new CreateSnapshotManager(loggingManager, snapshotService);

            // Script called at the beginning of every month.
            // Get the year and month according the Utc time.
            var year  = DateTime.UtcNow.Year;
            var month = DateTime.UtcNow.Month;

            // We want to create a snapshot of the previous month so we have to subtract 1 to the month if it is not 1 (January).
            // If it is 1, then change month to 12, and subtract 1 from year instead.
            if (month == 1)
            {
                year  = year - 1;
                month = 12;
            }
            else
            {
                month = month - 1;
            }

            var tries = 0;
            var createSnapshotSuccess = false;

            // If the createsnapshot was a failure, there are 3 extra tries. It can stop if it was successful though.
            while (!createSnapshotSuccess && tries < 4)
            {
                createSnapshotSuccess = await createSnapManager.CreateSnapshotAsync(tries, year, month).ConfigureAwait(false);

                if (!createSnapshotSuccess)
                {
                    tries++;
                }
            }
        }
        public void ShouldDeleteSnapshots()
        {
            var snapshots = GetTestSnapshots();
            var initialSnapshotsCount = snapshots.Count;
            var snapshotRepository = new Mock<ISnapshotRepository>();
            snapshotRepository.Setup(rep => rep.GetSnapshots()).Returns(snapshots);
            snapshotRepository.Setup(rep => rep.Delete(It.IsAny<string>()))
                .Callback((string name) => snapshots.Remove(snapshots.First(shot => shot.Name == name)));

            var service = new SnapshotService(snapshotRepository.Object);
            var nameToDelete = "second";
            service.DeleteSnapshot(snapshots.First(shot => shot.Name == nameToDelete));

            Assert.AreEqual(initialSnapshotsCount - 1, snapshots.Count, "There should be one less snapshot after deletion.");
            Assert.AreEqual(0, service.GetSnapshots().Count(shot => shot.Name == nameToDelete),
                string.Format("The snapshot named {0} should have been deleted", nameToDelete));
        }
示例#15
0
 public void Setup()
 {
     _ms                = new MemoryStream();
     _memoryDb          = new LiteDatabase(_ms);
     _userCollection    = _memoryDb.GetCollection <MiningMonitorUser>();
     _userStoreLogger   = new Mock <ILogger <MiningMonitorUserStore> >();
     _userStore         = new MiningMonitorUserStore(new LiteDbRepository <MiningMonitorUser, Guid>(_userCollection), _userStoreLogger.Object);
     _optionsAccessor   = new Mock <IOptions <IdentityOptions> >();
     _passwordHasher    = new Mock <IPasswordHasher <MiningMonitorUser> >();
     _normalizer        = new Mock <ILookupNormalizer>();
     _serviceProvider   = new Mock <IServiceProvider>();
     _userManagerLogger = new Mock <ILogger <UserManager <MiningMonitorUser> > >();
     _userManager       = new UserManager <MiningMonitorUser>(_userStore,
                                                              _optionsAccessor.Object,
                                                              _passwordHasher.Object,
                                                              Enumerable.Empty <IUserValidator <MiningMonitorUser> >(),
                                                              Enumerable.Empty <IPasswordValidator <MiningMonitorUser> >(),
                                                              _normalizer.Object,
                                                              new IdentityErrorDescriber(),
                                                              _serviceProvider.Object,
                                                              _userManagerLogger.Object);
     _httpContextAccessor = new Mock <IHttpContextAccessor>();
     _signinManagerLogger = new Mock <ILogger <SignInManager <MiningMonitorUser> > >();
     _userFactory         = new Mock <IUserClaimsPrincipalFactory <MiningMonitorUser> >();
     _authSchemeProvider  = new Mock <IAuthenticationSchemeProvider>();
     _signinManager       = new SignInManager <MiningMonitorUser>(_userManager,
                                                                  _httpContextAccessor.Object,
                                                                  _userFactory.Object,
                                                                  _optionsAccessor.Object,
                                                                  _signinManagerLogger.Object,
                                                                  _authSchemeProvider.Object);
     _loginService       = new LoginService(_signinManager);
     _snapshotCollection = _memoryDb.GetCollection <Snapshot>();
     _snapshotService    = new SnapshotService(new LiteDbRepository <Snapshot, Guid>(_snapshotCollection));
     _minerCollection    = _memoryDb.GetCollection <Miner>();
     _minerService       = new MinerService(new LiteDbRepository <Miner, Guid>(_minerCollection), _snapshotService);
     _userMapper         = new UserMapper();
     _resultMapper       = new IdentityResultMapper();
     _subject            = new CollectorService(_userManager,
                                                _loginService,
                                                _minerService,
                                                _snapshotService,
                                                _userMapper,
                                                _userMapper,
                                                _resultMapper);
 }
        public IHttpActionResult MonthlySnapshots(DateTime?startDate = null, DateTime?endDate = null)
        {
            //var account = GetLogInAccount();
            var groupOwner = GetGroupOwnerAccount();

            var snapshots = SnapshotService.GetMonthlySnapshots(groupOwner);

            if (startDate.HasValue)
            {
                snapshots = snapshots.Where(s => s.DateTaken >= startDate.Value.ToLocalTime());
            }
            if (endDate.HasValue)
            {
                // one day is added to the end date to ignore the actual time.
                snapshots = snapshots.Where(s => s.DateTaken <= endDate.Value.ToLocalTime().AddDays(1));
            }

            return(Ok(snapshots.ToList().ToApiModel()));
        }
示例#17
0
        private void InitCache()
        {
            cacheMgr = (CacheManager)CacheFactory.GetCacheManager();

            //string file = Path.Combine(HttpRuntime.AppDomainAppPath, "stateserver.state");
            //Stream s = null;
            //try
            //{
            //    if (File.Exists(file))
            //    {
            //        log.Debug("Analyzing StateServer persistance...");
            //        s = File.Open(file, FileMode.Open);
            //        BinaryFormatter bf = new BinaryFormatter();
            //        List<LineControl> lineControls = (List<LineControl>)bf.Deserialize(s);
            //        log.Debug(lineControls.Count + " lines retreived...");
            foreach (LineControl lc in SnapshotService.GetSnapshot())
            {
                log.Debug("Adding " + lc.directoryNumber + " to the cache.");
                cacheMgr.Add(lc.directoryNumber, lc);
            }
            //        s.Close();
            //        s.Dispose();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    log.Error("Unable to initialize cache: " + ex.Message);
            //}
            //finally
            //{
            //    if (s != null)
            //    {
            //        s.Close();
            //        s.Dispose();
            //    }
            //}
        }
        public void Verifies_Variant_Data()
        {
            // this test implements a full standalone NuCache (based upon a test IDataSource, does not
            // use any local db files, does not rely on any database) - and tests variations

            // get a snapshot, get a published content
            IPublishedSnapshot snapshot         = GetPublishedSnapshot();
            IPublishedContent  publishedContent = snapshot.Content.GetById(1);

            Assert.IsNotNull(publishedContent);
            Assert.AreEqual("val1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("val-fr1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "fr-FR"));
            Assert.AreEqual("val-uk1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "en-UK"));

            Assert.IsNull(publishedContent.Name(VariationContextAccessor)); // no invariant name for varying content
            Assert.AreEqual("name-fr1", publishedContent.Name(VariationContextAccessor, "fr-FR"));
            Assert.AreEqual("name-uk1", publishedContent.Name(VariationContextAccessor, "en-UK"));

            var draftContent = snapshot.Content.GetById(true, 1);

            Assert.AreEqual("val2", draftContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("val-fr2", draftContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "fr-FR"));
            Assert.AreEqual("val-uk2", draftContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "en-UK"));

            Assert.IsNull(draftContent.Name(VariationContextAccessor)); // no invariant name for varying content
            Assert.AreEqual("name-fr2", draftContent.Name(VariationContextAccessor, "fr-FR"));
            Assert.AreEqual("name-uk2", draftContent.Name(VariationContextAccessor, "en-UK"));

            // now french is default
            VariationContextAccessor.VariationContext = new VariationContext("fr-FR");
            Assert.AreEqual("val-fr1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("name-fr1", publishedContent.Name(VariationContextAccessor));
            Assert.AreEqual(new DateTime(2018, 01, 01, 01, 00, 00), publishedContent.CultureDate(VariationContextAccessor));

            // now uk is default
            VariationContextAccessor.VariationContext = new VariationContext("en-UK");
            Assert.AreEqual("val-uk1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("name-uk1", publishedContent.Name(VariationContextAccessor));
            Assert.AreEqual(new DateTime(2018, 01, 02, 01, 00, 00), publishedContent.CultureDate(VariationContextAccessor));

            // invariant needs to be retrieved explicitly, when it's not default
            Assert.AreEqual("val1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", culture: ""));

            // but,
            // if the content type / property type does not vary, then it's all invariant again
            // modify the content type and property type, notify the snapshot service
            _contentType.Variations  = ContentVariation.Nothing;
            _propertyType.Variations = ContentVariation.Nothing;
            SnapshotService.Notify(new[] { new ContentTypeCacheRefresher.JsonPayload("IContentType", publishedContent.ContentType.Id, ContentTypeChangeTypes.RefreshMain) });

            // get a new snapshot (nothing changed in the old one), get the published content again
            var anotherSnapshot = SnapshotService.CreatePublishedSnapshot(previewToken: null);
            var againContent    = anotherSnapshot.Content.GetById(1);

            Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.Variations);
            Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.GetPropertyType("prop").Variations);

            // now, "no culture" means "invariant"
            Assert.AreEqual("It Works1!", againContent.Name(VariationContextAccessor));
            Assert.AreEqual("val1", againContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
        }
    public void Remove_Node_Ensures_Linked_List()
    {
        // NOTE: these tests are not using real scopes, in which case a Scope does not control
        // how the snapshots generations work. We are forcing new snapshot generations manually.
        IEnumerable <ContentNodeKit> GetKits()
        {
            var paths = new Dictionary <int, string> {
                { -1, "-1" }
            };

            // root
            yield return(CreateInvariantKit(1, -1, 1, paths));

            // children
            yield return(CreateInvariantKit(2, 1, 1, paths));

            yield return(CreateInvariantKit(3, 1, 2, paths)); // middle child

            yield return(CreateInvariantKit(4, 1, 3, paths));
        }

        InitializedCache(GetKits(), _contentTypes);

        var snapshotService = (PublishedSnapshotService)SnapshotService;
        var contentStore    = snapshotService.GetContentStore();

        Assert.AreEqual(1, contentStore.Test.LiveGen);
        Assert.IsTrue(contentStore.Test.NextGen);

        var parentNode = contentStore.Test.GetValues(1)[0];

        Assert.AreEqual(1, parentNode.gen);
        AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 4);

        var child1 = contentStore.Test.GetValues(2)[0];

        Assert.AreEqual(1, child1.gen);
        AssertLinkedNode(child1.contentNode, 1, -1, 3, -1, -1);

        var child2 = contentStore.Test.GetValues(3)[0];

        Assert.AreEqual(1, child2.gen);
        AssertLinkedNode(child2.contentNode, 1, 2, 4, -1, -1);

        var child3 = contentStore.Test.GetValues(4)[0];

        Assert.AreEqual(1, child3.gen);
        AssertLinkedNode(child3.contentNode, 1, 3, -1, -1, -1);

        // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify)
        contentStore.CreateSnapshot();

        Assert.IsFalse(contentStore.Test.NextGen);

        SnapshotService.Notify(
            new[]
        {
            new ContentCacheRefresher.JsonPayload(3, Guid.Empty, TreeChangeTypes.Remove), // remove middle child
        },
            out _,
            out _);

        Assert.AreEqual(2, contentStore.Test.LiveGen);
        Assert.IsTrue(contentStore.Test.NextGen);

        var parentNodes = contentStore.Test.GetValues(1);

        Assert.AreEqual(1, parentNodes.Length); // the parent doesn't get changed, not new gen's are added
        parentNode = parentNodes[0];
        Assert.AreEqual(1, parentNode.gen);     // the parent node's gen has not changed
        AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 4);

        child1 = contentStore.Test.GetValues(2)[0];
        Assert.AreEqual(2, child1.gen); // there is now 2x gen's of this item
        AssertLinkedNode(child1.contentNode, 1, -1, 4, -1, -1);

        child2 = contentStore.Test.GetValues(3)[0];
        Assert.AreEqual(2, child2.gen);    // there is now 2x gen's of this item
        Assert.IsNull(child2.contentNode); // because it doesn't exist anymore

        child3 = contentStore.Test.GetValues(4)[0];
        Assert.AreEqual(2, child3.gen); // there is now 2x gen's of this item
        AssertLinkedNode(child3.contentNode, 1, 2, -1, -1, -1);
    }
示例#20
0
        public void GetSnapshot(int snapshotId)
        {
            var snapShotService = new SnapshotService();

            this.Snapshot = snapShotService.GetSnapshot(snapshotId);
        }
示例#21
0
 public void Teardown() => SnapshotService?.Dispose();
示例#22
0
        public MainViewModel()
        {
            var snapShotService = new SnapshotService();

            this.Snapshots = snapShotService.GetSnapshots();
        }
    public void MoveTest()
    {
        InitializedCache(GetInvariantKits(), _contentTypes);

        // get snapshot
        var snapshot = GetPublishedSnapshot();

        // do some changes
        var kit = NuCacheContentService.ContentKits[4];

        NuCacheContentService.ContentKits[4] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            kit.Node.Path,
            2,
            kit.Node.Level,
            kit.Node.ParentContentId,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        kit = NuCacheContentService.ContentKits[5];
        NuCacheContentService.ContentKits[5] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            kit.Node.Path,
            3,
            kit.Node.Level,
            kit.Node.ParentContentId,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        kit = NuCacheContentService.ContentKits[6];
        NuCacheContentService.ContentKits[6] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            kit.Node.Path,
            4,
            kit.Node.Level,
            kit.Node.ParentContentId,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        kit = NuCacheContentService.ContentKits[7];
        NuCacheContentService.ContentKits[7] = ContentNodeKitBuilder.CreateWithContent(
            _contentTypeInvariant.Id,
            kit.Node.Id,
            "-1,1,7",
            1,
            kit.Node.Level,
            1,
            draftData: null,
            publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name));

        // notify
        SnapshotService.Notify(
            new[]
        {
            // removal must come first
            new ContentCacheRefresher.JsonPayload(2, Guid.Empty, TreeChangeTypes.RefreshBranch),
            new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.RefreshBranch),
        },
            out _,
            out _);

        // changes that *I* make are immediately visible on the current snapshot
        var documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray();

        AssertDocuments(documents, "N7", "N4", "N5", "N6");

        documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray();
        AssertDocuments(documents, "N9", "N8");

        Assert.AreEqual(1, snapshot.Content.GetById(7).Parent?.Id);
    }
示例#24
0
 public CreateSnapshotManager(LoggingManager loggingManager, SnapshotService snapshotService)
 {
     _loggingManager  = loggingManager;
     _snapshotService = snapshotService;
 }
    public void Refresh_Branch_With_Alternating_Publish_Flags()
    {
        // NOTE: these tests are not using real scopes, in which case a Scope does not control
        // how the snapshots generations work. We are forcing new snapshot generations manually.
        IEnumerable <ContentNodeKit> GetKits()
        {
            var paths = new Dictionary <int, string> {
                { -1, "-1" }
            };

            // root
            yield return(CreateInvariantKit(100, -1, 1, paths));

            // site
            yield return(CreateInvariantKit(2, 100, 1, paths));

            yield return(CreateInvariantKit(1, 100, 2, paths)); // middle child

            yield return(CreateInvariantKit(3, 100, 3, paths));

            // children of 1
            yield return(CreateInvariantKit(20, 1, 1, paths));

            yield return(CreateInvariantKit(30, 1, 2, paths));

            yield return(CreateInvariantKit(40, 1, 3, paths));
        }

        // init with all published
        InitializedCache(GetKits(), _contentTypes);

        var snapshotService = (PublishedSnapshotService)SnapshotService;
        var contentStore    = snapshotService.GetContentStore();

        var rootKit = NuCacheContentService.ContentKits[1].Clone(PublishedModelFactory);

        void ChangePublishFlagOfRoot(bool published, int assertGen, TreeChangeTypes changeType)
        {
            // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify)
            contentStore.CreateSnapshot();

            Assert.IsFalse(contentStore.Test.NextGen);

            // Change the root publish flag
            var kit = rootKit.Clone(
                PublishedModelFactory,
                published ? null : rootKit.PublishedData,
                published ? rootKit.PublishedData : null);

            NuCacheContentService.ContentKits[1] = kit;

            SnapshotService.Notify(new[] { new ContentCacheRefresher.JsonPayload(1, Guid.Empty, changeType) }, out _, out _);

            Assert.AreEqual(assertGen, contentStore.Test.LiveGen);
            Assert.IsTrue(contentStore.Test.NextGen);

            // get the latest gen for content Id 1
            var(gen, contentNode) = contentStore.Test.GetValues(1)[0];
            Assert.AreEqual(assertGen, gen);

            // even when unpublishing/re-publishing/etc... the linked list is always maintained
            AssertLinkedNode(contentNode, 100, 2, 3, 20, 40);
        }

        // unpublish the root
        ChangePublishFlagOfRoot(false, 2, TreeChangeTypes.RefreshBranch);

        // publish the root (since it's not published, it will cause a RefreshBranch)
        ChangePublishFlagOfRoot(true, 3, TreeChangeTypes.RefreshBranch);

        // publish root + descendants
        ChangePublishFlagOfRoot(true, 4, TreeChangeTypes.RefreshBranch);

        // save/publish the root (since it's already published, it will just cause a RefreshNode
        ChangePublishFlagOfRoot(true, 5, TreeChangeTypes.RefreshNode);

        // publish root + descendants
        ChangePublishFlagOfRoot(true, 6, TreeChangeTypes.RefreshBranch);
    }