Beispiel #1
0
        /// <summary>
        ///     Downloads the pdbs from the symbol server.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="symbolServer">The symbol server name.</param>
        /// <param name="downloadDir">The download directory. Can be null.</param>
        /// <returns>
        ///     true if all symbols could be downloaded. False otherwise.
        /// </returns>
        public bool DownloadPdbs(FileQuery query, string symbolServer, string downloadDir)
        {
            using (var t = new Tracer(myType, "DownloadPdbs"))
            {
                var lret             = SymChkExecutor.bCanStartSymChk;
                var currentFailCount = this.FailedPdbs.Count;

                var fileQueue  = query.EnumerateFiles;
                var aggregator = new BlockingQueueAggregator <string>(fileQueue);

                Action <string> downLoadPdbThread = (string fileName) =>
                {
                    var pdbFileName = GetPdbNameFromBinaryName(fileName);

                    // delete old pdb to ensure that the new matching pdb is really downloaded. Symchk does not replace existing but not matching pdbs.
                    try
                    {
                        File.Delete(pdbFileName);
                    }
                    catch
                    {
                    }

                    if (!this.Executor.DownLoadPdb(fileName, symbolServer, downloadDir))
                    {
                        lock (this.FailedPdbs)
                        {
                            this.FailedPdbs.Add(Path.GetFileName(fileName));
                        }
                    }
                    else
                    {
                        lock (this.FailedPdbs)
                        {
                            this.SucceededPdbCount++;
                        }
                    }
                };

                var dispatcher = new WorkItemDispatcher <string>(this.myDownLoadThreadCount, downLoadPdbThread, "Pdb Downloader", aggregator, WorkItemOptions.AggregateExceptions);

                try
                {
                    dispatcher.Dispose();
                }
                catch (AggregateException ex)
                {
                    t.Error(ex, "Got error during pdb download");
                    lret = false;
                }

                if (this.FailedPdbs.Count > currentFailCount)
                {
                    t.Warning("The failed pdb count has increased by {0}", this.FailedPdbs.Count - currentFailCount);
                    lret = false;
                }

                return(lret);
            }
        }
Beispiel #2
0
        public AnalysisResult Analyze(string previousAssembly, string currentAssembly, string proposedVersionNumber)
        {
            var differ = new DiffAssemblies();

            var previous = new FileQuery(previousAssembly);
            var current  = new FileQuery(currentAssembly);

            var differences = differ.Execute(new List <FileQuery>
            {
                previous
            },
                                             new List <FileQuery>
            {
                current
            });

            var rule = new BreakingChangeRule();

            var breakingChange = rule.Detect(differences);

            if (breakingChange)
            {
                var semVer = SemVersion.Parse(proposedVersionNumber);

                var decidedVersionNumber = semVer.Change(semVer.Major + 1, 0, 0);

                proposedVersionNumber = decidedVersionNumber.ToString();
            }

            return(new AnalysisResult
            {
                BreakingChangesDetected = breakingChange,
                VersionNumber = proposedVersionNumber
            });
        }
Beispiel #3
0
        // ----------

        IList <string> BuildSqlQueries(FileQuery query)
        {
            // Entities
            // ----------------------

            var q1 = new StringBuilder();

            q1.Append("SELECT f.Id, 0 AS [Rank] FROM ")
            .Append("{prefix}_Files")
            .Append(" f WHERE (");
            if (!string.IsNullOrEmpty(query.Builder.Where))
            {
                q1.Append("(").Append(query.Builder.Where).Append(") AND ");
            }
            q1.Append("(")
            .Append(query.Params.Keywords.ToSqlString("f.[Name]", "Keywords"))
            .Append(" OR ")
            .Append(query.Params.Keywords.ToSqlString("f.Extension", "Keywords"))
            .Append("));");

            // Return queries
            return(new List <string>()
            {
                q1.ToString()
            });
        }
        public async Task <QueryResult <FileMetadata> > GetFiles(FileQuery query, string rootFolderId, GoogleCredentials googleCredentials, CancellationToken cancellationToken)
        {
            var fullDriveService = CreateDriveServiceAndCredentials(googleCredentials);
            var driveService     = fullDriveService.Item1;

            var result = new QueryResult <FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                try
                {
                    _logger.Debug("Getting files with id {0}", query.Id);

                    var file = await GetFile(query.Id, driveService, cancellationToken).ConfigureAwait(false);

                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFileMetadata).ToArray();
                }
                catch (FileNotFoundException)
                { }

                return(result);
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                _logger.Debug("Getting files with path {0}", string.Join("/", query.FullPath));

                var name      = query.FullPath.Last();
                var pathParts = query.FullPath.Take(query.FullPath.Length - 1).ToArray();

                try
                {
                    var parentId = await FindOrCreateParent(driveService, pathParts, rootFolderId, cancellationToken)
                                   .ConfigureAwait(false);

                    var file = await FindFileId(name, parentId, driveService, cancellationToken).ConfigureAwait(false);

                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFileMetadata).ToArray();
                }
                catch (FileNotFoundException)
                { }

                return(result);
            }

            _logger.Debug("Getting all files");

            var queryResult = await GetFiles(null, driveService, cancellationToken).ConfigureAwait(false);

            var files = queryResult
                        .Select(GetFileMetadata)
                        .ToArray();

            result.Items            = files;
            result.TotalRecordCount = files.Length;

            return(result);
        }
Beispiel #5
0
        public void TestImagePathVariants()
        {
            IFileServer server1 = new FileServerAzure("/Uploads/", "http://www.testdomain.com", null, AzureBucket);
            IFileQuery  file1   = new FileQuery("Awesome.jpg", "Images");

            IFileServer server2 = new FileServerAzure("/Uploads/", "http://www.anotherdomain.com", null, AzureBucket);
            IFileQuery  file2   = new FileQuery("Coolness.png", "ExPhotoImageFile", "/");

            string strURL, strLocalRelativePath, strPhysicalPath, strBasePath, strCDNPath;
            bool   blnExistsLocal = false;

            Model.URL.URLCheckExistsResult enuExistsRemote = Model.URL.URLCheckExistsResult.Unknown;
            // Assert
            strURL               = server1.GetLocalURL(file1);
            strPhysicalPath      = server1.GetLocalDiskPath(file1);
            strLocalRelativePath = server1.GetLocalRelativePath(file1);
            strBasePath          = server1.GetBasePath(file1);
            strCDNPath           = server1.GetCDNPath(file1, true);
            blnExistsLocal       = server1.FileExistsLocal(file1);
            enuExistsRemote      = server1.FileExistsLocal_HTTPCheck(file1);

            Assert.IsNotNull(strURL);
            Assert.AreEqual(strURL, "http://www.testdomain.com/Uploads/Images/Awesome.jpg");
            Assert.IsNotNull(strPhysicalPath);
            Assert.IsNotNull(strLocalRelativePath);
            Assert.IsNotNull(strBasePath);
            Assert.IsNotNull(strCDNPath);
            Assert.IsTrue(Uri.IsWellFormedUriString(strURL, UriKind.Absolute));
            Assert.IsTrue(strPhysicalPath.IndexOfAny(System.IO.Path.GetInvalidPathChars()) == -1);
            Assert.IsTrue(Uri.IsWellFormedUriString(strLocalRelativePath, UriKind.Relative));
            Assert.IsTrue(Uri.IsWellFormedUriString(strBasePath, UriKind.Relative));
            Assert.IsTrue(Uri.IsWellFormedUriString(strCDNPath, UriKind.Relative));
            Assert.IsTrue(Model.URL.IsValid(strURL));
            //Assert.IsTrue(enuExistsRemote == General.Model.URL.URLCheckExistsResult.Exists);

            strURL               = server2.GetLocalURL(file2);
            strPhysicalPath      = server2.GetLocalDiskPath(file2);
            strLocalRelativePath = server2.GetLocalRelativePath(file2);
            strBasePath          = server2.GetBasePath(file2);
            strCDNPath           = server1.GetCDNPath(file1, true);
            blnExistsLocal       = server2.FileExistsLocal(file2);
            enuExistsRemote      = server2.FileExistsLocal_HTTPCheck(file2);

            Assert.IsNotNull(strURL);
            Assert.AreEqual(strURL, "http://www.anotherdomain.com/Uploads/ExPhotoImageFile/Coolness.png");
            Assert.IsNotNull(strPhysicalPath);
            Assert.IsNotNull(strLocalRelativePath);
            Assert.IsNotNull(strBasePath);
            Assert.IsNotNull(strCDNPath);
            Assert.IsTrue(Uri.IsWellFormedUriString(strURL, UriKind.Absolute));
            Assert.IsTrue(strPhysicalPath.IndexOfAny(System.IO.Path.GetInvalidPathChars()) == -1);
            Assert.IsTrue(Uri.IsWellFormedUriString(strLocalRelativePath, UriKind.Relative));
            Assert.IsTrue(Uri.IsWellFormedUriString(strBasePath, UriKind.Relative));
            Assert.IsTrue(Uri.IsWellFormedUriString(strCDNPath, UriKind.Relative));
            Assert.IsTrue(Model.URL.IsValid(strURL));
            //Assert.IsTrue(enuExistsRemote == General.Model.URL.URLCheckExistsResult.Exists);

            //This should not exist because it's the wrong server for the file.
            //Assert.IsTrue(server2.FileExistsLocal_HTTPCheck(file1) == General.Model.URL.URLCheckExistsResult.DoesNotExist);
        }
        public Task <QueryResult <FileMetadata> > GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var googleCredentials = GetGoogleCredentials(target);
            var syncAccount       = _configurationRetriever.GetSyncAccount(target.Id);

            return(_googleDriveService.GetFiles(query, syncAccount.FolderId, googleCredentials, cancellationToken));
        }
Beispiel #7
0
        public void OneDriveCase()
        {
            var fq      = new FileQuery();
            var results = fq.ExecuteAsync(@"C:\Users\adamo\OneDrive", "*.pptx").Result;

            Assert.IsTrue(results.Any());
        }
Beispiel #8
0
        public void VisualStudioCase()
        {
            var fq      = new FileQuery();
            var results = fq.ExecuteAsync(@"C:\Users\adamo\Source\Repos", "*.sln", FileQuery.VisualStudioResult).Result;
            var array   = results.ToArray(); // just to avoid weird debugger complaining

            Assert.IsTrue(array.Any());
        }
Beispiel #9
0
        public void Can_Search_In_More_Than_One_Dir()
        {
            List <FileQuery> queries = FileQuery.ParseQueryList(@"%WINDIR%\*.exe;%COMSPEC%", null);

            Assert.AreEqual(2, queries.Count);
            Assert.Greater(queries[0].Files.Length, 10);
            Assert.AreEqual(1, queries[1].Files.Length);
        }
        public async Task<QueryResult<FileMetadata>> GetFiles(FileQuery query, string rootFolderId, GoogleCredentials googleCredentials,
            CancellationToken cancellationToken)
        {
            var fullDriveService = CreateDriveServiceAndCredentials(googleCredentials);
            var driveService = fullDriveService.Item1;

            var result = new QueryResult<FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                try
                {
                    var file = await GetFile(query.Id, driveService, cancellationToken).ConfigureAwait(false);

                    result.TotalRecordCount = 1;
                    result.Items = new[] { file }.Select(GetFileMetadata).ToArray();
                }
                catch (FileNotFoundException)
                {
                    
                }

                return result;
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var name = query.FullPath.Last();
                var pathParts = query.FullPath.Take(query.FullPath.Length - 1).ToArray();

                try
                {
                    var parentId = await FindOrCreateParent(driveService, false, pathParts, rootFolderId, cancellationToken)
                                .ConfigureAwait(false);

                    var file = await FindFileId(name, parentId, driveService, cancellationToken).ConfigureAwait(false);

                    result.TotalRecordCount = 1;
                    result.Items = new[] { file }.Select(GetFileMetadata).ToArray();
                }
                catch (FileNotFoundException)
                {

                }

                return result;
            }

            var queryResult = await GetFiles(null, driveService, cancellationToken).ConfigureAwait(false);
            var files = queryResult
                .Select(GetFileMetadata)
                .ToArray();

            result.Items = files;
            result.TotalRecordCount = files.Length;

            return result;
        }
Beispiel #11
0
        public Task <QueryResult <FileMetadata> > GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                          .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult <FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                var file = _fileSystem.GetFileSystemInfo(query.Id);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFile).ToArray();
                }

                return(Task.FromResult(result));
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var fullPath = GetFullPath(query.FullPath, target);
                var file     = _fileSystem.GetFileSystemInfo(fullPath);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFile).ToArray();
                }

                return(Task.FromResult(result));
            }

            FileMetadata[] files;

            try
            {
                files = _fileSystem.GetFiles(account.Path, true)
                        .Select(GetFile)
                        .ToArray();
            }
            catch (DirectoryNotFoundException)
            {
                files = new FileMetadata[] { };
            }

            result.Items            = files;
            result.TotalRecordCount = files.Length;

            return(Task.FromResult(result));
        }
        public void WhenICompareTheTwoSetsOfAssemblies()
        {
            var differ = new DiffAssemblies();

            var previousAssemblies = FileQuery.ParseQueryList(ScenarioContext.Current.Get <string>("PreviousAssembliesQuery"));
            var newAssemblies      = FileQuery.ParseQueryList(ScenarioContext.Current.Get <string>("NewAssembliesQuery"));

            var differences = differ.Execute(previousAssemblies, newAssemblies);

            ScenarioContext.Current.Set(differences, "Results");
        }
Beispiel #13
0
        public MainWindow(
            MainWindowView viewModel,
            SettingsManager <MainWindowSettings> settingsManager,
            FileQuery fileQuery)
        {
            InitializeComponent();

            _viewModel       = viewModel;
            _settingsManager = settingsManager;
            _fileQuery       = fileQuery;
        }
Beispiel #14
0
        /// <summary>
        /// Retrieves number of files matching query.
        /// </summary>
        /// <param name="query">The query filter to use.</param>
        /// <param name="token">Optional cancellation token to use.</param>
        /// <returns>Number of files matching given filters and optional cursor</returns>
        public async Task <Int32> AggregateAsync(FileQuery query, CancellationToken token = default)
        {
            if (query is null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var req = Oryx.Cognite.Files.aggregate <Int32>(query);

            return(await RunAsync(req, token).ConfigureAwait(false));
        }
        public FileQueryTests()
        {
            _workDirectory = Path.Combine(Directory.GetCurrentDirectory(), _directoryName);
            DirectoryInfo directoryInfo = new DirectoryInfo(_workDirectory);
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }

            _fileQuery = new FileQuery(_workDirectory);
        }
        private async Task <QueryResult <FileMetadata> > TryGetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var syncAccount = _configurationRetriever.GetSyncAccount(target.Id);
            var path        = FindPathFromFileQuery(query, target);

            if (string.IsNullOrEmpty(path))
            {
                return(await FindFilesMetadata(syncAccount.AccessToken, cancellationToken));
            }

            return(await FindFileMetadata(path, syncAccount.AccessToken, cancellationToken));
        }
Beispiel #17
0
        public async Task TestWriteImagesLocal()
        {
            string strTulipsPath = TestContent.GetContentFilePhysicalPath("/Images/Tulips.jpg");

            IFileServer server1 = new FileServerLocal("Temp", "");
            IFileQuery  file1   = new FileQuery("Tulips.jpg", "SiteImageFile");

            for (int i = 0; i < 100; i++)
            {
                server1.StoreImage(strTulipsPath, file1);
                Assert.IsTrue(server1.FileExistsLocal(file1));
                server1.Delete(file1);
                System.Threading.Thread.Sleep(5); //It seems like Delete returns before the delete is known by the file system, here's some buffer.
                Assert.IsFalse(server1.FileExistsLocal(file1));
            }

            for (int i = 0; i < 100; i++)
            {
                var   tskStore = server1.StoreImageAsync(strTulipsPath, file1);
                await tskStore;
                Assert.IsTrue(server1.FileExistsLocal(file1));
                var   tskDelete = server1.DeleteAsync(file1);
                await tskDelete;
                System.Threading.Thread.Sleep(5); //It seems like Delete returns before the delete is known by the file system, here's some buffer.
                Assert.IsFalse(server1.FileExistsLocal(file1));
            }
            Assert.IsFalse(server1.FileExistsLocal(file1));

            IFileQuery file2 = new FileQuery("TulipsFromImage.jpg", "SiteImageFile");
            IFileQuery file3 = new FileQuery("TulipsFromStream.jpg", "SiteImageFile");
            IFileQuery file4 = new FileQuery("TulipsFromImageWithTypeChange.png", "SiteImageFile");

            //Test System.Drawing.Image
            using (System.Drawing.Image objImage = System.Drawing.Image.FromFile(strTulipsPath))
            {
                await server1.StoreImageAsync(objImage, file2);
            }
            Assert.IsTrue(server1.FileExistsLocal(file2));

            //Test System.Stream
            using (System.IO.Stream stmImage = new System.IO.FileStream(strTulipsPath, System.IO.FileMode.Open))
            {
                await server1.StoreImageAsync(stmImage, file3, System.Drawing.Imaging.ImageFormat.Jpeg);

                stmImage.Close();
            }
            Assert.IsTrue(server1.FileExistsLocal(file3));

            await server1.StoreImageAsync(System.Drawing.Image.FromFile(strTulipsPath), file4, System.Drawing.Imaging.ImageFormat.Png);

            Assert.IsTrue(server1.FileExistsLocal(file4));
        }
        public void Insert(Widget entity)
        {
            DirectoryData directoryData = new DirectoryData(entity.Id, entity.Name);

            _directoryQuery.Insert(directoryData);

            _fileQuery = new FileQuery(directoryData.Id);
            foreach (WidgetData widgetData in entity.Data)
            {
                FileData fileData = new FileData(widgetData.Id, widgetData.Name, Convert.ToString(widgetData.Data));
                _fileQuery.Insert(fileData);
            }
        }
        private string FindPathFromFileQuery(FileQuery query, SyncTarget target)
        {
            if (!string.IsNullOrEmpty(query.Id))
            {
                return(query.Id);
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                return(GetFullPath(query.FullPath, target));
            }

            return(string.Empty);
        }
Beispiel #20
0
        public async Task <List <FileQueryModel> > HandleAsync(FileQuery query)
        {
            var files = await _context.File
                        .Where(t => t.SidebarContentFile.Any(x => x.SidebarContentId == query.Id))
                        .Select(t => new FileQueryModel
            {
                Id          = t.Id,
                Name        = t.Name,
                ContentType = t.ContentType,
                Data        = t.Data
            })
                        .ToListAsync();

            return(files);
        }
Beispiel #21
0
        public void InPath_WithFilesInPath_ReturnsAllFilesInPath()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
            {
                { @"C:\test\1.txt", MockFileData.NullObject },
                { @"C:\test\2.txt", MockFileData.NullObject },
                { @"C:\test\3.txt", MockFileData.NullObject }
            });

            var files = new FileQuery(mockFileSystem)
                        .InPath(@"C:\test\")
                        .Find();

            Assert.That(files, Is.EqualTo(mockFileSystem.AllFiles.ToList()));
        }
Beispiel #22
0
        void AddQuery(List <FileQuery> fileQuery, CommandData cmdArgs, List <string> hookCmd)
        {
            if (hookCmd.Count == 0)
            {
                return;
            }
            else if (hookCmd.Count > 1)
            {
                cmdArgs.InvalidComandLineSwitch =
                    String.Format("Unexpected file query parameter: {0}. Hint: Multiple file queries must be separated with ; as separator.", hookCmd[1]);
                return;
            }

            fileQuery.AddRange(FileQuery.ParseQueryList(ExpandDefaultFileQueries(hookCmd[0])));
        }
Beispiel #23
0
        public void ReadMscorlibAssembly()
        {
            string         mscorlib = new FileQuery("GAC:\\mscorlib.dll").Files.Single();
            CorFlagsReader data     = null;

            using (var fStream = new FileStream(mscorlib, FileMode.Open, FileAccess.Read))
            {
                data = CorFlagsReader.ReadAssemblyMetadata(fStream);
            }
            Assert.IsNotNull(data);
            Assert.IsTrue(data.IsPureIL);
            Assert.IsTrue(data.IsSigned);
            Assert.AreEqual(ProcessorArchitecture.X86, data.ProcessorArchitecture);
            Assert.IsTrue(data.MajorRuntimeVersion >= 2);
        }
        public void WhenICompareTheTwoAssemblies()
        {
            var differ = new DiffAssemblies();

            var previous    = new FileQuery(ScenarioContext.Current.Get <string>("PreviousAssembly"));
            var newAssembly = new FileQuery(ScenarioContext.Current.Get <string>("NewAssembly"));

            var differences = differ.Execute(new List <FileQuery> {
                previous
            }, new List <FileQuery> {
                newAssembly
            });

            ScenarioContext.Current.Set(differences, "Results");
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            var paths = new List <string>
            {
                @"C:\temp\",
                @"C:\source\"
            };

            var files = new FileQuery()
                        .InPath(@"C:\temp\")
                        .WithExtension("sql")
                        .Find()
                        .ToList();

            var files2 = Directory.EnumerateFiles(@"C:\temp\", @"*.sql", SearchOption.AllDirectories);
        }
Beispiel #26
0
        public void When_No_Directory_Is_Given_Use_Cwd()
        {
            string cwd = Directory.GetCurrentDirectory();

            try
            {
                Directory.SetCurrentDirectory(Environment.GetEnvironmentVariable("WINDIR"));
                FileQuery query = new FileQuery("winhelp.exe");
                Assert.AreEqual(1, query.Files.Length);
                StringAssert.EndsWith("winhelp.exe", query.Files[0].ToLower());
            }
            finally
            {
                Directory.SetCurrentDirectory(cwd);
            }
        }
        public Widget Find(string id)
        {
            var directroyData = _directoryQuery.Find(id);

            Widget widget = new Widget(directroyData.Id, directroyData.Name);
            widget.Data = new List<WidgetData>();

            _fileQuery = new FileQuery(base.ContextString + @"/" + widget.Name);
            var fileDataList = _fileQuery.GetAll();
            foreach (var fileData in fileDataList)
            {
                WidgetData widgetData = new WidgetData(fileData.Id, fileData.Name, fileData.Data);
                widget.Data.Add(widgetData);
            }
            return widget;
        }
Beispiel #28
0
        public async Task <QueryResult <FileMetadata> > GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            try
            {
                return(await TryGetFiles(query, target, cancellationToken));
            }
            catch (HttpException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return(new QueryResult <FileMetadata>());
                }

                throw;
            }
        }
Beispiel #29
0
        public void WithExtension_NoFilesWithExtensionExists_ReturnsNoFiles()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
            {
                { @"C:\1.etc", MockFileData.NullObject },
                { @"C:\2.etc", MockFileData.NullObject },
                { @"C:\3.etc", MockFileData.NullObject }
            });

            var files = new FileQuery(mockFileSystem)
                        .InPath(@"C:\")
                        .WithExtension(".txt")
                        .Find();

            Assert.That(files, Is.EqualTo(mockFileSystem.AllFiles.Where(f => f.EndsWith(".txt")).ToList()));
        }
Beispiel #30
0
        public FileQuery ReadFile(int fileID)
        {
            if (fileID < 0 || fileID >= _files.Count)
            {
                return(new FileQuery());
            }

            var fileDesc  = _files[fileID];
            var fileQuery = new FileQuery
            {
                fileID  = fileID,
                name    = fileDesc.label,
                content = fileDesc.Read(),
            };

            return(fileQuery);
        }
Beispiel #31
0
        private async Task <QueryResult <FileMetadata> > TryGetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var oneDriveCredentials = CreateOneDriveCredentials(target);

            if (!string.IsNullOrEmpty(query.Id))
            {
                return(await GetFileById(query.Id, oneDriveCredentials, cancellationToken));
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var path = GetFullPath(query.FullPath);
                return(await GetFileByPath(path, oneDriveCredentials, cancellationToken));
            }

            return(await GetAllFiles(oneDriveCredentials, cancellationToken));
        }
Beispiel #32
0
        public void WhenICompareTheTwoAssembliesAndValidateTheRules()
        {
            var differ = new DiffAssemblies();

            var previous    = new FileQuery(ScenarioContext.Current.Get <string>("PreviousAssembly"));
            var newAssembly = new FileQuery(ScenarioContext.Current.Get <string>("NewAssembly"));

            var differences = differ.Execute(new List <FileQuery> {
                previous
            }, new List <FileQuery> {
                newAssembly
            });
            var rule = new BreakingChangeRule();

            var result = rule.Detect(differences);

            ScenarioContext.Current.Set(result, "Results");
        }
Beispiel #33
0
        public void Can_Search_In_Directories_Relative_To_Cwd()
        {
            string cwd = Directory.GetCurrentDirectory();

            try
            {
                Directory.SetCurrentDirectory(Environment.GetEnvironmentVariable("WINDIR"));

                FileQuery query = new FileQuery(@"system32\..\winhelp.exe");
                query.UseCwd = true;
                Assert.AreEqual(1, query.Files.Length, "Did not find winhelp.exe with a path relative to the current working directory");
                StringAssert.Contains("winhelp.exe", query.Files[0].ToLower(), "Wrong file returned");
            }
            finally
            {
                Directory.SetCurrentDirectory(cwd);
            }
        }
Beispiel #34
0
        public void InPaths_PathDoesNotExist_ThrowsDirectoryNotFoundException()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
            {
                { @"C:\test\1.txt", MockFileData.NullObject },
                { @"C:\test2\1.txt", MockFileData.NullObject },
            });

            Assert.Throws <DirectoryNotFoundException>(() =>
            {
                var files = new FileQuery(mockFileSystem)
                            .InPaths(new List <string>
                {
                    @"C:\test\",
                    @"C:\test3\"
                })
                            .Find();
            });
        }
        public IEnumerable<Widget> GetAll()
        {
            var directoryList = _directoryQuery.GetAll();
            List<Widget> widgets = new List<Widget>();
            foreach (var directoryData in directoryList)
            {
                Widget widget = new Widget(directoryData.Id, directoryData.Name);
                widget.Data = new List<WidgetData>();
                _fileQuery = new FileQuery(base.ContextString + "\\" + directoryData.Name);

                List<FileData> fileData = _fileQuery.GetAll();
                foreach(var file in fileData)
                {
                    widget.Data.Add( new WidgetData(file.Id, file.Name, file.Data));
                }

                widgets.Add(widget);
            }

            return widgets;
        }
        private async Task<QueryResult<FileMetadata>> TryGetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var syncAccount = _configurationRetriever.GetSyncAccount(target.Id);
            var path = FindPathFromFileQuery(query, target);

            if (string.IsNullOrEmpty(path))
            {
                return await FindFilesMetadata(syncAccount.AccessToken, cancellationToken);
            }

            return await FindFileMetadata(path, syncAccount.AccessToken, cancellationToken);
        }
Beispiel #37
0
        public Task<QueryResult<FileMetadata>> GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult<FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                var file = _fileSystem.GetFileSystemInfo(query.Id);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items = new[] { file }.Select(GetFile).ToArray();
                }

                return Task.FromResult(result);
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var file = _fileSystem.GetFileSystemInfo(query.FullPath[0]);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items = new[] { file }.Select(GetFile).ToArray();
                }

                return Task.FromResult(result);
            }

            var files = _fileSystem.GetFiles(account.Path, true)
                .Select(GetFile)
                .ToArray();

            result.Items = files;
            result.TotalRecordCount = files.Length;

            return Task.FromResult(result);
        }
 public FileSystemWidgetContext(string contextString)
     : base(contextString)
 {
     _fileQuery = new FileQuery(base.ContextString);
     _directoryQuery = new DirectoryQuery(base.ContextString);
 }
        private string FindPathFromFileQuery(FileQuery query, SyncTarget target)
        {
            if (!string.IsNullOrEmpty(query.Id))
            {
                return query.Id;
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                return GetFullPath(query.FullPath, target);
            }

            return string.Empty;
        }
        public Task<QueryResult<FileMetadata>> GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var googleCredentials = GetGoogleCredentials(target);
            var syncAccount = _configurationRetriever.GetSyncAccount(target.Id);

            return _googleDriveService.GetFiles(query, syncAccount.FolderId, googleCredentials, cancellationToken);
        }
        private async Task<QueryResult<FileMetadata>> TryGetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var oneDriveCredentials = CreateOneDriveCredentials(target);

            if (!string.IsNullOrEmpty(query.Id))
            {
                return await GetFileById(query.Id, oneDriveCredentials, cancellationToken);
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var path = GetFullPath(query.FullPath);
                return await GetFileByPath(path, oneDriveCredentials, cancellationToken);
            }

            return await GetAllFiles(oneDriveCredentials, cancellationToken);
        }
        public async Task<QueryResult<FileMetadata>> GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            try
            {
                return await TryGetFiles(query, target, cancellationToken);
            }
            catch (HttpException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return new QueryResult<FileMetadata>();
                }

                throw;
            }
        }