Exemplo n.º 1
0
        // POST: api/Directory
        public dynamic Post([FromBody] DirAction action)
        {
            action.SetType();
            switch (action.Type)
            {
            case ActionType.GetDrives:
                return(DirectoryManager.GetDrives());

            case ActionType.GetItems:
                return(DirectoryManager.GetDirItems(action.Path));

            case ActionType.CountFiles:
            {
                string[]    args    = action.Path.Split('|');
                FileCounter counter = new FileCounter(args[0], args[1]);
                string      start   = DirectoryManager.GetNextFolder(counter.Path, counter.LastPath);
                while (!DirectoryManager.CountFiles(start, ref counter))
                {
                    start = DirectoryManager.GetNextFolder(counter.Path, counter.LastPath);
                }
                counter.Done = (start.Length == 0);
                return(counter);
            }
            }
            return(null);
        }
        private void DoCountingWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var options = (UserOptions)doWorkEventArgs.Argument;
            var counter = new FileCounter(options, () => this.worker.CancellationPending, () => { doWorkEventArgs.Cancel = true; });

            doWorkEventArgs.Result = counter.StartTask();
        }
Exemplo n.º 3
0
        private Response HandleGetRatingsRequest(dynamic parameters)
        {
            string vsixId = parameters.id;
            var    rating = FileCounter.GetRating(vsixId, _configuration);

            return(Response.AsText("{\"rating\": " + rating.Item1 + ", \"count\": " + rating.Item2 + "}", "application/json"));
        }
Exemplo n.º 4
0
 public FileNameWriter(string fileName, Logger logger, FileCounter fileCounter)
 {
     _fileName        = fileName;
     _logger          = logger;
     _fileCounter     = fileCounter;
     _fileNameWritten = false;
 }
Exemplo n.º 5
0
        public IHttpActionResult UpdateVsixRating(string vsixId, [FromBody] string ratingString)
        {
            if (!float.TryParse(ratingString, out float rawRating))
            {
                return(BadRequest());
            }

            // Upperbound the rating
            float rating = Math.Min(5, Math.Max(0, rawRating));

            // Record the rating
            if (!FileCounter.SetRating(vsixId, rating, _configuration))
            {
                return(InternalServerError());
            }

            // Trigger a re-creation of the ATOM feed by touching the main file if possible
            var vsixFilePath = FileCounter.GetVsixFileFromId(vsixId, _configuration);

            if (vsixFilePath != null && File.Exists(vsixFilePath))
            {
                File.SetLastWriteTime(vsixFilePath, DateTime.Now);
            }

            // All ok
            return(Ok());
        }
Exemplo n.º 6
0
        private Response HandleDownloadRequest(dynamic parameters)
        {
            string vsixName     = HttpUtility.UrlDecode(parameters.vsix);
            string vsixId       = parameters.id;
            string vsixFilePath = Path.Combine(Environment.CurrentDirectory, _configuration.VsixStorageDirectory, vsixName);

            // Count the download
            bool refreshFile = FileCounter.SetDownloadCount(vsixId, _configuration);

            // Serve the requested VSIX file back to the caller
            Response fileResponse = null;
            var      vsixFile     = new FileStream(vsixFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);

            using (var response = new StreamResponse(() => vsixFile, "application/octet-stream"))
            {
                fileResponse = response.AsAttachment(vsixName);
            }

            // Re-process the file
            if (refreshFile && File.Exists(vsixFilePath))
            {
                // Schedule the ATOM feed to be re-created by touching the VSIX file in question
                File.SetLastWriteTime(vsixFilePath, DateTime.Now);
            }

            return(fileResponse);
        }
Exemplo n.º 7
0
        public IHttpActionResult GetVsixRating(string id)
        {
            var rating = FileCounter.GetRating(id, _configuration);

            var popularity = new PackagePopularity()
            {
                Rating = rating.Item1, Count = rating.Item2
            };

            return(Ok(popularity));
        }
Exemplo n.º 8
0
        private void btnKtIEInit_Click(object sender, EventArgs e)
        {
            string system        = "IE";
            string systemVersion = this.cbIEVersions.Text;
            string dirPath       = this.txtKtIEPath.Text.Trim();

            this.FileCounter = 0;
            //this.Invoke(
            this.txtKtIEInitLog.Text = string.Empty;
            ComputerInitHelper.InitFolderMd5(system, systemVersion, dirPath, dirPath, new InitFileMd5Delegate(InitIEFileMd5));
            this.txtKtIEInitLog.Text += "\r\n\r\n处理完毕!共" + FileCounter.ToString() + "文件!";
        }
Exemplo n.º 9
0
        public void ValidateDirectory_DirectoryIsValid_ReturnTrue()
        {
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(@"/test/");
            var counter = new FileCounter(fileSystem);

            string input  = @"/test/";
            bool   output = counter.ValidateDirectory(input);

            Assert.True(output);
        }
Exemplo n.º 10
0
        public void CalculateXmlFiles_1XmlFile_Return1()
        {
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(@"/test/");
            fileSystem.AddFile(@"/test/file.xml", new MockFileData("Test"));
            var counter = new FileCounter(fileSystem);

            string input  = @"/test/";
            int    output = counter.CalculateXmlFiles(input);

            Assert.Equal(1, output);
        }
Exemplo n.º 11
0
        public void ValidateDirectory_InputIsEmptyOrNull_InvalidDirectoryException()
        {
            var counter = new FileCounter(new MockFileSystem());

            try
            {
                string input = "";
                counter.ValidateDirectory(input);
            }
            catch (InvalidDirectoryException e)
            {
                Assert.Equal("Please select a directory", e.Message);
            }
        }
Exemplo n.º 12
0
 private void IOnCountFolder(FileCounter fileCounter)
 {
     if (fileCounter.FolderLocationFromDataPath.Equals("/Managed/") && fileCounter.Folders.Length != 39)
     {
         var folders = (string[])FoldersField.GetValue(fileCounter);
         Array.Resize(ref folders, 39);
         FoldersField.SetValue(fileCounter, folders);
     }
     else if (fileCounter.FolderLocationFromDataPath.Equals("/../") && fileCounter.Folders.Length != 2)
     {
         var folders = (string[])FoldersField.GetValue(fileCounter);
         Array.Resize(ref folders, 2);
         FoldersField.SetValue(fileCounter, folders);
     }
 }
Exemplo n.º 13
0
 private void IOnCountFolder(FileCounter fileCounter)
 {
     if (fileCounter.FolderLocationFromDataPath.Equals("/Managed/") && fileCounter.Folders.Length != 39)
     {
         var folders = FileCounter._folders;
         Array.Resize(ref folders, 39);
         folders = fileCounter.Folders;
     }
     else if (fileCounter.FolderLocationFromDataPath.Equals("/../") && fileCounter.Folders.Length != 2)
     {
         var folders = FileCounter._folders;
         Array.Resize(ref folders, 2);
         folders = fileCounter.Folders;
     }
 }
Exemplo n.º 14
0
        public IHttpActionResult Get(string vsixId, string vsixName)
        {
            string vsixFilePath = Path.Combine(_configuration.VsixStorageDirectory, vsixName);

            // Count the download
            bool refreshFile = FileCounter.SetDownloadCount(vsixId, _configuration);

            // Re-process the file
            if (refreshFile && File.Exists(vsixFilePath))
            {
                // Schedule the ATOM feed to be re-created by touching the VSIX file in question
                File.SetLastWriteTime(vsixFilePath, DateTime.Now);
            }

            return(new FileResult(vsixFilePath));
        }
Exemplo n.º 15
0
        public void ValidateDirectory_DirectoryDoesNotExist_InvalidDirectoryException()
        {
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(@"/test/");
            var counter = new FileCounter(fileSystem);

            try
            {
                string input = @"/invalid/";
                counter.ValidateDirectory(input);
            }
            catch (InvalidDirectoryException e)
            {
                Assert.Equal("Invalid directory", e.Message);
            }
        }
Exemplo n.º 16
0
        public MainForm()
        {
            InitializeComponent();
            b2b = new DirectoryMonitor(this, Paths.B2B_PATH);
            b2c = new DirectoryMonitor(this, Paths.B2C_PATH);
            initPrinters();
            initDataCards();
            Load += MainForm_ChangeSize;
            new Clock(this);

            FileCounter fileCounterStoreTno = new FileCounter(this, Paths.STORE_TNO);

            fileCounterStoreTno.loadViewStoreTnoDelayed();

            FileCounter fileCounterMaterials = new FileCounter(this, Paths.MATERIALS);

            fileCounterMaterials.loadViewMaterialsDelayed();

            log = new LaczeV5Log(this);
        }
Exemplo n.º 17
0
        private void AddExtensions(SyndicationItem item, IVsixPackage pkg)
        {
            var ns  = XNamespace.Get("http://schemas.microsoft.com/developer/vsx-syndication-schema/2010");
            var xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");

            // If enabled then fetch the download count for the file, otherwise don't specify it
            var dlCountElement = new XElement(ns + "DownloadCount", _configGallery.TrackDownloads
                                    ? (object)FileCounter.GetDownloadCount(pkg.Id, _configStorage)
                                    : new XAttribute(xsi + "nil", "true"));

            // Default is not set
            var ratingElement      = new XElement(ns + "Rating", new XAttribute(xsi + "nil", "true"));
            var ratingCountElement = new XElement(ns + "RatingCount", new XAttribute(xsi + "nil", "true"));

            // If ratings are enabled then attempt to resolve them
            if (_configGallery.TrackRatings)
            {
                // Only apply ratings if there are any
                var rating = FileCounter.GetRating(pkg.Id, _configStorage);
                if (rating != null && rating.Item2 > 0)
                {
                    ratingElement      = new XElement(ns + "Rating", rating.Item1);
                    ratingCountElement = new XElement(ns + "RatingCount", rating.Item2);
                }
            }

            var content = new XElement(ns + "Vsix",
                                       new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                       new XElement(ns + "Id", pkg.Id),
                                       new XElement(ns + "Version", pkg.Version),
                                       new XElement(ns + "References"),
                                       ratingElement,
                                       ratingCountElement,
                                       dlCountElement);

            using (var stringReader = new StringReader(content.ToString()))
                using (var reader = XmlReader.Create(stringReader))
                {
                    item.ElementExtensions.Add(reader);
                }
        }
Exemplo n.º 18
0
        private Response HandleSetRatingsRequest(dynamic parameters)
        {
            string vsixId = parameters.id;
            float  rawRating;

            if (!float.TryParse(Request.Body.AsString(), out rawRating))
            {
                return new Response {
                           StatusCode = HttpStatusCode.BadRequest
                }
            }
            ;

            // Upperbound the rating
            float rating = Math.Min(5, Math.Max(0, rawRating));

            // Record the rating
            if (!FileCounter.SetRating(vsixId, rating, _configuration))
            {
                return new Response {
                           StatusCode = HttpStatusCode.InternalServerError
                }
            }
            ;

            // Trigger a re-creation of the ATOM feed by touching the main file if possible
            var vsixFilePath = FileCounter.GetVsixFileFromId(vsixId, _configuration);

            if (vsixFilePath != null && File.Exists(vsixFilePath))
            {
                File.SetLastWriteTime(vsixFilePath, DateTime.Now);
            }

            // All ok
            return(new Response {
                StatusCode = HttpStatusCode.OK
            });
        }
    }
}
Exemplo n.º 19
0
        private static void Main()
        {
            Logger         logger;
            IConfiguration appConfiguration;
            IConfiguration searchConfiguration;

            try
            {
                appConfiguration = GetConfiguration();

                string configurationName = DisplayAndChooseConfiguration(appConfiguration);

                logger = SetupLogger(configurationName);

                searchConfiguration = GetSearchConfiguration(appConfiguration, configurationName);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadLine();

                return;
            }

            try
            {
                Regex[]    fileExcludePatterns = GetFileExcludePatterns(searchConfiguration);
                Regex[]    fileIncludePatterns = GetFileIncludePatterns(searchConfiguration);
                Regex[]    excludePatterns     = GetExcludePatterns(searchConfiguration);
                string[]   itemsToSearch       = GetItemsToSearch(searchConfiguration);
                MapResults mapResults          = new MapResults();
                ICollection <ICollection <MapPattern> > mapChains = GetMapChains(searchConfiguration, mapResults);

                IEnumerable <string> files = Directory
                                             .EnumerateFiles(appConfiguration["searchRoot"],
                                                             "*",
                                                             SearchOption.AllDirectories
                                                             )
                                             .Where(file =>
                                                    fileExcludePatterns.All(pattern => !pattern.IsMatch(file)) ||
                                                    fileIncludePatterns.Any(pattern => pattern.IsMatch(file))
                                                    );

                int         foundItemCount = 0;
                FileCounter fileCounter    = new FileCounter();

                Parallel.ForEach(
                    files,
                    (file, state) =>
                {
                    FileNameWriter fileNameWriter = new FileNameWriter(file, logger, fileCounter);

                    bool somethingReplaced = false;

                    string[] fileLines = File.ReadAllLines(file);

                    for (int lineIndex = 0; lineIndex < fileLines.Length; lineIndex++)
                    {
                        string fileLine = fileLines[lineIndex];

                        string currentLine = fileLine;

                        if (string.IsNullOrEmpty(currentLine))
                        {
                            continue;
                        }

                        if (itemsToSearch
                            .All(itemToSearch => !currentLine.Contains(itemToSearch, StringComparison.OrdinalIgnoreCase)))
                        {
                            continue;
                        }

                        for (int index = 0; index < excludePatterns.Length; index++)
                        {
                            Regex excludePattern = excludePatterns[index];
                            currentLine          = excludePattern.Replace(currentLine, string.Empty);
                        }

                        for (int index = 0; index < excludePatterns.Length; index++)
                        {
                            Regex excludePattern = excludePatterns[index];
                            currentLine          = excludePattern.Replace(currentLine, string.Empty);
                        }

                        if (itemsToSearch
                            .All(itemToSearch => !currentLine.Contains(itemToSearch, StringComparison.OrdinalIgnoreCase)))
                        {
                            continue;
                        }

                        fileNameWriter.Write();
                        logger.Information($"    {lineIndex} {fileLine}");

                        ++foundItemCount;

                        foreach (ICollection <MapPattern> mapChain in mapChains)
                        {
                            string processingLine = fileLine;
                            foreach (MapPattern mapPattern in mapChain)
                            {
                                (string outputLine, bool replaceOrigin) = mapPattern.Process(processingLine);

                                processingLine = outputLine;

                                if (replaceOrigin)
                                {
                                    logger.Information("Replaced with:");
                                    logger.Information($"    {lineIndex} {processingLine}");
                                    fileLines[lineIndex] = processingLine;
                                    somethingReplaced    = true;
                                }
                            }
                        }
                    }

                    if (somethingReplaced)
                    {
                        File.WriteAllLines(file, fileLines);
                    }

                    Console.WriteLine($"'{file}' has been processed");
                }
                    );

                logger.Information($"Found: {foundItemCount} items in {fileCounter.Count} files");

                foreach ((string FileName, ICollection <string> Values)mapResult
                         in mapResults
                         .GetFiles()
                         .Select(fileName => (FileName: fileName, Results: mapResults.GetResults(fileName)))
                         )
                {
                    ICollection <string> collection = mapResult.Values;

                    if (!collection.Any())
                    {
                        continue;
                    }

                    logger.Information(string.Empty);
                    logger.Information($"Results for output '{mapResult.FileName}':");
                    foreach (string item in collection)
                    {
                        logger.Information(item);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(e.ToString());
                Console.ReadLine();
            }

            logger.Information(string.Empty);
            logger.Information("Done");
        }
Exemplo n.º 20
0
        private void AddPackages(SyndicationFeed feed,
                                 Uri root,
                                 string rootStoragePath,
                                 IEnumerable <IVsixPackage> packages)
        {
            // See https://msdn.microsoft.com/en-us/library/hh266717.aspx
            var items = new List <SyndicationItem>();

            var orderedPackages = packages
                                  .OrderBy(pkg => pkg.DisplayName)
                                  .ThenBy(pkg => pkg.Id)
                                  .ToArray();

            OnBackgroundProgress(new VsixFeedBuilderProgressArgs(0, orderedPackages.Length, "Starting"));

            for (var pkgIdx = 0; pkgIdx < orderedPackages.Length; pkgIdx++)
            {
                var pkg = orderedPackages[pkgIdx];

                // Possibly normalize the file name for the package,
                // visual studio does not like special characters in the file download urls so it is best to clear these out
                pkg.File = FileCleaner.NormalizePackageFileName(pkg.File);
                var pkgFileName = Path.GetFileName(pkg.File);

                OnBackgroundProgress(new VsixFeedBuilderProgressArgs(pkgIdx + 1, orderedPackages.Length, pkgFileName));

                // Schema: https://msdn.microsoft.com/en-us/library/dd393754(v=vs.100).aspx
                // Extension Schema: https://msdn.microsoft.com/en-us/library/dd393700(v=vs.100).aspx
                var item = new SyndicationItem
                {
                    Id              = pkg.Id,
                    Title           = new TextSyndicationContent(pkg.DisplayName),
                    Summary         = new TextSyndicationContent(pkg.Description),
                    PublishDate     = new DateTimeOffset(File.GetLastWriteTimeUtc(pkg.File)),
                    LastUpdatedTime = new DateTimeOffset(File.GetLastWriteTimeUtc(pkg.File))
                };

                // Create the subfolder for the package contents on the local system, ensure that the path exists
                var packageFolderPath = Path.Combine(rootStoragePath, pkg.Id);
                Directory.CreateDirectory(packageFolderPath);

                // Create a mapping between the vsix id and the file name by placing a simple file in the root
                FileCounter.SetIdToVsixFile(pkg.Id, pkgFileName, _configStorage);

                item.Authors.Add(new SyndicationPerson {
                    Name = pkg.Publisher
                });

                // If the configuration specifies that the downloads should be tracked then route the downloads
                // through the DownloadModule for tracking, if tracking is off then serve the static files directly
                // from the file-system
                item.Content = SyndicationContent.CreateUrlContent(_configGallery.TrackDownloads
                                                                   ? new Uri($"../api/download/{pkg.Id}/{pkgFileName}", UriKind.Relative)
                                                                   : root.MakeRelativeUri(new Uri(pkg.File)), "application/octet-stream");

                // Only use the first category found, the developer should put the most important category first anyways
                var category = pkg.Categories.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));
                if (category != null)
                {
                    item.Categories.Add(new SyndicationCategory(category.Trim().ToTitleCase()));
                }

                if (pkg.TrySaveIcon(packageFolderPath, out Uri iconUri))
                {
                    item.Links.Add(new SyndicationLink(root.MakeRelativeUri(iconUri), "icon", "", "", 0));
                }

                if (pkg.TrySavePreviewImage(packageFolderPath, out Uri previewUri))
                {
                    item.Links.Add(new SyndicationLink(root.MakeRelativeUri(previewUri), "previewimage", "", "", 0));
                }

                // Displays the "More Info" link if set
                if (pkg.MoreInfoUrl.IsUrl())
                {
                    item.Links.Add(new SyndicationLink(new Uri(pkg.MoreInfoUrl), "alternate", "", "", 0)); // Must be set to "alternate", rest does not need to be set
                }
                // Displays the "Release Notes" link if set
                if (pkg.ReleaseNotes.IsUrl())
                {
                    item.Links.Add(new SyndicationLink(new Uri(pkg.ReleaseNotes), "releasenotes", "", "", 0));
                }

                // Add the extensions to the item
                AddExtensions(item, pkg);

                // Now save the item
                items.Add(item);
            }
            OnBackgroundProgress(new VsixFeedBuilderProgressArgs(orderedPackages.Length, orderedPackages.Length, "All done"));

            // Save all the items into the feed object
            feed.Items = items;
        }
Exemplo n.º 21
0
 /// <summary>
 /// Counts the files of both directories of this job.
 /// </summary>
 /// <returns>The result of the counting of both directories of this job.</returns>
 public FileCountResult CountFiles()
 {
     return(FileCounter.CountFiles(this.DirectoryA) + FileCounter.CountFiles(this.DirectoryB));
 }
Exemplo n.º 22
0
 public Counter()
 {
     Directories = 0;
     Files       = new FileCounter();
 }         // constructor
Exemplo n.º 23
0
 void OnCountFolder(FileCounter fileCounter)
 {
     if (fileCounter.FolderLocationFromDataPath.Equals("/Managed/") && fileCounter.Folders.Length != 39)
     {
         var folders = (string[]) FoldersField.GetValue(fileCounter);
         Array.Resize(ref folders, 39);
         FoldersField.SetValue(fileCounter, folders);
     }
     else if (fileCounter.FolderLocationFromDataPath.Equals("/../") && fileCounter.Folders.Length != 2)
     {
         var folders = (string[])FoldersField.GetValue(fileCounter);
         Array.Resize(ref folders, 2);
         FoldersField.SetValue(fileCounter, folders);
     }
 }
Exemplo n.º 24
0
 private void DoCountingWork(object sender, DoWorkEventArgs doWorkEventArgs)
 {
     var options = (UserOptions)doWorkEventArgs.Argument;
     var counter = new FileCounter(options, () => this.worker.CancellationPending, () => { doWorkEventArgs.Cancel = true; });
     doWorkEventArgs.Result = counter.StartTask();
 }