Exemplo n.º 1
0
        public Main()
        {
            InitializeComponent();

            _sourceFiles = new FileList<FileData>();
            _extensions = new ExtensionList<ExtensionData>("C:\\sets.xml");
            
            gridDestinations.RowTemplate.Height = Util.ColHeight;
            gridDestinations.CellValueChanged += OnCellvalueChanged;


            clmnCheckBox.DataPropertyName = "Checked";
            clmnFileName.DataPropertyName = "FileName";
            clmnExt.DataPropertyName = "Extension";
            clmnSourcePath.DataPropertyName = "FullPath";
            clmnDestPath.DataPropertyName = "DestinationPath";
            gridFiles.DataSource = _sourceFiles;

            clmnID.DataPropertyName = "Id";
            clmnExtension.DataPropertyName = "Extension";
            clmnDestFolder.DataPropertyName = "FullPath";
            gridDestinations.DataSource = _extensions;

            RefreshButtonsCaption();
        }
Exemplo n.º 2
0
 public void Add(FileInfo f)
 {
     if (filesWithSameLength == null)
         filesWithSameLength = new FileList();
     filesWithSameLength.Add(f);
     _numberOfFilesWithSameLength++;
 }
Exemplo n.º 3
0
		public ProjectVisitor(bool fastLoader, string[] projects, ProjectFileFilter filter)
		{
			_fastLoader = fastLoader;
			_projects = new FileList();
			_projects.ProhibitedAttributes = FileAttributes.Hidden;
			_projects.FileFound += FileFound;
			if (filter != null)
				_projects.FileFound += delegate(object o, FileList.FileFoundEventArgs e) { e.Ignore |= filter(e.File); };
			_projects.Add(projects);
		}
Exemplo n.º 4
0
        public Reconciler(FileList srcList, FileList tgtList, SyncTask task, String metaDataDir)
        {
            _srcList = srcList;
            _tgtList = tgtList;
            _taskSettings = task.Settings;
            _srcPath = task.Source;
            _tgtPath = task.Target;
            _taskName = task.Name;
            _errorDetected = false;

            _previewFilesList = new CustomDictionary<string, string, PreviewUnit>();
            _previewFoldersList = new CustomDictionary<string, string, PreviewUnit>();
            _updatedList = new CustomDictionary<string, string, FileUnit>();
            _srcRenameList = new CustomDictionary<string, string, FileUnit>();
            _tgtRenameList = new CustomDictionary<string, string, FileUnit>();

            _summary = new SyncSummary();
            _summary.logFile = metaDataDir + @"\" + task.Name + ".log";
        }
Exemplo n.º 5
0
		static int Main(string[] raw)
		{
			ArgumentList args = new ArgumentList(raw);

			using (Log.AppStart(Environment.CommandLine))
			{
				if (args.Contains("nologo") == false)
				{
					Console.WriteLine("StampVersion.exe");
					Console.WriteLine("Copyright 2009 by Roger Knapp, Licensed under the Apache License, Version 2.0");
					Console.WriteLine("");
				}

				if ((args.Unnamed.Count == 0 && args.Count == 0) || args.Contains("?") || args.Contains("help"))
					return DoHelp();

				try
				{
                    string major = null, minor = null, build = null, revision = null;
				    string version;
                    if(args.TryGetValue("version", out version))
                    {
                        string[] dotted = version.Split('.');
                        major = dotted[0];
                        minor = dotted.Length >= 1 ? dotted[1] : null;
                        build = dotted.Length >= 2 ? dotted[2] : null;
                        revision = dotted.Length >= 3 ? dotted[3] : null;
                    }

				    major = GetNumber("Major", args, major);
					minor = GetNumber("Minor", args, minor);
					build = GetNumber("Build", args, build);
					revision = GetNumber("Revision", args, revision);

					if (major == null && minor == null && build == null && revision == null)
						return DoHelp();

				    string fileversion = args.SafeGet("fileversion");

					FileList files = new FileList(@"AssemblyInfo.cs");

					Regex versionPattern = new Regex(@"[^a-z,A-Z,0-9](?<Type>AssemblyVersion|AssemblyFileVersion)\s*\(\s*\" + '\"' +
						@"(?<Version>[0-2]?[0-9]{1,9}\.[0-2]?[0-9]{1,9}(?:(?:\.[0-2]?[0-9]{1,9}(?:(?:\.[0-2]?[0-9]{1,9})|(?:\.\*))?)|(?:\.\*))?)\" + '\"' +
						@"\s*\)");

					foreach (FileInfo file in files.ToArray())
					{
						StringBuilder content = new StringBuilder();
						int lastpos = 0;
						string text = File.ReadAllText(file.FullName);
						foreach (Match match in versionPattern.Matches(text))
						{
							Group verMatch = match.Groups["Version"];
							content.Append(text, lastpos, verMatch.Index - lastpos);
							lastpos = verMatch.Index + verMatch.Length;

							string[] parts = verMatch.Value.Split('.');
							if( parts.Length < 2 )//regex should prevent us getting here
								throw new ApplicationException(String.Format("Bad version string: {0} on line {1}", verMatch.Value, content.ToString().Split('\n').Length));
							if (parts.Length < 3)
								parts = new string[] { parts[0], parts[1], "0" };
							else if( parts.Length == 3 && parts[2] == "*" )
								parts = new string[] { parts[0], parts[1], "0", "*" };
							if (parts.Length == 3 && revision != null)
								parts = new string[] { parts[0], parts[1], parts[2], "0" };
							if( build != null && build == "*" )
								parts = new string[] { parts[0], parts[1], "*" };

							if (major != null && parts.Length > 0)
								parts[0] = major;
							if (minor != null && parts.Length > 1)
								parts[1] = minor;
							if (build != null && parts.Length > 2)
								parts[2] = build;
							if (revision != null && parts.Length > 3)
								parts[3] = revision;

							//AssemblyFileVersion doesn't use '*', so trim off the build and/or revision
							if (match.Groups["Type"].Value == "AssemblyFileVersion")
							{
								if (parts.Length >= 4 && parts[3] == "*")
									parts = new string[] { parts[0], parts[1], parts[2] };
								if (parts.Length >= 3 && parts[2] == "*")
									parts = new string[] { parts[0], parts[1] };

							    if (!String.IsNullOrEmpty(fileversion))
							    {
							        parts = fileversion.Split('.');
							    }
							}

							string newVersion = String.Join(".", parts);
							//Console.WriteLine("Changed '{0}' to '{1}'", verMatch.Value, newVersion);
							content.Append(newVersion);
						}
						content.Append(text, lastpos, text.Length - lastpos);

					    if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
					        file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;
                            
						File.WriteAllText(file.FullName, content.ToString());
					}
				}
				catch (ApplicationException ae)
				{
					Log.Error(ae);
					Console.Error.WriteLine();
					Console.Error.WriteLine(ae.Message);
					Environment.ExitCode = -1;
				}
				catch (Exception e)
				{
					Log.Error(e);
					Console.Error.WriteLine();
					Console.Error.WriteLine(e.ToString());
					Environment.ExitCode = -1;
				}
			}

			if (args.Contains("wait"))
			{
				Console.WriteLine();
				Console.WriteLine("Press [Enter] to continue...");
				Console.ReadLine();
			}

			return Environment.ExitCode;
		}
Exemplo n.º 6
0
 /// <summary>
 /// Scan a set of nop and cop files.
 /// Creates a list of Items and a list Isotopics from the nop files.
 /// Creates a list of CmPu Ratio records from the cop files.
 /// </summary>
 /// <param name="files">List of nop and cop files to process</param>
 public void Process(FileList<CSVFile> files)
 {
     if (files == null)
         return;
     foreach (CSVFile csv in files)
     {
         if (0 == string.Compare(csv.ThisSuffix, ".nop", true))
             mPathToNOPFile.Add(csv.Filename, csv);
         else if (0 == string.Compare(csv.ThisSuffix, ".cop", true))
             mPathToCOPFile.Add(csv.Filename, csv);
         else continue;
         csv.ProcessFile();  // split lines with scanner, construct istopics, item id and CmPu ratios
         Results.mlogger.TraceEvent(LogLevels.Info, 34100, "Processed " + System.IO.Path.GetFileName(csv.Filename));
     }
     foreach (CSVFile csv in mPathToNOPFile.Values)
     {
         GenerateIsotopics(csv);
         // Isotopic data sets are created for each unique set of isotopics and
         GenerateItemIds(csv);
         // An entry is made in the item data entry table for each unique item id.
     }
     foreach (CSVFile csv in mPathToCOPFile.Values)
     {
         GenerateCmPuRatioRecs(csv); // these are mapped by item id for use by NCC CmPuRatio operations
     }
     Results.ApplyContent();
 }
Exemplo n.º 7
0
		public void Test()
		{
			FileList files = new FileList(BaseDirectory);
			Assert.AreEqual(3, files.Count);

			files = new FileList(Path.Combine(BaseDirectory, "file?.*"));
			Assert.AreEqual(3, files.Count);

			files = new FileList();
			files.Add(BaseDirectory);
			Assert.AreEqual(3, files.Count);

			files = new FileList(0, BaseDirectory);
			Assert.AreEqual(0, (int)files.ProhibitedAttributes);
			Assert.AreEqual(7, files.Count);

			files = new FileList();
			files.IgnoreFolderAttributes = true;
			Assert.IsTrue(files.IgnoreFolderAttributes);
			files.Add(BaseDirectory);
			Assert.AreEqual(7, files.Count);

			files = new FileList();
			files.RecurseFolders = false;
			Assert.IsFalse(files.RecurseFolders);
			files.Add(BaseDirectory);
			Assert.AreEqual(1, files.Count);

			files = new FileList();
			files.IgnoreFolderAttributes = true;
			files.FileFound += new EventHandler<FileList.FileFoundEventArgs>(
				delegate(object sender, FileList.FileFoundEventArgs e) { if(e.File.Extension != ".ini") e.Ignore = true; } );
			files.Add(BaseDirectory);
			Assert.AreEqual(new FileList(0, Path.Combine(BaseDirectory, "*.ini")).Count, files.Count);
			Assert.AreEqual(".ini", files[0].Extension);

			files = new FileList();
			files.ProhibitedAttributes = FileAttributes.Hidden;
			files.Add(BaseDirectory);
			Assert.AreEqual(3, files.Count);

			files = new FileList();
			files.ProhibitedAttributes = FileAttributes.ReadOnly;
			files.Add(BaseDirectory);
			Assert.AreEqual(5, files.Count);
			files.Add(Path.Combine(BaseDirectory, "file1.txt"));
			Assert.AreEqual(5, files.Count);
			Assert.AreEqual(5, files.ToArray().Length);

			string restoredDir = Environment.CurrentDirectory;
			try
			{
				Environment.CurrentDirectory = BaseDirectory;
				files = new FileList();
				files.ProhibitedAttributes = FileAttributes.ReadOnly;
				files.Add(".");
				Assert.AreEqual(5, files.Count);
				files.Add("file1.txt");
				Assert.AreEqual(5, files.Count);
				Assert.AreEqual(5, files.ToArray().Length);
			}
			finally { Environment.CurrentDirectory = restoredDir; }

			files = new FileList(Path.Combine(BaseDirectory, "*.none"));
			Assert.AreEqual(0, files.Count);//nothing matching wildcard - does not throw FileNotFound
		}
Exemplo n.º 8
0
 /// <summary>
 /// Generate file lists for reconciler component
 /// </summary>
 private void CreateFileLists()
 {
     _sourceList = new FileList(_sCleanFiles, _sDirtyFiles, _sDirtyDirs, _sCleanDirs);
     _targetList = new FileList(_tCleanFiles, _tDirtyFiles, _tDirtyDirs, _tCleanDirs);
 }
Exemplo n.º 9
0
        public void detectDuplicates(FileList files)
        {
            if (files == null)
                return;
            calculateTotalNumberOfCmpOps(files);
            long fileLength = filesWithSameLengthAndDuplicates.fileLength;
            numberOfCmpOpPassed = 0;

            for (int i = 0;
                !searchingDuplicatesProgressDialog.stop &&
                i < files.Count - 1; i++,
                numberOfCmpOpPassed = fileLength * (2 * files.Count - i - 3) * i)
            {
                try
                {
                    var files_i = files[i];
                    if (files_i == null)
                        continue;

                    long lastNumberOfCmpOpPassed = numberOfCmpOpPassed;
                    FileStream f1 = files_i.OpenRead();
                    FileList same = null;

                    for (int j = i + 1;
                        !searchingDuplicatesProgressDialog.stop &&
                        j < files.Count;
                        numberOfCmpOpPassed = lastNumberOfCmpOpPassed +
                        fileLength * (j - i) * 2, j++)
                    {
                        try
                        {
                            var files_j = files[j];
                            if (files_j == null)
                                continue;

                            DateTime start = DateTime.Now;
                            numberOfBytesRead = 0;
                            /* OpenRead() may cause an IOEXception, WinIOError
                             * saying "Operation did not complete successfully
                             * because the file contains a virus or potentially
                             * unwanted software."
                             */
                            FileStream f2 = files_j.OpenRead();

                            if (compareFiles(f1, f2))
                            {
                                if (same == null)
                                {
                                    same = new FileList();
                                    same.Add(files_i);
                                }
                                same.Add(files_j);
                                files[j] = null;
                            }

                            f2.Close();

                            double elapsed = (DateTime.Now - start).TotalMilliseconds;

                            if (readTimes.ContainsKey(numberOfBytesRead))
                            {
                                readTimes[numberOfBytesRead] += elapsed;
                                readTimes[numberOfBytesRead] *= .5;
                            }
                            else
                            {
                                readTimes.Add(numberOfBytesRead, elapsed);
                            }
                        }
                        catch (Exception e)
                        {
                            Log.error(e);
                        }
                    }
                    if (same != null)
                    {
                        filesWithSameLengthAndDuplicates.AddDuplicate(same);
                    }
                    f1.Close();
                }
                catch (Exception e)
                {
                    Log.error(e);
                }

            }
        }
Exemplo n.º 10
0
		static void FileFound(object sender, FileList.FileFoundEventArgs e)
		{
			e.Ignore = false == StringComparer.OrdinalIgnoreCase.Equals(e.File.Extension, ".csproj");
		}
Exemplo n.º 11
0
		void FileFound(object sender, FileList.FileFoundEventArgs e)
		{
			e.Ignore = false == (
				StringComparer.OrdinalIgnoreCase.Equals(e.File.Extension, ".dll") ||
				StringComparer.OrdinalIgnoreCase.Equals(e.File.Extension, ".exe"));
		}
Exemplo n.º 12
0
		void ResolveFiles(ReferenceFolder folder)
		{
			FileList found = new FileList();
			found.FileFound += new EventHandler<FileList.FileFoundEventArgs>(FileFound);
			found.RecurseFolders = folder.Recursive;
            found.Add(folder.AbsolutePath(_namedValues));

			ReferenceWorkItem item;
			
			foreach (FileInfo file in found)
			{
				string filenameonly = Path.GetFileNameWithoutExtension(file.Name);
				if(!_assemblyNameToFile.TryGetValue(filenameonly, out item))
					_assemblyNameToFile.Add(filenameonly, item = new ReferenceWorkItem());
				
				item.FullPath = file.FullName;
				item.FoundIn = folder;
			}
		}
Exemplo n.º 13
0
		static int Main(string[] raw)
		{
			ArgumentList args = new ArgumentList(raw);
			using (Log.AppStart(Environment.CommandLine))
			{
				if (args.Count == 0 || args.Unnamed.Count == 0 || args.Contains("?"))
					return DoHelp();
				if (args.Contains("nologo") == false)
				{
					Console.WriteLine("CSharpTest.Net.CoverageReport.exe");
					Console.WriteLine("Copyright 2009 by Roger Knapp, Licensed under the Apache License, Version 2.0");
					Console.WriteLine("");
				}

				try
				{
					List<string> filesFound = new List<string>();
					FileList files = new FileList();
					files.RecurseFolders = args.Contains("s");
					files.Add(new List<string>(args.Unnamed).ToArray());

					XmlParser parser = new XmlParser( args.SafeGet("exclude").Values );
					foreach (System.IO.FileInfo file in files)
					{
						filesFound.Add(file.FullName);
						using(Log.Start("parsing file: {0}", file.FullName))
							parser.Parse(file.FullName);
					}

					parser.Complete();

					if (args.Contains("module"))
					{
						using (Log.Start("Creating module report."))
						using (XmlReport rpt = new XmlReport(OpenText(args["module"]), parser, "Module Summary", filesFound.ToArray()))
							new MetricReport(parser.ByModule).Write(rpt);
					}

					if (args.Contains("namespace"))
					{
						using (Log.Start("Creating namespace report."))
						using (XmlReport rpt = new XmlReport(OpenText(args["namespace"]), parser, "Namespace Summary", filesFound.ToArray()))
							new MetricReport(parser.ByNamespace).Write(rpt);
					}

					if (args.Contains("class"))
					{
						using (Log.Start("Creating class report."))
						using (XmlReport rpt = new XmlReport(OpenText(args["class"]), parser, "Module Class Summary", filesFound.ToArray()))
							new MetricReport(parser.ByModule, parser.ByNamespace, parser.ByClass).Write(rpt);
					}

                    if (args.Contains("unused"))
                    {
                        using (Log.Start("Creating unused statement report."))
                        using (UnusedReport rpt = new UnusedReport(OpenText(args["unused"]), parser))
                            new MetricReport(parser.ByModule, parser.ByMethod).Write(rpt);
                    }

					if (args.Contains("combine"))
					{
						using (Log.Start("Creating combined coverage file."))
						using (XmlCoverageWriter wtr = new XmlCoverageWriter(OpenText(args["combine"]), parser))
							new MetricReport(parser.ByModule, parser.ByMethod).Write(wtr);
					}
					//foreach (ModuleInfo mi in parser)
					//    Console.WriteLine("{0} hit {1} of {2} for {3}", mi.Name, mi.VisitedPoints, mi.SequencePoints, mi.CoveragePercent);

				}
				catch (Exception e)
				{
					Log.Error(e);
					Console.Error.WriteLine();
					Console.Error.WriteLine("Exception: {0}", e.Message);
					Console.Error.WriteLine();
					Environment.ExitCode = -1;
				}
			}

			if (args.Contains("wait"))
			{
				Console.WriteLine("Press [Enter] to continue...");
				Console.ReadLine();
			}

			return Environment.ExitCode;
		}
Exemplo n.º 14
0
 internal void AddDuplicate(FileList same)
 {
     if (duplicates == null)
     {
         duplicates = new List<FileList>();
     }
     duplicates.Add(same);
 }
Exemplo n.º 15
0
		protected override void ProcessRecord()
		{
			const string zipArchivePlaceHolder = "#";

			using (var bar = Notify.CreateStatus("Erzeuge Backup", $"Sicherung von {Source}..."))
			{
				var totalBytes = 0L;
				//var position = 0L;
				var itemsModified = 0;
				var itemsUnmodified = 0;
				var itemsZipped = 0;
				var archiveUsed = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

				// Lade Index-Datei
				bar.StatusDescription = "Lese Index...";
				var targetPath = new DirectoryInfo(Target);
				var targetIndex = Path.Combine(targetPath.FullName, "index.txt.gz");
				var index = new FileIndex();
				if (String.IsNullOrEmpty(ShadowIndex)) // Kein lokaler Index, also lade dem vom Target
					index.ReadIndex(Notify, targetIndex);
				else
					index.ReadIndex(Notify, ShadowIndex);

				// Gleiche die Daten ab und erzeuge die Statistik
				bar.StatusDescription = "Vergleiche Dateien mit Index...";
				var swFileStopWatch = Stopwatch.StartNew();
				var files = new FileList(Notify, new DirectoryInfo(Source), Excludes);
				foreach (var c in files)
				{
					var indexItem = index.UpdateFile(c);
					var tmp = 0;

					// Gib einen zwischen Bericht
					if (swFileStopWatch.ElapsedMilliseconds > 500)
					{
						bar.StatusDescription = $"Vergleiche {c.RelativePath} mit Index...";
						swFileStopWatch = Stopwatch.StartNew();
					}

					switch (indexItem.State)
					{
						case FileIndexState.Modified:
							// Erzeuge den Eintrag im Index
							if (c.FileInfo.Length < ZipArchiveBorder)
							{
								itemsZipped++;
								indexItem.ArchiveName = zipArchivePlaceHolder;
							}
							else
							{
								if (String.IsNullOrEmpty(indexItem.ArchiveName))
									indexItem.ArchiveName = Guid.NewGuid().ToString("N") + Path.GetExtension(indexItem.RelativePath) + (ZipFile(indexItem.RelativePath) ? ".gz" : ".nopack");
							}

							// Statistik für den Progress
							totalBytes += c.FileInfo.Length;
							itemsModified++;

							// Erhöhe den Zugriff
							if (archiveUsed.TryGetValue(indexItem.ArchiveName, out tmp))
								archiveUsed[indexItem.ArchiveName] = tmp + 1;
							break;
						case FileIndexState.Unmodified:
							// Prüfe die existens den Archives
							if (Force || (String.IsNullOrEmpty(ShadowIndex) && !File.Exists(Path.Combine(targetPath.FullName, indexItem.ArchiveName))))
							{
								indexItem.Update(c.FileInfo);
								goto case FileIndexState.Modified;
							}
							itemsUnmodified++;

							// Erhöhe den Zugriff
							if (archiveUsed.TryGetValue(indexItem.ArchiveName, out tmp))
								archiveUsed[indexItem.ArchiveName] = tmp + 1;
							break;
						case FileIndexState.None:
							if (archiveUsed.ContainsKey(indexItem.ArchiveName))
								archiveUsed[indexItem.ArchiveName] = 0;
							break;
					}
				}

				// Schreibe das neue Archiv
				if (itemsModified > 0)
				{
					string currentArchiveName = null;
					FileWrite zipStream = null;
					ZipOutputStream zip = null;
					try
					{
						bar.StartRemaining();
						bar.Maximum = totalBytes;

						var removeItems = new List<FileIndexItem>();
						foreach (var c in index)
						{
							switch (c.State)
							{
								case FileIndexState.Modified: // Kopiere die Datei
									using (var src = Stuff.OpenRead(new FileInfo(Path.Combine(Source, c.RelativePath)), Notify, allowEmpty: true))
									{
										if (c.ArchiveName == zipArchivePlaceHolder)
										{
											// Schließe das Archiv, wenn genug Inhalt
											if (zipStream != null && zipStream.Stream.Position > 512 << 20)
											{
												zipStream.Commit();
												CloseZipStream(zipStream, zip);
												currentArchiveName = null;
											}

											// Erzeuge das Archiv
											if (currentArchiveName == null)
											{
												currentArchiveName = Guid.NewGuid().ToString("N") + ".zip";
												CreateZipStream(targetPath, currentArchiveName, out zipStream, out zip);
											}

											// Kopiere die Daten
											ZipFileItem(Notify, bar, src, zip, c);
											c.ArchiveName = currentArchiveName;
										}
										else
											GZipFileItem(Notify, bar, src, targetPath, c);
									}
									break;
								case FileIndexState.None: // Lösche den Index
									removeItems.Remove(c);
									break;
							}
						}

						// Entferne die Einträge aus dem Index
						foreach (var c in removeItems)
							index.RemoveEntry(c);

						if (zipStream != null)
							zipStream.Commit();
					}
					finally
					{
						CloseZipStream(zipStream, zip);
					}

					// Schreibe den Index
					bar.StopRemaining();
					bar.StatusDescription = "Schreibe Index...";
					if (!String.IsNullOrEmpty(ShadowIndex))
						index.WriteIndex(Notify, ShadowIndex);
					index.WriteIndex(Notify, targetIndex);

					// Lösche ungenutzte Archive
					if (String.IsNullOrEmpty(ShadowIndex))
					{
						foreach (var c in archiveUsed)
							if (c.Value == 0)
							{
								var file = new FileInfo(Path.Combine(targetPath.FullName, c.Key));
								bar.StatusDescription = $"Nicht mehr benötigtes Archiv '{c.Key}'...";
								Notify.SafeIO(file.Delete, bar.StatusDescription);
							}
					}
					else // Erzeuge nur eine Löschdatei
					{
						bar.StatusDescription = "Nicht mehr benötigte Archive werden gelöscht...";
						using (var sw = new StreamWriter(Stuff.OpenWrite(new FileInfo(Path.Combine(targetPath.FullName, "index_rm.txt")), Notify, CompressMode.Stored)))
						{
							sw.BaseStream.Position = sw.BaseStream.Length;
							foreach (var c in archiveUsed)
								if (c.Value == 0)
									sw.WriteLine(c.Key);
						}
					}
				}
			}
		} // proc ProcessRecord
Exemplo n.º 16
0
		static int Main(string[] raw)
        {
            String temp;
		    bool wait = ArgumentList.Remove(ref raw, "wait", out temp);
            bool addMissing = ArgumentList.Remove(ref raw, "add-missing", out temp);

            try
		    {
		        var entryAssembly = Assembly.GetEntryAssembly();
		        if (entryAssembly != null && !ArgumentList.Remove(ref raw, "nologo", out temp))
		        {
		            var aname = entryAssembly.GetName();
		            aname.CultureInfo = null;
		            Console.WriteLine("{0}", aname);
		            foreach (
		                AssemblyCopyrightAttribute a in
		                    entryAssembly.GetCustomAttributes(typeof (AssemblyCopyrightAttribute), false))
		                Console.WriteLine("{0}", a.Copyright);
		            Console.WriteLine();
		        }

		        if (ArgumentList.Remove(ref raw, "verbose", out temp) || ArgumentList.Remove(ref raw, "verbosity", out temp))
		        {
		            SourceLevels traceLevel;
		            try
		            {
		                traceLevel = (SourceLevels) Enum.Parse(typeof (SourceLevels), temp);
		            }
		            catch
		            {
		                traceLevel = SourceLevels.All;
		            }

		            Trace.Listeners.Add(new ConsoleTraceListener()
		            {
		                Filter = new EventTypeFilter(traceLevel),
		                IndentLevel = 0,
		                TraceOutputOptions = TraceOptions.None
		            });
		        }

		        var argsList = new List<string>();
		        foreach (string arg in raw)
		        {
		            if (arg.StartsWith("@"))
		            {
		                foreach (var line in File.ReadAllLines(arg.Substring(1)))
		                {
		                    if (!String.IsNullOrEmpty(line) && line.Trim().Length > 0)
		                        argsList.Add(line.Trim());
		                }
		            }
		            else
		            {
		                argsList.Add(arg);
		            }
		        }

		        raw = argsList.ToArray();
		        if (ArgumentList.Remove(ref raw, "?", out temp) || ArgumentList.Remove(ref raw, "help", out temp))
		            return DoHelp();

                var args = new ArgumentList(StringComparer.Ordinal, raw);
		        if (args.Unnamed.Count == 0 || args.Count == 0)
		            return DoHelp();

		        var files = new FileList();
		        files.ProhibitedAttributes = FileAttributes.Hidden | FileAttributes.System;
		        files.RecurseFolders = true;
		        files.FileFound +=
		            delegate(object sender, FileList.FileFoundEventArgs eventArgs)
		            {
		                eventArgs.Ignore = !eventArgs.File.Name.StartsWith("AssemblyInfo");
		            };

		        foreach (var arg in args.Unnamed)
		            files.Add(arg);

		        var processor = new AssemblyFileProcessor(args, addMissing);
		        foreach (FileInfo file in files.ToArray())
		        {
		            processor.ProcessFile(file);
		        }
		    }
		    catch (ApplicationException ae)
		    {
		        Trace.TraceError("{0}", ae);
		        Console.Error.WriteLine();
		        Console.Error.WriteLine(ae.Message);
		        Environment.ExitCode = -1;
		    }
		    catch (Exception e)
		    {
		        Trace.TraceError("{0}", e);
		        Console.Error.WriteLine();
		        Console.Error.WriteLine(e.ToString());
		        Environment.ExitCode = -1;
		    }
		    finally
		    {
		        if (wait)
		        {
		            Console.WriteLine();
		            Console.WriteLine("Press [Enter] to continue...");
		            Console.ReadLine();
		        }
		    }
		    return Environment.ExitCode;
		}
Exemplo n.º 17
0
        public GenerateNuGetSpecTask WithContentFiles(FileList files, string target = null)
        {
            if (target == null)
            {
                target = "content";
            }

            foreach (var file in files)
            {
                Files.Add(new File(file.AbsolutePath, Path.Combine(target, file.GetRelativePath(files.BaseDirectory)), null));
            }

            return this;
        }
Exemplo n.º 18
0
        static int Main(string[] raw)
        {
            ArgumentList args = new ArgumentList(raw);

            using (DisposingList dispose = new DisposingList())
            using (Log.AppStart(Environment.CommandLine))
            {
                if (args.Contains("nologo") == false)
                {
                    Console.WriteLine("XhtmlValidate.exe");
                    Console.WriteLine("Copyright 2010 by Roger Knapp, Licensed under the Apache License, Version 2.0");
                    Console.WriteLine("");
                }

                if ((args.Unnamed.Count == 0) || args.Contains("?") || args.Contains("help"))
                    return DoHelp();

                try
                {
                    FileList files = new FileList();
                    files.RecurseFolders = true;
                    foreach (string spec in args.Unnamed)
                    {
                        Uri uri;
                        if (Uri.TryCreate(spec, UriKind.Absolute, out uri) && !(uri.IsFile || uri.IsUnc))
                        {
                            using(WebClient wc = new WebClient())
                            {
                                TempFile tfile = new TempFile();
                                dispose.Add(tfile);
                                wc.DownloadFile(uri, tfile.TempPath);
                                files.Add(tfile.Info);
                            }
                        }
                        else
                            files.Add(spec);
                    }
                    if( files.Count == 0 )
                        return 1 + DoHelp();

                    XhtmlValidation validator = new XhtmlValidation(XhtmlDTDSpecification.Any);
                    foreach (FileInfo f in files)
                        validator.Validate(f.FullName);
                }
                catch (ApplicationException ae)
                {
                    Log.Error(ae);
                    Console.Error.WriteLine();
                    Console.Error.WriteLine(ae.Message);
                    Environment.ExitCode = -1;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    Console.Error.WriteLine();
                    Console.Error.WriteLine(e.ToString());
                    Environment.ExitCode = -1;
                }
            }

            if (args.Contains("wait"))
            {
                Console.WriteLine();
                Console.WriteLine("Press [Enter] to continue...");
                Console.ReadLine();
            }

            return Environment.ExitCode;
        }
Exemplo n.º 19
0
        public void Testv2()
        {
            DirectoryInfo root = new DirectoryInfo(BaseDirectory);

            FileList files = new FileList();
            files.AddRange(root.GetFiles("*", SearchOption.AllDirectories));
            Assert.AreEqual(7, files.Count);

            FileList txtFiles = new FileList(root.GetFiles("*.txt", SearchOption.AllDirectories));
            Assert.AreEqual(3, txtFiles.Count);
            Assert.IsTrue(files.Contains(txtFiles[0]));
            Assert.IsTrue(files.Contains(txtFiles[1]));
            Assert.IsTrue(files.Contains(txtFiles[2]));

            files.Remove(txtFiles.ToArray());
            Assert.AreEqual(4, files.Count);
            Assert.IsFalse(files.Contains(txtFiles[0]));
            Assert.IsFalse(files.Contains(txtFiles[1]));

            string[] names = files.GetFileNames();
            Assert.AreEqual(4, names.Length);
            foreach(string fpath in names)
                Assert.IsTrue(files.Contains(new FileInfo(fpath)));
        }
Exemplo n.º 20
0
        public void Scan()
        {
            if (!Scanned)
            {
                // Index ALL files in GameDataDirectory:
                Files = new FileList(GamedataDirectory,
                    new string[] { ".aiw", ".gdb", ".veh", ".rfm", ".ini", ".hdv" , ".tbc"});

                Scanned = true;

                ScanTracks();
                ScanCars();

            }
        }
Exemplo n.º 21
0
		public void TestAddFileNotFound()
		{
			//A file name that does not contain wildcards and does not exist will throw FileNotFound
			FileList list = new FileList();
			list.RecurseFolders = false;
			list.Add(Path.Combine(@"C:\", Guid.NewGuid().ToString()));
		}
Exemplo n.º 22
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            MoSync.SystemPropertyManager.RegisterSystemPropertyProvider("mosync.path.local",
                delegate(String key)
                {
                    // The isolated storage becomes the "root"
                    return "/";
                }
            );

            ioctls.maFileOpen = delegate(int _path, int _mode)
            {
                String path = core.GetDataMemory().ReadStringAtAddress(_path);
                path = ConvertPath(path);

                File file = null;
                FileAccess access = 0;

                if (_mode == MoSync.Constants.MA_ACCESS_READ)
                {
                    access = FileAccess.Read;
                }
                else if (_mode == MoSync.Constants.MA_ACCESS_READ_WRITE)
                {
                    access = FileAccess.ReadWrite;
                }
                else
                {
                    throw new Exception("Invalid file access mode");
                }

                file = new File(path, access);

                if (file.IsDirectory)
                {
                    if (isolatedStorage.FileExists(path))
                        return MoSync.Constants.MA_FERR_WRONG_TYPE;
                }
                else
                {
                    if (isolatedStorage.DirectoryExists(path))
                        return MoSync.Constants.MA_FERR_WRONG_TYPE;
                    try
                    {
                        file.TryOpen();
                    }
                    catch (IsolatedStorageException e)
                    {
                        MoSync.Util.Log(e);
                        return MoSync.Constants.MA_FERR_GENERIC;
                    }
                }

                mFileHandles.Add(mNextFileHandle, file);
                return mNextFileHandle++;
            };

            ioctls.maFileClose = delegate(int _file)
            {
                File file = mFileHandles[_file];
                file.Close();
                mFileHandles.Remove(_file);
                return 0;
            };

            ioctls.maFileRead = delegate(int _file, int _dst, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                core.GetDataMemory().WriteFromStream(_dst, fileStream, _len);
                return 0;
            };

            ioctls.maFileReadToData = delegate(int _file, int _data, int _offset, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory data = (Memory)dataRes.GetInternalObject();
                Stream data = (Stream)dataRes.GetInternalObject();
                MoSync.Util.CopySeekableStreams(fileStream, (int)fileStream.Position,
                    data, _offset, _len);
                //data.WriteFromStream(_offset, fileStream, _len);
                return 0;
            };

            ioctls.maFileWriteFromData = delegate(int _file, int _data, int _offset, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory data = (Memory)dataRes.GetInternalObject();
                Stream data = (Stream)dataRes.GetInternalObject();
                //byte[] bytes = new byte[_len];
                //data.ReadBytes(bytes, _offset, _len);
                MoSync.Util.CopySeekableStreams( data, _offset,
                    fileStream, (int)fileStream.Position,
                    _len);
                //fileStream.Write(bytes, 0, _len);
                fileStream.Flush();
                return 0;
            };

            ioctls.maFileWrite = delegate(int _file, int _src, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                byte[] bytes = new byte[_len];
                core.GetDataMemory().ReadBytes(bytes, _src, _len);
                fileStream.Write(bytes, 0, _len);
                fileStream.Flush();
                return 0;
            };

            ioctls.maFileSeek = delegate(int _file, int _offset, int _whence)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                SeekOrigin origin;
                switch (_whence)
                {
                    case MoSync.Constants.MA_SEEK_SET:
                        origin = SeekOrigin.Begin;
                        break;
                    case MoSync.Constants.MA_SEEK_CUR:
                        origin = SeekOrigin.Current;
                        break;
                    case MoSync.Constants.MA_SEEK_END:
                        origin = SeekOrigin.End;
                        break;
                    default:
                        throw new Exception("maFileSeek whence");
                }

                try
                {
                    return (int)fileStream.Seek(_offset, origin);
                }
                catch (IOException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MA_FERR_GENERIC;
                }
            };

            ioctls.maFileTell = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                return (int)fileStream.Position;
            };

            ioctls.maFileExists = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return file.Exists ? 1 : 0;
            };

            ioctls.maFileCreate = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.Exists)
                    return MoSync.Constants.MA_FERR_GENERIC;
                file.Create();
                return 0;
            };

            ioctls.maFileDelete = delegate(int _file)
            {
                File file = mFileHandles[_file];
                try
                {
                    file.Delete();
                }
                catch (IsolatedStorageException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MA_FERR_GENERIC;
                }
                return 0;
            };

            ioctls.maFileSize = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return file.Size();
            };

            ioctls.maFileAvailableSpace = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return file.AvailableSpace();
            };

            ioctls.maFileTotalSpace = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return file.TotalSpace();
            };

            ioctls.maFileDate = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return Util.ToUnixTimeUtc(file.Date().ToFileTime());
            };

            ioctls.maFileRename = delegate(int _file, int _newName)
            {
                File file = mFileHandles[_file];
                String newName = core.GetDataMemory().ReadStringAtAddress(_newName);
                newName = ConvertPath(newName);
                if (newName.Contains("\\"))
                {
                    if (newName[0] != '\\')
                        throw new Exception("Invalid newName");
                }
                else
                {   // add directory of old file.
                    newName = Path.GetDirectoryName(file.Path) + "\\" + newName;
                }
                file.Rename(newName);
                return 0;
            };

            ioctls.maFileTruncate = delegate(int _file, int _offset)
            {
                File file = mFileHandles[_file];
                file.Truncate(_offset);
                return 0;
            };

            ioctls.maFileListStart = delegate(int _path, int _filter, int _sorting)
            {
                // todo: respect _sorting.
                String path = core.GetDataMemory().ReadStringAtAddress(_path);
                path = ConvertPath(path);
                String filter = core.GetDataMemory().ReadStringAtAddress(_filter);
                String pattern = path + filter;
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                FileList fl = new FileList();
                fl.dirs = isf.GetDirectoryNames(pattern);
                fl.files = isf.GetFileNames(pattern);
                fl.pos = 0;

                mFileListHandles.Add(mNextFileListHandle, fl);
                return mNextFileListHandle++;
            };

            ioctls.maFileListNext = delegate(int _list, int _nameBuf, int _bufSize)
            {
                FileList fl = mFileListHandles[_list];
                String name;
                if (fl.pos < fl.dirs.Length)
                    name = fl.dirs[fl.pos] + "/";
                else if (fl.pos < fl.dirs.Length + fl.files.Length)
                    name = fl.files[fl.pos - fl.dirs.Length];
                else
                    return 0;
                if (name.Length >= _bufSize)
                    return name.Length;
                core.GetDataMemory().WriteStringAtAddress(_nameBuf,
                    name, _bufSize);
                fl.pos++;
                return name.Length;
            };

            ioctls.maFileListClose = delegate(int _list)
            {
                FileList fl = mFileListHandles[_list];
                mFileListHandles.Remove(_list);
                return 0;
            };
        }
Exemplo n.º 23
0
 public ScanningProcessing()
 {
     this.m_ScanFolderList = new ScanFolderList();
     this.m_ScanFileList = new FileList();
 }