Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            const string root = @"C:\Users\sp\Source\Repos\ChangeTracking\Source";
            var excluded = new[] { @"\obj", @"\bin", @"\Properties", ".vs", @"\packages" };

            Func<string, bool> isIncluded = (name) => excluded.All(e => !name.Contains(e));

            var path = new DirectoryInfo(root)
                .GetDirectories("*", SearchOption.AllDirectories)
                .Select(di => di.FullName)
                .Where(isIncluded)
                .SelectMany(Directory.GetFiles)
                .ToList();

            XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            var csproj = path.Where(p => Path.GetExtension(p) == ".csproj");
            var used = csproj
                .Select(XElement.Load)
                .Elements(ns + "ItemGroup")
                .Elements(ns + "Compile")
                .Attributes("Include")
                .Select(a => a.Value)
                .Where(isIncluded)
                .Select(Path.GetFileName);

            var cs = path
                .Where(p => Path.GetExtension(p) == ".cs")
                .Select(Path.GetFileName);

            var unused = cs.Except(used);
            unused.ToList().ForEach(Console.WriteLine);
        }
Ejemplo n.º 2
0
        public ReleasePackage ApplyDeltaPackage(ReleasePackage basePackage, ReleasePackage deltaPackage, string outputFile)
        {
            Contract.Requires(deltaPackage != null);
            Contract.Requires(!String.IsNullOrEmpty(outputFile) && !File.Exists(outputFile));

            string workingPath;
            string deltaPath;

            using (Utility.WithTempDirectory(out deltaPath))
            using (Utility.WithTempDirectory(out workingPath))
            using (var deltaZip = new ZipFile(deltaPackage.InputPackageFile))
            using (var baseZip = new ZipFile(basePackage.InputPackageFile)) {
                deltaZip.ExtractAll(deltaPath);
                baseZip.ExtractAll(workingPath);

                var pathsVisited = new List<string>();

                var deltaPathRelativePaths = new DirectoryInfo(deltaPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(deltaPath + Path.DirectorySeparatorChar, ""))
                    .ToArray();

                // Apply all of the .diff files
                deltaPathRelativePaths
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(file => {
                        pathsVisited.Add(Regex.Replace(file, @".diff$", "").ToLowerInvariant());
                        applyDiffToFile(deltaPath, file, workingPath);
                    });

                // Delete all of the files that were in the old package but
                // not in the new one.
                new DirectoryInfo(workingPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(workingPath + Path.DirectorySeparatorChar, "").ToLowerInvariant())
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase) && !pathsVisited.Contains(x))
                    .ForEach(x => {
                        this.Log().Info("{0} was in old package but not in new one, deleting", x);
                        File.Delete(Path.Combine(workingPath, x));
                    });

                // Update all the files that aren't in 'lib' with the delta
                // package's versions (i.e. the nuspec file, etc etc).
                deltaPathRelativePaths
                    .Where(x => !x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(x => {
                        this.Log().Info("Updating metadata file: {0}", x);
                        File.Copy(Path.Combine(deltaPath, x), Path.Combine(workingPath, x), true);
                    });

                using (var zf = new ZipFile(outputFile)) {
                    zf.AddDirectory(workingPath);
                    zf.Save();
                }
            }

            return new ReleasePackage(outputFile);
        }
Ejemplo n.º 3
0
        public void PreLoadAssembliesFromPath(string p)
        {
            //get all .dll files from the specified path and load the lot
            //you might not want recursion - handy for localised assemblies
            //though especially.
            var assemblyFiles = new DirectoryInfo(p).GetFiles("*.dll", SearchOption.AllDirectories);

            foreach (var assemblyName in assemblyFiles
                .Where(Settings.Filter)
                .Select(fi => fi.FullName)
                .Select(AssemblyName.GetAssemblyName)
                .Where(a => !AppDomain.CurrentDomain
                    .GetAssemblies()
                    .Any(assembly => AssemblyName.ReferenceMatchesDefinition(a, assembly.GetName()))))
            {
                //crucial - USE THE ASSEMBLY NAME.
                //in a web app, this assembly will automatically be bound from the
                //Asp.Net Temporary folder from where the site actually runs.
                try
                {
                    Assembly.Load(assemblyName);
                }
                catch (BadImageFormatException)
                {
                    //Debug.WriteLine(e); // TODO: just ignore this?
                }
            }
        }
		public UpdatePackagesStep UpdateNuspecAndAssemblyInfo()
		{
			var checkPackages =
				new DirectoryInfo(solutionSystemInfo.FolderPath)
					.GetFiles("AssemblyInfo.cs", SearchOption.AllDirectories)
					.Select(Packages.Parse)
					.Where(x => x != null && packagesId.Contains(x.Title))
					.GroupBy(x => x.Title)
					.ToDictionary(k => k.Key, v => new { Versions = v.Select(y => y.PackageVersion), Packages = v.Select(y => y) })
					.Where(x => x.Value.Packages.Any(y => y.HasNuget))
					.ToArray();

			var packagesWithDifferentVersions = checkPackages.Where(x => x.Value.Versions.Distinct().Count() > 1).ToArray();

			if (packagesWithDifferentVersions.Any())
			{
				ConsoleHelper.WriteLine("Packages with different versions to be fixed");

				return new UpdatePackagesStep();
			}

			var packages =
				checkPackages
					.OrderBy(x => x.Key)
					.Select(x => new PackageWithFramework(x.Key, x.Value.Versions.First(), x.Value.Packages))
					.ToArray();

			return new UpdatePackagesStep(solutionSystemInfo, buildAndRevision, packages, previousVersions);
		}
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            var options = new Options();
            Parser.Default.ParseArguments(args , options);
            //Get all forders from the current folder
            var rootFolder = options.RootFolder == "" ? Environment.CurrentDirectory : options.RootFolder;
            var folders = new DirectoryInfo(rootFolder).GetDirectories("*.*", SearchOption.AllDirectories);
            var stats = new List<CodeFile>();

            foreach (var d in folders.Where(d => !d.Name.StartsWith(".")))
            {
                //Check if there's a .git folder here and do a git pull if that is asked for
                //if (options.GitPull) GitPull(d);

                //Check if there's a .vbp file here.
                var vbpFiles = d.GetFiles().Where(f => f.Extension.ToLower() == ".vbp");

                //Get all referenced files from the .vbp
                foreach (var vbp in vbpFiles)
                {
                    var codeFiles = GetProjectFiles(vbp);
                    //Parse each file
                    foreach (var codeFile in codeFiles)
                    {
                        var code = new CodeFile(Path.Combine(d.FullName, codeFile));
                        code.Parse();
                        stats.Add(code);
                    }
                }
            }
            if(!string.IsNullOrEmpty(options.ResultFile))
            {
                if(!File.Exists(options.ResultFile))
                {
                    File.WriteAllText(options.ResultFile, "Date\tFiles\tLines\tComments\tMethods" + Environment.NewLine);
                }
                File.AppendAllText(options.ResultFile, string.Format("{0}\t{1}\t{2}\t{3}\t{4}" + Environment.NewLine,
                DateTime.Now,
                stats.Count(),
                stats.Sum(s => s.Lines),
                stats.Sum(c => c.Comments),
                stats.Sum(m => m.Methods)
                ));
            }
            //Present the result
            if (!options.Silent)
            {
                Console.WriteLine(string.Format("Files:{0} Lines:{1} Comments:{2} Methods:{3}",
                    stats.Count(),
                    stats.Sum(s => s.Lines),
                    stats.Sum(c => c.Comments),
                    stats.Sum(m => m.Methods)
                    ));
            }
        }
        public IEnumerable<DirectoryInfo> GetFolders(string folder, string[] filter)
        {
            var path = IOHelper.MapPath("~/" + folder.TrimStart('~', '/'));
            if (filter != null && filter[0] != ".")
            {
                IEnumerable<DirectoryInfo> dirs = new DirectoryInfo(path).EnumerateDirectories();
                return dirs.Where(d => d.EnumerateFiles().Where(f => filter.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)).Any());
            }

            return new DirectoryInfo(path).GetDirectories("*");
        }
Ejemplo n.º 7
0
 public override bool Run()
 {
     if (base.Run())
     {
         DebugInfo.Add("xbl generator");
         var directoryFiles = new DirectoryInfo(this.ApiOutputDirectory).GetFiles("*.xml").Where(f => !f.Name.StartsWith("_"));
         this.ProfileFile = directoryFiles.SingleOrDefault(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "profile")));
         this.GamesFile = directoryFiles.SingleOrDefault(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "games")));
         this.GameFiles = directoryFiles.Where(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "achievements-")));
         return true;
     }
     return false;
 }
Ejemplo n.º 8
0
        static int Main(string[] args)
        {
            var containerBuilder = new ContainerBuilder();

            var allAssemblies = new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.dll").Select(x => Assembly.LoadFile(x.FullName));
            var assemblies = allAssemblies.Where(x => x.GetTypes().Any(t => t.IsAssignableTo<RxDemoModule>())).ToArray();

            containerBuilder.RegisterAssemblyModules(assemblies);

            var container = containerBuilder.Build();


            new MainWindow(container.Resolve<IList<IDemo>>()).ShowDialog();
            return 0;
        }
Ejemplo n.º 9
0
        public Tile[,] ArtBuilder(string path)
        {
            var folderPath = path.ToMapPath();
            var images = new DirectoryInfo(folderPath).GetFiles().OnlyImages();
            var config = ConfigService.Generate(folderPath);

            return images
                .Where(FilterImages)
                .Select(x => new Tile(x))
                .Aggregate(new Tile[config.Width, config.Height], (acc, tile) =>
                {
                    acc[tile.Position.X, tile.Position.Y] = tile;

                    return acc;
                });
        }
		static string GetEndpointName(string path)
		{		
			var assemblyFiles = new DirectoryInfo(path).GetFiles("*.dll", SearchOption.AllDirectories)
				.Union(new DirectoryInfo(path).GetFiles("*.exe", SearchOption.AllDirectories));

			assemblyFiles = assemblyFiles.Where(f => !defaultAssemblyExclusions.Any(exclusion => f.Name.ToLower().StartsWith(exclusion)));			

			var results = new List<Assembly>();
			foreach (var assemblyFile in assemblyFiles)
			{
				try
				{
					var pd = new ProxyDomain();
					var assembly = pd.GetAssembly(assemblyFile.FullName);
					assembly.GetTypes();
					results.Add(assembly);
				}
				catch(Exception e)
				{
					
				}
			}


			var endPointType = ScanAssembliesForEndpoints(results).FirstOrDefault();

			if (endPointType == null)
			{
				throw new Exception(string.Format("No implementation of IConfigureThisEndpoint found in {0}", path));
			}

			//Stolen from https://github.com/NServiceBus/NServiceBus/blob/master/src/hosting/NServiceBus.Hosting.Windows/Program.cs
			var endpointConfiguration = Activator.CreateInstance(endPointType);
			var endpointName = endpointConfiguration.GetType().Namespace;

			var arr = endpointConfiguration.GetType().GetCustomAttributes(typeof(EndpointNameAttribute), false);
			if (arr.Length == 1)
				endpointName = (arr[0] as EndpointNameAttribute).Name;

			if (endpointConfiguration is INameThisEndpoint)
				endpointName = (endpointConfiguration as INameThisEndpoint).GetName();

			return endpointName;
		}
Ejemplo n.º 11
0
 public static FileInfo FindSolution(string path)
 {
     var solutions =  new DirectoryInfo(path).GetFiles("*.sln", SearchOption.AllDirectories);
     if (solutions.Length == 0)
         throw new Exception("No solution found");
     if (solutions.Length == 1)
         return solutions.First();
     // candidates.Length > 1
     var candidatesByDepth = solutions.GroupBy(x => x.FullName.Count(ch => ch == '/')).ToList();
     var minKey2 = candidatesByDepth.Min(x => x.Key);
     var topLevelCandidates = candidatesByDepth.First(x => x.Key == minKey2);
     if (topLevelCandidates.Count() == 1)
         return topLevelCandidates.First();
     //TopLevelCandidates > 1
     var dirName = Path.GetFileName(path);
     var matchesName = solutions.Where(x => x.Name == dirName).ToList();
     if (matchesName.Count == 1)
         return matchesName.First();
     throw new Exception("Could not find solution");
 }
Ejemplo n.º 12
0
            /// <summary>
            /// Scans the given path for image files and creates a hash for every element found.
            /// </summary>
            /// <param name="path">The directory to search through.</param>
            /// <param name="checkSubdirs">Include subdirectories?</param>
            /// <param name="minDate">Ignore files older than this date.</param>
            /// <returns>Returns a dictionary with the FileInfo-object of the file as key and its hash as value.</returns>
            private Dictionary<FileInfo, ulong> Scan(string path, bool checkSubdirs, DateTime minDate)
            {
                #region Scan subdirs or not
		            SearchOption __options;
                    if (checkSubdirs) __options = SearchOption.AllDirectories;
                    else __options = SearchOption.TopDirectoryOnly;
	            #endregion
                
                //Get all files
                var __files = new DirectoryInfo(path).GetFiles(new string[] { "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp" }, __options).ToList();

                #region Filter according to a given date
                    if (minDate != null)
                        __files = __files.Where(f => DateTime.Compare(f.LastWriteTime, minDate) >= 0).ToList();
                #endregion

                State.Max = __files.Count;

                //todo: Because this is a parallel operation, the ConcurrentDictionary class is used instead of the standard Dictionary (which is not thread-safe) 
                //Critical issue, because doing this parallel saves a huge amount of time
                //var __images = new ConcurrentDictionary<FileInfo, ulong>();
                //__files.AsParallel().ForAll((f) => 
                var __images = new Dictionary<FileInfo, ulong>();
                __files.ToList().ForEach((f) => 
                {
                    //Calling the respective overridden method to create a hash (the case where the key already exists can't happen, so it's not implemented properly)
                    __images.Add(f, GetHash(f.FullName));
                    //Update the State to give information about the current image
                    State.Current = f.Name;
                    State.Count = __files.IndexOf(f) + 1;
                });
                return __images;
            }
Ejemplo n.º 13
0
 public void Configure(IContainer container)
 {
     var files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).EnumerateFiles("*.dll");
     if (files.Where(file => !IsCoreAssembly(file)).Any(TryLoadConfigurator))
         _configurator.Configure(container);
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Find a local directory that has been created and is, thus, accessible and good where we can
 /// cache a dataset.
 /// </summary>
 /// <param name="dirCacheLocations">List of locations to look at</param>
 /// <returns></returns>
 private static DirectoryInfo FindLocalCache(DirectoryInfo[] dirCacheLocations)
 {
     return dirCacheLocations
         .Where(d => d.Exists)
         .FirstOrDefault();
 }
Ejemplo n.º 15
0
        public IEnumerable<MediaSourceInfo> GetCachedChannelItemMediaSources(IChannelMediaItem item)
        {
            var filenamePrefix = item.Id.ToString("N");
            var parentPath = Path.Combine(ChannelDownloadPath, item.ChannelId);

            try
            {
                var files = new DirectoryInfo(parentPath).EnumerateFiles("*", SearchOption.TopDirectoryOnly);

                if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
                {
                    files = files.Where(i => EntityResolutionHelper.IsVideoFile(i.FullName));
                }
                else
                {
                    files = files.Where(i => EntityResolutionHelper.IsAudioFile(i.FullName));
                }

                var file = files
                    .FirstOrDefault(i => i.Name.StartsWith(filenamePrefix, StringComparison.OrdinalIgnoreCase));

                if (file != null)
                {
                    var cachedItem = _libraryManager.ResolvePath(file);

                    if (cachedItem != null)
                    {
                        var hasMediaSources = _libraryManager.GetItemById(cachedItem.Id) as IHasMediaSources;

                        if (hasMediaSources != null)
                        {
                            var source = hasMediaSources.GetMediaSources(true).FirstOrDefault();

                            if (source != null)
                            {
                                source.Type = MediaSourceType.Cache;
                                return new[] { source };
                            }
                        }
                    }
                }
            }
            catch (DirectoryNotFoundException)
            {

            }

            return new List<MediaSourceInfo>();
        }
Ejemplo n.º 16
0
 /// <summary>
 /// </summary>
 private void CleanupTemporary(string path)
 {
     try
     {
         var fileInfos = new DirectoryInfo(path).GetFiles();
         foreach (var fileInfo in fileInfos.Where(t => t.Extension == ".tmp" || t.Extension == ".PendingOverwrite"))
         {
             fileInfo.Delete();
         }
     }
     catch (Exception ex)
     {
     }
 }
Ejemplo n.º 17
0
        public static void StartupCheck()
        {
            try
            {
                try
                {
                    if (!Directory.Exists(System.IO.Path.GetTempPath()))
                    {
                        Directory.CreateDirectory(System.IO.Path.GetTempPath());
                    }
                }
                catch(Exception ex)
                {
                    Log.Unhandled(ex);
                }
                if (!Directory.Exists(settingsPath))
                {
                    Directory.CreateDirectory(settingsPath);
                }
                if (!Directory.Exists(settingsTemp))
                {
                    Directory.CreateDirectory(settingsTemp);
                }
                try {
                    var files = new DirectoryInfo(settingsTemp).GetFiles();
                    foreach (var file in files.Where(file => DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromHours(72)))
                    {
                        file.Delete();
                    }
                }
                catch
                { // do nothing
                }
                if (File.Exists(settingsPath + @"\install.txt"))
                {
                    newInstall = true;
                    File.Delete(settingsPath + @"\install.txt");
                }
                if (!File.Exists(htmlImport))
                {
                    File.WriteAllText(htmlImport, Resources.htmlImportData, Encoding.Unicode);
                }
                else if (File.ReadAllText(htmlImport).Length != Resources.htmlImportData.Length)
                {
                    File.Delete(htmlImport);
                    File.WriteAllText(htmlImport, Resources.htmlImportData, Encoding.Unicode);
                }
                if (!File.Exists(htmlImportStore))
                {
                    File.WriteAllText(htmlImportStore, Resources.htmlImportStore, Encoding.Unicode);
                }
                else if (File.ReadAllText(htmlImportStore).Length != Resources.htmlImportStore.Length)
                {
                    File.Delete(htmlImportStore);
                    File.WriteAllText(htmlImportStore, Resources.htmlImportStore, Encoding.Unicode);
                }
                if (!File.Exists(htmlSetupBudget))
                {
                    File.WriteAllText(htmlSetupBudget, Resources.htmlSetupBudget, Encoding.Unicode);
                }
                if (!File.Exists(htmlImportService))
                {
                    File.WriteAllText(htmlImportService, Resources.htmlImportService, Encoding.Unicode);
                }
                else if (File.ReadAllText(htmlImportService).Length != Resources.htmlImportService.Length)
                {
                    File.Delete(htmlImportService);
                    File.WriteAllText(htmlImportService, Resources.htmlImportService, Encoding.Unicode);
                }
                if (!File.Exists(htmlLoading))
                {
                    File.WriteAllText(htmlLoading, Resources.htmlLoading, Encoding.Unicode);
                }
                else if (File.ReadAllText(htmlLoading).Length != Resources.htmlLoading.Length)
                {
                    File.Delete(htmlLoading);
                    File.WriteAllText(htmlLoading, Resources.htmlLoading, Encoding.Unicode);
                }

                if (!File.Exists(htmlError))
                {
                    File.WriteAllText(htmlError, Resources.htmlError, Encoding.Unicode);
                }
                else if (File.ReadAllText(htmlError).Length != Resources.htmlError.Length)
                {
                    File.Delete(htmlError);
                    File.WriteAllText(htmlError, Resources.htmlError, Encoding.Unicode);
                }
                if (!File.Exists(htmlStopped))
                {
                    File.WriteAllText(htmlStopped, Resources.htmlStopped, Encoding.Unicode);
                }
                else if (File.ReadAllText(htmlStopped).Length != Resources.htmlStopped.Length)
                {
                    File.Delete(htmlStopped);
                    File.WriteAllText(htmlStopped, Resources.htmlStopped, Encoding.Unicode);
                }
                if (!File.Exists(settingsPath + @"\favicon.ico"))
                {
                    File.WriteAllBytes(settingsPath + @"\favicon.ico", Resources.favicon);
                }
                if (!File.Exists(settingsPath + @"\bar_green.png"))
                {
                    File.WriteAllBytes(settingsPath + @"\bar_green.png", Resources.img_bar_green);
                }
                if (!File.Exists(settingsPath + @"\bar_red.png"))
                {
                    File.WriteAllBytes(settingsPath + @"\bar_red.png", Resources.img_bar_red);
                }
                if (!File.Exists(macroProgram))
                {
                    File.WriteAllText(macroProgram, Resources.Macro);
                }
                if (!File.Exists(macroProgramQuick))
                {
                    File.WriteAllText(macroProgramQuick, Resources.MacroQuick);
                }
                if (!File.Exists(macroProgramService))
                {
                    File.WriteAllText(macroProgramService, Resources.MacroService);
                }
                if (!File.Exists(macroProgramStore))
                {
                    File.WriteAllText(macroProgramStore, Resources.MacroStore);
                }
                if (!File.Exists(jsJqueryTablesorter))
                {
                    File.WriteAllText(jsJqueryTablesorter, Resources.jquery_tablesorter);
                }
                if (!File.Exists(jsJqueryMetadata))
                {
                    File.WriteAllText(jsJqueryMetadata, Resources.jquery_metadata);
                }
                if (!File.Exists(jsJquery))
                {
                    File.WriteAllText(jsJquery, Resources.jquery);
                }
                else if (File.ReadAllText(jsJquery).Length != Resources.jquery.Length)
                {
                    File.Delete(jsJquery);
                    File.WriteAllText(jsJquery, Resources.jquery);
                }
            }
            catch(Exception ex)
            {
                Log.Unhandled(ex);
            }
        }
Ejemplo n.º 18
0
        private static void TestFileOrdering(string directory = "", string pattern = "*.*")
        {
            if (string.IsNullOrEmpty(directory))
            {
                directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            Console.WriteLine(string.Format("Finding files matching {0} in {1}...", pattern, directory));
            FileInfo[] files = new DirectoryInfo(directory).GetFiles(pattern)
                                                           .OrderByDescending(f => f.LastWriteTime)
                                                           .ToArray();
            FileInfo[] filesCreatedToday = files.Where(f => f.CreationTime.Date.Equals(DateTime.Now.Date)).ToArray();
            FileInfo[] filesWrittenToday = files.Where(f => f.LastWriteTime.Date.Equals(DateTime.Now.Date)).ToArray();
            Console.WriteLine(
                string.Format("Found {0} files. {1} of them was/were created today. {2} was/were last edited today.",
                              files.Length, filesCreatedToday.Length, filesWrittenToday.Length));
            foreach (FileInfo fi in files)
            {
                Console.WriteLine(string.Format("  {0} created on {1} last edited at {2}", fi.Name,
                                                fi.CreationTime.Date.ToShortDateString(), fi.LastWriteTime));
            }
        }
Ejemplo n.º 19
0
        private List<string> GetFiles(string sourceFolder)
        {
            var files = new DirectoryInfo(sourceFolder).GetFiles(IncludeMask);
            var fileList = (string.IsNullOrWhiteSpace(ExcludeMask)
                        ? files
                        : files.Where(p => !PatternMatcher.StrictMatchPattern(ExcludeMask, p.Name)))
                    .Select(p => p.FullName).ToList();
            this.LogInfo("'{0}' returned {1} files that matched the given file masks", sourceFolder, fileList.Count);

            return fileList;
        }