Example #1
0
        public void RemoteFolderChangedAndModificationDateCouldNotBeSet()
        {
            DateTime creationDate    = DateTime.UtcNow;
            string   folderName      = "a";
            string   path            = Path.Combine(Path.GetTempPath(), folderName);
            string   id              = "id";
            string   parentId        = "papa";
            string   lastChangeToken = "token";
            string   newChangeToken  = "newToken";
            DateTime modification    = DateTime.UtcNow;

            var dirInfo = new Mock <IDirectoryInfo>();

            dirInfo.Setup(d => d.FullName).Returns(path);
            dirInfo.Setup(d => d.Name).Returns(folderName);
            dirInfo.Setup(d => d.Parent).Returns(Mock.Of <IDirectoryInfo>());
            dirInfo.SetupGet(d => d.LastWriteTimeUtc).Returns(modification);
            dirInfo.SetupSet(d => d.LastWriteTimeUtc = It.IsAny <DateTime>()).Throws(new IOException("Another process is using this folder"));

            var mappedObject = new MappedObject(
                folderName,
                id,
                MappedObjectType.Folder,
                parentId,
                lastChangeToken)
            {
                Guid = Guid.NewGuid()
            };

            this.storage.AddMappedFolder(mappedObject);

            Mock <IFolder> remoteObject = MockOfIFolderUtil.CreateRemoteFolderMock(id, folderName, path, parentId, newChangeToken);

            remoteObject.Setup(f => f.LastModificationDate).Returns((DateTime?)creationDate);

            this.underTest.Solve(dirInfo.Object, remoteObject.Object);

            this.storage.VerifySavedMappedObject(MappedObjectType.Folder, id, folderName, parentId, newChangeToken, lastLocalModification: modification);
            dirInfo.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(creationDate)), Times.Once());
            this.queue.Verify(q => q.AddEvent(It.IsAny <ISyncEvent>()), Times.Never());
        }
Example #2
0
        public void OneRemoteFileRenamedAndContentHashIsAvailable()
        {
            byte[]   checksum         = new byte[20];
            string   type             = "SHA-1";
            string   oldFileName      = "fileName";
            string   newFileName      = "newfileName";
            string   fileId           = "fileId";
            DateTime lastModification = DateTime.UtcNow;
            var      localGuid        = Guid.NewGuid();
            var      oldLocalFile     = this.fsFactory.AddFile(Path.Combine(this.localRootPath, oldFileName));

            oldLocalFile.SetupLastWriteTimeUtc(lastModification);
            oldLocalFile.SetupGuid(localGuid);
            var storedFile = new MappedObject(oldFileName, fileId, MappedObjectType.File, this.remoteRootId, "changeToken")
            {
                Guid = localGuid,
                ChecksumAlgorithmName = type,
                LastChecksum          = checksum,
                LastLocalWriteTimeUtc = lastModification
            };

            this.localFolder.SetupFiles(oldLocalFile.Object);
            this.storage.SaveMappedObject(storedFile);
            var renamedRemoteFile = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, fileId, newFileName, this.remoteRootId, changeToken: "newChangeToken");

            renamedRemoteFile.SetupContentStreamHash(checksum, type);
            this.remoteFolder.SetupDescendants(renamedRemoteFile.Object);
            Assert.That(this.CreateCrawler().Handle(new StartNextSyncEvent()), Is.True);
            this.queue.Verify(
                q =>
                q.AddEvent(
                    It.Is <FileEvent>(
                        e =>
                        e.Remote == MetaDataChangeType.CHANGED &&
                        e.RemoteContent == ContentChangeType.NONE &&
                        e.Local == MetaDataChangeType.NONE &&
                        e.RemoteFile.Equals(renamedRemoteFile.Object))),
                Times.Once());
            this.VerifyThatCountOfAddedEventsIsLimitedTo(Times.Once());
            this.VerifyThatListenerHasBeenUsed();
        }
Example #3
0
        public void RemoteDocumentsMetaDataChanged()
        {
            byte[]   hash             = new byte[20];
            DateTime modificationDate = DateTime.UtcNow;
            string   fileName         = "a";
            string   path             = Path.Combine(Path.GetTempPath(), fileName);
            string   id              = "id";
            string   parentId        = "papa";
            string   lastChangeToken = "token";
            string   newChangeToken  = "newToken";

            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(d => d.FullName).Returns(path);
            fileInfo.Setup(d => d.Name).Returns(fileName);
            fileInfo.Setup(d => d.Directory).Returns(Mock.Of <IDirectoryInfo>());

            var mappedObject = new MappedObject(
                fileName,
                id,
                MappedObjectType.File,
                parentId,
                lastChangeToken)
            {
                Guid                  = Guid.NewGuid(),
                LastContentSize       = 0,
                LastChecksum          = hash,
                ChecksumAlgorithmName = "SHA-1"
            };

            this.storage.AddMappedFile(mappedObject);

            Mock <IDocument> remoteObject = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, id, fileName, parentId, changeToken: newChangeToken);

            remoteObject.Setup(f => f.LastModificationDate).Returns((DateTime?)modificationDate);

            this.underTest.Solve(fileInfo.Object, remoteObject.Object, ContentChangeType.NONE, ContentChangeType.NONE);

            this.storage.VerifySavedMappedObject(MappedObjectType.File, id, fileName, parentId, newChangeToken, contentSize: 0, checksum: hash);
            fileInfo.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(modificationDate)), Times.Once());
        }
Example #4
0
        public void TestSqlConnectionObjectMappingInsertAndMerge()
        {
            // Setup
            var entity = new MappedObject
            {
                SessionIdMapped       = Guid.NewGuid(),
                ColumnBigIntMapped    = long.MaxValue,
                ColumnBitMapped       = true,
                ColumnDateTime2Mapped = DateTime.Parse("1970-01-01 1:25:00.44569"),
                ColumnDateTimeMapped  = DateTime.Parse("1970-01-01 10:30:30"),
                ColumnIntMapped       = int.MaxValue,
                ColumnNVarCharMapped  = Helper.GetAssemblyDescription()
            };

            using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
            {
                // Act Insert
                var id = connection.Insert(entity);

                // Setup
                entity.ColumnNVarCharMapped = $"{entity.ColumnNVarCharMapped} (Merged)";

                // Act Update
                var mergeResult = connection.Merge <MappedObject>(entity, Field.From("SessionId"));

                // Assert
                Assert.AreEqual(entity.SessionIdMapped, mergeResult);

                // Act Query
                var data = connection.Query <MappedObject>(new { SessionId = id }).FirstOrDefault();

                // Assert
                Assert.IsNotNull(data);
                Assert.AreEqual(entity.ColumnBigIntMapped, data.ColumnBigIntMapped);
                Assert.AreEqual(entity.ColumnBitMapped, data.ColumnBitMapped);
                Assert.AreEqual(entity.ColumnDateTime2Mapped, data.ColumnDateTime2Mapped);
                Assert.AreEqual(entity.ColumnDateTimeMapped, data.ColumnDateTimeMapped);
                Assert.AreEqual(entity.ColumnIntMapped, data.ColumnIntMapped);
                Assert.AreEqual(entity.ColumnNVarCharMapped, data.ColumnNVarCharMapped);
            }
        }
Example #5
0
        public void TestSqlConnectionObjectMappingInsertAndInlineUpdateViaExpression()
        {
            // Setup
            var entity = new MappedObject
            {
                SessionIdMapped       = Guid.NewGuid(),
                ColumnBigIntMapped    = long.MaxValue,
                ColumnBitMapped       = true,
                ColumnDateTime2Mapped = DateTime.Parse("1970-01-01 1:25:00.44569"),
                ColumnDateTimeMapped  = DateTime.Parse("1970-01-01 10:30:30"),
                ColumnIntMapped       = int.MaxValue,
                ColumnNVarCharMapped  = Helper.GetAssemblyDescription()
            };

            using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
            {
                // Act Insert
                var id = connection.Insert(entity);

                // Act Update
                var affectedRows = connection.InlineUpdate <MappedObject>(new
                {
                    ColumnNVarChar = $"{entity.ColumnNVarCharMapped} (Updated)"
                }, c => c.SessionIdMapped == (Guid)id);

                // Assert
                Assert.AreEqual(1, affectedRows);

                // Act Query
                var data = connection.Query <MappedObject>(new { SessionId = id }).FirstOrDefault();

                // Assert
                Assert.IsNotNull(data);
                Assert.AreEqual(entity.ColumnBigIntMapped, data.ColumnBigIntMapped);
                Assert.AreEqual(entity.ColumnBitMapped, data.ColumnBitMapped);
                Assert.AreEqual(entity.ColumnDateTime2Mapped, data.ColumnDateTime2Mapped);
                Assert.AreEqual(entity.ColumnDateTimeMapped, data.ColumnDateTimeMapped);
                Assert.AreEqual(entity.ColumnIntMapped, data.ColumnIntMapped);
                Assert.AreEqual($"{entity.ColumnNVarCharMapped} (Updated)", data.ColumnNVarCharMapped);
            }
        }
Example #6
0
        public void OneLocalFileRemoved()
        {
            var oldLocalFile = this.fsFactory.AddFile(Path.Combine(this.localRootPath, "oldFile"));

            oldLocalFile.Setup(f => f.Exists).Returns(false);
            var remoteFile = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, "oldFileId", "oldFile", this.remoteRootId, changeToken: "oldChange");
            var storedFile = new MappedObject("oldFile", "oldFileId", MappedObjectType.File, this.remoteRootId, "oldChange")
            {
                Guid = Guid.NewGuid()
            };

            this.storage.SaveMappedObject(storedFile);

            this.remoteFolder.SetupDescendants(remoteFile.Object);
            var crawler = this.CreateCrawler();

            Assert.That(crawler.Handle(new StartNextSyncEvent()), Is.True);
            this.queue.Verify(q => q.AddEvent(It.Is <FileEvent>(e => e.LocalFile != null && e.LocalFile.Equals(oldLocalFile.Object) && e.Local.Equals(MetaDataChangeType.DELETED))), Times.Once());
            this.VerifyThatCountOfAddedEventsIsLimitedTo(Times.Once());
            this.VerifyThatListenerHasBeenUsed();
        }
        public void RemoteFileDeletedAndAlsoLocalFileDoesNotExistsAnymore()
        {
            this.SetUpTestMocks();
            DateTime lastModified = DateTime.UtcNow;
            var      fileInfo     = new Mock <IFileInfo>();

            fileInfo.Setup(f => f.FullName).Returns(this.path);
            fileInfo.Setup(f => f.LastWriteTimeUtc).Returns(new DateTime());
            fileInfo.Setup(f => f.Exists).Returns(false);
            var mappedObject = new MappedObject("a", "id", MappedObjectType.File, "parentId", "changeToken", 0)
            {
                LastLocalWriteTimeUtc = lastModified
            };

            this.storage.AddMappedFile(mappedObject, this.path);

            this.underTest.Solve(fileInfo.Object, null);

            fileInfo.Verify(f => f.Delete(), Times.Never());
            this.storage.Verify(s => s.RemoveObject(mappedObject), Times.Once());
        }
        public void RenameFile()
        {
            this.SetUpMocks();
            long fileLength = 100;
            var  file       = Mock.Of <IFileInfo>(
                f =>
                f.Name == "newName");
            var doc = Mock.Of <IDocument>(
                d =>
                d.Id == "remoteId");
            var obj = new MappedObject("oldName", "remoteId", MappedObjectType.File, "parentId", "changeToken", fileLength)
            {
                Guid = Guid.NewGuid()
            };

            this.storage.AddMappedFile(obj);
            this.underTest.Solve(file, doc, ContentChangeType.CHANGED, ContentChangeType.CHANGED);
            Mock.Get(doc).Verify(d => d.Rename("newName", true), Times.Once());
            this.storage.VerifySavedMappedObject(MappedObjectType.File, "remoteId", "newName", "parentId", "changeToken", contentSize: fileLength);
            this.changeSolver.Verify(s => s.Solve(file, doc, ContentChangeType.CHANGED, ContentChangeType.CHANGED));
        }
Example #9
0
        public void GetObjectByPath()
        {
            var matcher = new Mock <IPathMatcher>();

            matcher.Setup(m => m.LocalTargetRootPath).Returns(Path.GetTempPath());
            matcher.Setup(m => m.CanCreateRemotePath(It.Is <string>(f => f == Path.Combine(Path.GetTempPath(), "a")))).Returns(true);
            matcher.Setup(m => m.GetRelativeLocalPath(It.Is <string>(p => p == Path.Combine(Path.GetTempPath(), "a")))).Returns("a");
            var storage = new MetaDataStorage(this.engine, matcher.Object);
            var folder  = Mock.Of <IDirectoryInfo>(f =>
                                                   f.FullName == Path.Combine(Path.GetTempPath(), "a"));
            var mappedFolder = new MappedObject("a", "remoteId", MappedObjectType.Folder, null, null)
            {
                Guid = Guid.NewGuid(),
            };

            storage.SaveMappedObject(mappedFolder);

            var obj = storage.GetObjectByLocalPath(folder);

            Assert.That(obj, Is.EqualTo(mappedFolder));
        }
Example #10
0
        public void ToLinePrintReturnsOneLinePerEntry()
        {
            var storage      = new MetaDataStorage(this.engine, Mock.Of <IPathMatcher>());
            var rootFolder   = new MappedObject("name", "rootId", MappedObjectType.Folder, null, "token");
            var child1Folder = new MappedObject("sub1", "subId1", MappedObjectType.Folder, "rootId", "token");
            var child2Folder = new MappedObject("sub2", "subId2", MappedObjectType.Folder, "rootId", "token");
            var child3Folder = new MappedObject("sub3", "subId3", MappedObjectType.Folder, "rootId", "token");
            var subChildFile = new MappedObject("file", "subId4", MappedObjectType.File, "subId1", "token");

            storage.SaveMappedObject(rootFolder);
            storage.SaveMappedObject(child1Folder);
            storage.SaveMappedObject(child2Folder);
            storage.SaveMappedObject(child3Folder);
            storage.SaveMappedObject(subChildFile);

            string src = storage.ToFindString();

            int count = src.Select((c, i) => src.Substring(i)).Count(sub => sub.StartsWith(Environment.NewLine));

            Assert.That(count, Is.EqualTo(5), string.Format("Newlines Counting {0}:{2} {1}", count, src, Environment.NewLine));
        }
Example #11
0
        public void NoChangeOnExistingFileAndFolderCreatesNoEventsInQueue()
        {
            DateTime changeTime           = DateTime.UtcNow;
            string   changeToken          = "token";
            string   fileName             = "name";
            string   fileId               = "fileId";
            string   folderName           = "folder";
            string   folderId             = "folderId";
            Guid     folderGuid           = Guid.NewGuid();
            Guid     fileGuid             = Guid.NewGuid();
            var      remoteFile           = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, fileId, fileName, this.remoteRootId, changeToken: changeToken);
            var      existingRemoteFolder = MockOfIFolderUtil.CreateRemoteFolderMock(folderId, folderName, this.remoteRootPath + folderName, this.remoteRootId, changeToken);
            var      file = this.fsFactory.AddFile(Path.Combine(this.localRootPath, fileName), fileGuid);

            file.Setup(f => f.LastWriteTimeUtc).Returns(changeTime);
            var storedFile = new MappedObject(fileName, fileId, MappedObjectType.File, this.remoteRootId, changeToken)
            {
                Guid = fileGuid, LastLocalWriteTimeUtc = changeTime
            };

            this.storage.SaveMappedObject(storedFile);
            var folder = this.fsFactory.AddDirectory(Path.Combine(this.localRootPath, folderName), folderGuid);

            folder.Setup(f => f.LastWriteTimeUtc).Returns(changeTime);
            var storedFolder = new MappedObject(folderName, folderId, MappedObjectType.Folder, this.remoteRootId, changeToken)
            {
                Guid = folderGuid, LastLocalWriteTimeUtc = changeTime
            };

            this.storage.SaveMappedObject(storedFolder);
            this.remoteFolder.SetupDescendants(remoteFile.Object, existingRemoteFolder.Object);
            this.localFolder.SetupFilesAndDirectories(file.Object, folder.Object);

            var crawler = this.CreateCrawler();

            Assert.That(crawler.Handle(new StartNextSyncEvent()), Is.True);
            this.queue.Verify(q => q.AddEvent(It.Is <AbstractFolderEvent>(e => e.Local == MetaDataChangeType.NONE && e.Remote == MetaDataChangeType.NONE)), Times.Never());
            this.VerifyThatCountOfAddedEventsIsLimitedTo(Times.Never());
            this.VerifyThatListenerHasBeenUsed();
        }
Example #12
0
        public void MoveAndRenameLocalFolder([Values(true, false)] bool childrenAreIgnored)
        {
            this.SetUpMocks();
            string oldPath      = Path.Combine(Path.GetTempPath(), "old", "oldname");
            string newPath      = Path.Combine(Path.GetTempPath(), "new", "newname");
            var    mappedObject = new MappedObject("oldname", "remoteId", MappedObjectType.Folder, "oldParentId", "changeToken")
            {
                Guid = Guid.NewGuid()
            };

            this.storage.AddMappedFolder(mappedObject);
            var remoteFolder = MockOfIFolderUtil.CreateRemoteFolderMock("remoteId", "newname", "path", "parentId", ignored: childrenAreIgnored);
            var dir          = Mock.Of <IDirectoryInfo>(
                d =>
                d.FullName == oldPath);

            this.storage.Setup(s => s.Matcher.CreateLocalPath(remoteFolder.Object)).Returns(newPath);
            this.underTest.Solve(dir, remoteFolder.Object, ContentChangeType.NONE, ContentChangeType.NONE);
            Mock.Get(dir).Verify(d => d.MoveTo(newPath), Times.Once());
            this.changeSolver.Verify(s => s.Solve(dir, remoteFolder.Object, ContentChangeType.NONE, ContentChangeType.NONE), Times.Once());
            this.storage.VerifySavedMappedObject(MappedObjectType.Folder, "remoteId", "newname", "parentId", "changeToken", ignored: childrenAreIgnored);
        }
Example #13
0
        internal void WriteJsonObject(MappedObject mappedObject, JsonTextWriter jsonWriter, IDictionary <string, object> currentRow, RowSet rowSet, List <string> fieldNameList, ParentObject parent, IDictionary <string, object> context)
        {
            jsonWriter.WriteStartObject();
            foreach (var prop in mappedObject.MappedPropertyList)
            {
                if (prop.GetValidQuery() != null)
                {
                    var localParent = new ParentObject(parent, currentRow, prop);

                    if (prop.GetValidQuery() is MappedQueryWithNestedResults)
                    {
                        WriteQueryWithNestedResults(prop.GetValidQuery() as MappedQueryWithNestedResults, jsonWriter, localParent, context, prop);
                    }
                    else
                    {
                        WriteQueryResults(prop.GetValidQuery(), jsonWriter, localParent, context, prop);
                    }
                }
                else if (prop.MappedObject != null)
                {
                    jsonWriter.WritePropertyName(prop.TargetPropertyName);
                    WriteJsonObject(prop.MappedObject, jsonWriter, currentRow, rowSet, fieldNameList, parent, context);
                }
                else if (prop.MappedNestedResults != null)
                {
                    WriteNestedResult(prop, prop.MappedNestedResults, jsonWriter, rowSet, fieldNameList, parent, context);
                }
                else if (prop.ValueResolver != null)
                {
                    WriteCustomResolvedValue(prop, jsonWriter, currentRow, context);
                }
                else
                {
                    WriteColumnValue(prop, jsonWriter, currentRow, fieldNameList);
                    WriteStaticValue(prop, jsonWriter);
                }
            }
            jsonWriter.WriteEndObject();
        }
Example #14
0
        internal void InternalCreateQueryNewCommands(MappedObject mappedObject, CommandParameterPrefix prefix, IDictionary <MappedQuery, ICommandWithParameterSetter> commands)
        {
            if (mappedObject is MappedQuery)
            {
                var mappedQuery            = mappedObject as MappedQuery;
                var queryWithNestedResults = mappedObject as MappedQueryWithNestedResults;
                var queryText = queryWithNestedResults != null?EnforceOrderingOfQueryWithNestedResults(queryWithNestedResults.Query, queryWithNestedResults.IdColumn) : mappedQuery.Query;

                commands.Add(mappedQuery, commandSetterFactory.CreateCommand(queryText, connection, prefix));
            }
            foreach (var mappedProperty in mappedObject.MappedPropertyList)
            {
                if (mappedProperty.GetValidQuery() != null)
                {
                    InternalCreateQueryNewCommands(mappedProperty.GetValidQuery(), prefix, commands);
                }
                if (mappedProperty.MappedObject != null)
                {
                    InternalCreateQueryNewCommands(mappedProperty.MappedObject, prefix, commands);
                }
            }
        }
Example #15
0
        public void GetObjectByPathWithHierarchie()
        {
            var matcher = new PathMatcher(Path.GetTempPath(), "/");
            var storage = new MetaDataStorage(this.engine, matcher);
            var root    = Mock.Of <IDirectoryInfo>(f =>
                                                   f.FullName == Path.GetTempPath());
            var folder = Mock.Of <IDirectoryInfo>(f =>
                                                  f.FullName == Path.Combine(Path.GetTempPath(), "a"));
            var mappedRoot   = new MappedObject("/", "rootId", MappedObjectType.Folder, null, null);
            var mappedFolder = new MappedObject("a", "remoteId", MappedObjectType.Folder, "rootId", null)
            {
                Guid = Guid.NewGuid(),
            };

            storage.SaveMappedObject(mappedRoot);
            storage.SaveMappedObject(mappedFolder);

            var obj = storage.GetObjectByLocalPath(folder);

            Assert.That(storage.GetObjectByLocalPath(root), Is.EqualTo(mappedRoot));
            Assert.That(obj, Is.EqualTo(mappedFolder));
        }
        public void RemoteFileDeleted()
        {
            this.SetUpTestMocks();
            DateTime lastModified = DateTime.UtcNow;
            var      fileInfo     = new Mock <IFileInfo>();

            fileInfo.Setup(f => f.FullName).Returns(this.path);
            fileInfo.Setup(f => f.LastWriteTimeUtc).Returns(lastModified);
            fileInfo.Setup(f => f.Exists).Returns(true);
            fileInfo.Setup(f => f.Delete()).Callback(() => fileInfo.Setup(f1 => f1.Refresh()).Callback(() => fileInfo.Setup(f3 => f3.Exists).Returns(false)));
            var mappedObject = new MappedObject("a", "id", MappedObjectType.File, "parentId", "changeToken", 0)
            {
                LastLocalWriteTimeUtc = lastModified
            };

            this.storage.AddMappedFile(mappedObject, this.path);

            this.underTest.Solve(fileInfo.Object, null);

            fileInfo.Verify(f => f.Delete(), Times.Once());
            this.storage.Verify(s => s.RemoveObject(mappedObject), Times.Once());
        }
Example #17
0
        private string[] GetRelativePathSegments(Transaction tran, string id)
        {
            Stack <string> pathSegments = new Stack <string>();
            var            value        = tran.Select <string, DbCustomSerializer <MappedObject> >(MappedObjectsTable, id).Value;

            if (value == null)
            {
                return(null);
            }

            MappedObject entry = value.Get;

            pathSegments.Push(entry.Name);
            while (entry.ParentId != null)
            {
                id    = entry.ParentId;
                entry = tran.Select <string, DbCustomSerializer <MappedObject> >(MappedObjectsTable, id).Value.Get;
                pathSegments.Push(entry.Name);
            }

            return(pathSegments.ToArray());
        }
Example #18
0
        /// <summary>
        /// Gets the tree of mapped objects.
        /// </summary>
        /// <returns>The object tree.</returns>
        public IObjectTree <IMappedObject> GetObjectTree()
        {
            MappedObject        root    = null;
            List <MappedObject> objects = new List <MappedObject>();

            using (var tran = this.engine.GetTransaction()) {
                foreach (var row in tran.SelectForward <string, DbCustomSerializer <MappedObject> >(MappedObjectsTable))
                {
                    var value = row.Value;
                    if (value == null)
                    {
                        continue;
                    }

                    var data = value.Get;
                    if (data == null)
                    {
                        continue;
                    }

                    if (data.ParentId == null)
                    {
                        root = data;
                    }
                    else
                    {
                        objects.Add(data);
                    }
                }
            }

            if (root == null)
            {
                return(null);
            }

            return(this.GetSubTree(objects, root));
        }
Example #19
0
        public void LocalFolderChangedFetchByGuidInExtendedAttribute()
        {
            Guid guid             = Guid.NewGuid();
            var  modificationDate = DateTime.UtcNow;
            var  localDirectory   = new Mock <IDirectoryInfo>();

            localDirectory.Setup(f => f.LastWriteTimeUtc).Returns(modificationDate.AddMinutes(1));
            localDirectory.Setup(f => f.Exists).Returns(true);
            localDirectory.Setup(f => f.GetExtendedAttribute(MappedObject.ExtendedAttributeKey)).Returns(guid.ToString());

            var mappedObject = new MappedObject(
                "name",
                "remoteId",
                MappedObjectType.Folder,
                "parentId",
                "changeToken")
            {
                Guid = guid,
                LastRemoteWriteTimeUtc = modificationDate.AddMinutes(1)
            };

            this.storage.AddMappedFolder(mappedObject);

            this.underTest.Solve(localDirectory.Object, Mock.Of <IFolder>());

            this.storage.VerifySavedMappedObject(
                MappedObjectType.Folder,
                "remoteId",
                mappedObject.Name,
                mappedObject.ParentId,
                mappedObject.LastChangeToken,
                true,
                localDirectory.Object.LastWriteTimeUtc);
            this.queue.Verify(q => q.AddEvent(It.IsAny <ISyncEvent>()), Times.Never());
            localDirectory.VerifyThatLocalFileObjectLastWriteTimeUtcIsNeverModified();
            this.manager.Verify(m => m.AddTransmission(It.IsAny <FileTransmissionEvent>()), Times.Never());
            this.storage.Verify(s => s.GetObjectByLocalPath(It.IsAny <IFileSystemInfo>()), Times.Never());
        }
        /// <summary>
        /// Get the merged Objectparameter for a MappedObject
        /// </summary>
        /// <param name="mapObj"></param>
        /// <returns></returns>
        public static Objectparameter getMergedObjectParameter(MappedObject mapObj)
        {
            // default take everything from original
            Objectparameter mergedObjParam = (Objectparameter)mapObj.Objectparameter.Clone();

            // look for free fill properties
            if (mapObj.Objectparameter.MotherObjectparameter != null)
            {
                mergedObjParam.HasProperties     = mapObj.Objectparameter.MotherObjectparameter.HasProperties;
                mergedObjParam.ProcessParameters = mapObj.Objectparameter.MotherObjectparameter.ProcessParameters;
                mergedObjParam.FeatureType       = mapObj.Objectparameter.MotherObjectparameter.FeatureType;
            }
            else
            {
                mergedObjParam.HasProperties = mapObj.Objectparameter.HasProperties;
                mergedObjParam.FeatureType   = mapObj.Objectparameter.FeatureType;
            }

            // copy all free fill properties to merged parameter, wenn free fill has a value
            foreach (ObjectparameterHasProperties ohp in mergedObjParam.HasProperties.Where(m => m.isOptional == true))
            {
                if (mapObj.FreeFillParameter != null)
                {
                    // Get the Property from the Free Fill Object
                    PropertyInfo FreeFillProperty = ohp.Property.Split('.').Select(s => mapObj.FreeFillParameter.GetType().GetProperty(s)).FirstOrDefault();
                    // Get the Property from the Merged Object
                    PropertyInfo MergedProperty = ohp.Property.Split('.').Select(s => mergedObjParam.GetType().GetProperty(s)).FirstOrDefault();

                    // Assign FreeFill PropertyValue to Merged PropertyValue
                    if (FreeFillProperty.GetValue(mapObj.FreeFillParameter) != null)
                    {
                        MergedProperty.SetValue(mergedObjParam, FreeFillProperty.GetValue(mapObj.FreeFillParameter));
                    }
                }
            }

            return(mergedObjParam);
        }
        public void RemoteFolderDeletedButNotAllContainingFilesAreSyncedYet()
        {
            this.SetUpTestMocks();
            string               fileName       = "fileName";
            string               filePath       = Path.Combine(this.path, fileName);
            string               syncedFileName = "syncedFileName";
            string               syncedFilePath = Path.Combine(this.path, syncedFileName);
            DateTime             lastModified   = DateTime.UtcNow;
            Guid                 syncedFileGuid = Guid.NewGuid();
            Mock <IMappedObject> folder         = this.storage.AddLocalFolder(this.path, "id");
            var dirInfo = new Mock <IDirectoryInfo>();

            dirInfo.Setup(d => d.FullName).Returns(this.path);
            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(f => f.FullName).Returns(filePath);
            fileInfo.Setup(f => f.Name).Returns(fileName);
            var syncedFileInfo = new Mock <IFileInfo>();

            syncedFileInfo.Setup(s => s.FullName).Returns(syncedFilePath);
            syncedFileInfo.Setup(s => s.Name).Returns(syncedFileName);
            syncedFileInfo.SetupGuid(syncedFileGuid);
            syncedFileInfo.Setup(s => s.LastWriteTimeUtc).Returns(lastModified);
            dirInfo.SetupFiles(fileInfo.Object, syncedFileInfo.Object);
            var mappedSyncedFile = new MappedObject(syncedFileName, "id", MappedObjectType.File, "parentId", "changeToken", 0)
            {
                Guid = syncedFileGuid, LastLocalWriteTimeUtc = lastModified
            };

            this.storage.AddMappedFile(mappedSyncedFile, syncedFilePath);

            Assert.Throws <IOException>(() => this.underTest.Solve(dirInfo.Object, null));

            dirInfo.Verify(d => d.Delete(true), Times.Never());
            syncedFileInfo.Verify(s => s.Delete(), Times.Once());
            fileInfo.Verify(f => f.Delete(), Times.Never());
            this.storage.Verify(s => s.RemoveObject(It.Is <IMappedObject>(o => o == folder.Object)), Times.Once());
        }
Example #22
0
        public void OneRemoteFileRemoved()
        {
            Guid         fileGuid         = Guid.NewGuid();
            DateTime     modificationDate = DateTime.UtcNow;
            MappedObject obj = new MappedObject("name", "id", MappedObjectType.File, this.remoteRootId, "changeToken", 0)
            {
                Guid = fileGuid,
                LastLocalWriteTimeUtc = modificationDate
            };
            var oldLocalFile = this.fsFactory.AddFile(Path.Combine(this.localRootPath, "name"));

            oldLocalFile.SetupGuid(fileGuid);
            oldLocalFile.SetupLastWriteTimeUtc(modificationDate);
            this.localFolder.SetupFiles(oldLocalFile.Object);
            this.storage.SaveMappedObject(obj);

            var underTest = this.CreateCrawler();

            Assert.That(underTest.Handle(new StartNextSyncEvent()), Is.True);
            this.queue.Verify(q => q.AddEvent(It.Is <FileEvent>(e => e.Remote == MetaDataChangeType.DELETED)), Times.Once());
            this.VerifyThatCountOfAddedEventsIsLimitedTo(Times.Once());
            this.VerifyThatListenerHasBeenUsed();
        }
Example #23
0
        public void OneRemoteFolderRemoved()
        {
            Guid     uuid           = Guid.NewGuid();
            DateTime modification   = DateTime.UtcNow;
            var      oldLocalFolder = this.fsFactory.AddDirectory(Path.Combine(this.localRootPath, "folderName"));

            oldLocalFolder.SetupGuid(uuid);
            oldLocalFolder.SetupLastWriteTimeUtc(modification);
            var storedFolder = new MappedObject("folderName", "folderId", MappedObjectType.Folder, this.remoteRootId, "changeToken")
            {
                Guid = uuid,
                LastLocalWriteTimeUtc = modification
            };

            this.storage.SaveMappedObject(storedFolder);
            this.localFolder.SetupDirectories(oldLocalFolder.Object);
            var crawler = this.CreateCrawler();

            Assert.That(crawler.Handle(new StartNextSyncEvent()), Is.True);
            this.queue.Verify(q => q.AddEvent(It.Is <FolderEvent>(e => e.Remote == MetaDataChangeType.DELETED && e.LocalFolder.Equals(oldLocalFolder.Object))), Times.Once());
            this.VerifyThatCountOfAddedEventsIsLimitedTo(Times.Once());
            this.VerifyThatListenerHasBeenUsed();
        }
        public void ConstructorTakesData(
            [Values(true, false)] bool ignored,
            [Values(true, false)] bool readOnly,
            [Values(MappedObjectType.File, MappedObjectType.Folder)] MappedObjectType type)
        {
            var data = new MappedObject("name", "remoteId", type, "parentId", "changeToken")
            {
                LastChecksum            = new byte[20],
                Ignored                 = ignored,
                Guid                    = Guid.NewGuid(),
                LastLocalWriteTimeUtc   = DateTime.Now,
                LastRemoteWriteTimeUtc  = DateTime.UtcNow,
                Description             = "desc",
                LastContentSize         = type == MappedObjectType.File ? 2345 : 0,
                IsReadOnly              = readOnly,
                LastTimeStoredInStorage = DateTime.UtcNow
            };

            var file = new MappedObject(data);

            Assert.That(data, Is.EqualTo(file));
            Assert.That(file.LastTimeStoredInStorage, Is.EqualTo(data.LastTimeStoredInStorage));
        }
Example #25
0
        /// <summary>
        /// Gets the object by GUID.
        /// </summary>
        /// <returns>The object by GUID.</returns>
        /// <param name="guid">GUID of the requested object.</param>
        public IMappedObject GetObjectByGuid(Guid guid)
        {
            using (var tran = this.engine.GetTransaction()) {
                var row = tran.Select <byte[], string>(MappedObjectsGuidsTable, guid.ToByteArray());
                if (row.Exists)
                {
                    DbCustomSerializer <MappedObject> value = tran.Select <string, DbCustomSerializer <MappedObject> >(MappedObjectsTable, row.Value).Value;
                    if (value != null)
                    {
                        MappedObject data = value.Get;

                        if (data == null)
                        {
                            return(null);
                        }

                        return(new MappedObject(data));
                    }
                }
            }

            return(null);
        }
Example #26
0
        public void ContentChangeIndicatesFolderMove()
        {
            // Moves /a/b to /b
            string rootFolderId = "rootId";
            string folderAName  = "a";
            string folderAId    = "aid";
            string folderBName  = "b";
            string folderBId    = "bid";

            string lastChangeToken = "changeToken";

            Mock <IFileSystemInfoFactory> fsFactory = new Mock <IFileSystemInfoFactory>();
            var folderBInfo = fsFactory.AddDirectory(Path.Combine(this.localRoot, folderAName, folderBName));

            Mock <ISession> session = MockSessionUtil.GetSessionMockReturningFolderChange(DotCMIS.Enums.ChangeType.Updated, folderBId, folderBName, this.remoteRoot + "/" + folderBName, rootFolderId, lastChangeToken);

            session.SetupTypeSystem();

            var storage = this.GetInitializedStorage();

            storage.ChangeLogToken = "oldtoken";
            var mappedRootObject = new MappedObject("/", rootFolderId, MappedObjectType.Folder, null, storage.ChangeLogToken);

            storage.SaveMappedObject(mappedRootObject);
            var mappedAObject = new MappedObject(folderAName, folderAId, MappedObjectType.Folder, rootFolderId, storage.ChangeLogToken);

            storage.SaveMappedObject(mappedAObject);
            var mappedBObject = new MappedObject(folderBName, folderBId, MappedObjectType.Folder, folderAId, storage.ChangeLogToken);

            storage.SaveMappedObject(mappedBObject);

            var queue = this.CreateQueue(session, storage, fsFactory.Object);

            queue.RunStartSyncEvent();

            folderBInfo.Verify(d => d.MoveTo(Path.Combine(this.localRoot, folderBName)), Times.Once());
        }
Example #27
0
        public void RemoteFolderChanged([Values(true, false)] bool childrenAreIgnored)
        {
            DateTime creationDate    = DateTime.UtcNow;
            string   folderName      = "a";
            string   path            = Path.Combine(Path.GetTempPath(), folderName);
            string   id              = "id";
            string   parentId        = "papa";
            string   lastChangeToken = "token";
            string   newChangeToken  = "newToken";

            var dirInfo = new Mock <IDirectoryInfo>();

            dirInfo.Setup(d => d.FullName).Returns(path);
            dirInfo.Setup(d => d.Name).Returns(folderName);
            dirInfo.Setup(d => d.Parent).Returns(Mock.Of <IDirectoryInfo>());

            var mappedObject = new MappedObject(
                folderName,
                id,
                MappedObjectType.Folder,
                parentId,
                lastChangeToken)
            {
                Guid = Guid.NewGuid()
            };

            this.storage.AddMappedFolder(mappedObject);

            Mock <IFolder> remoteObject = MockOfIFolderUtil.CreateRemoteFolderMock(id, folderName, path, parentId, newChangeToken, childrenAreIgnored);

            remoteObject.Setup(f => f.LastModificationDate).Returns((DateTime?)creationDate);

            this.underTest.Solve(dirInfo.Object, remoteObject.Object);

            this.storage.VerifySavedMappedObject(MappedObjectType.Folder, id, folderName, parentId, newChangeToken, ignored: childrenAreIgnored);
            dirInfo.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(creationDate)), Times.Once());
        }
        private void SetupOldMappedObject(bool isFolder)
        {
            var mappedObject = new MappedObject(
                this.oldName,
                this.remoteObjectId,
                isFolder ? MappedObjectType.Folder : MappedObjectType.File,
                this.oldRemoteParentId,
                this.oldChangeToken)
            {
                Guid = this.localUuid,
                LastLocalWriteTimeUtc  = this.oldModification,
                LastRemoteWriteTimeUtc = this.oldModification,
                LastContentSize        = isFolder ? -1 : 0
            };

            if (isFolder)
            {
                this.storage.AddMappedFolder(mappedObject);
            }
            else
            {
                this.storage.AddMappedFile(mappedObject);
            }
        }
Example #29
0
        public MappedObject GetMapping(String entityType, Int32 id)
        {
            entityType = entityType.ToLowerInvariant();

            MappedObject map = null;

            using (SqlConnection connection = new SqlConnection(DB.GetDBConn()))
            {
                connection.Open();

                IDataReader reader = DB.GetRS("dbo.aspdnsf_GetMappedObject @StoreId = {0}, @EntityType = {1}, @EntityID = {2}".FormatWith(this.StoreID, entityType.DBQuote(), id), connection);
                while (reader.Read())
                {
                    map          = new MappedObject();
                    map.ID       = reader.FieldInt("ID");
                    map.StoreID  = this.StoreID;
                    map.Type     = reader.Field("EntityType");
                    map.Name     = reader.Field("Name");
                    map.IsMapped = reader.FieldBool("Mapped");
                }
            }

            return(map);
        }
        public void LocalFolderMoved([Values(true, false)] bool childrenAreIgnored)
        {
            this.SetUpMocks();
            string folderName = "name";
            var    dir        = Mock.Of <IDirectoryInfo>(
                d =>
                d.FullName == Path.Combine(Path.GetTempPath(), this.newParentsName, folderName) &&
                d.Name == folderName &&
                d.Parent.Uuid == this.parentUuid);
            var folder = MockOfIFolderUtil.CreateRemoteFolderMock(this.remoteObjectId, folderName, "path", this.oldParentsId, ignored: childrenAreIgnored);

            folder.Setup(d => d.Move(It.IsAny <IObjectId>(), It.IsAny <IObjectId>())).Returns(folder.Object);
            var obj = new MappedObject(folderName, this.remoteObjectId, MappedObjectType.Folder, this.oldParentsId, this.changeToken)
            {
                Guid = Guid.NewGuid()
            };

            this.storage.AddMappedFolder(obj);
            this.underTest.Solve(dir, folder.Object, ContentChangeType.NONE, ContentChangeType.NONE);
            this.storage.VerifySavedMappedObject(MappedObjectType.Folder, this.remoteObjectId, folderName, this.newParentsId, this.changeToken, ignored: childrenAreIgnored);
            folder.Verify(d => d.Move(It.Is <IObjectId>(o => o.Id == this.oldParentsId), It.Is <IObjectId>(o => o.Id == this.newParentsId)));
            this.changeSolver.Verify(s => s.Solve(dir, folder.Object, ContentChangeType.NONE, ContentChangeType.NONE), Times.Once());
            this.renameSolver.Verify(s => s.Solve(It.IsAny <IFileSystemInfo>(), It.IsAny <IObjectId>(), It.IsAny <ContentChangeType>(), It.IsAny <ContentChangeType>()), Times.Never);
        }