/// <summary>
        /// Invokes CSC to build the given files against the given set of references
        /// </summary>
        /// <param name="files"></param>
        /// <param name="referenceAssemblies"></param>
        /// <param name="lang"></param>
        public static bool CompileCSharpSource(IEnumerable<string> files, IEnumerable<string> referenceAssemblies)
        {
            List<ITaskItem> sources = new List<ITaskItem>();
            foreach (string f in files)
                sources.Add(new TaskItem(f));

            List<ITaskItem> references = new List<ITaskItem>();
            foreach (string s in referenceAssemblies)
                references.Add(new TaskItem(s));

            Csc csc = new Csc();
            MockBuildEngine buildEngine = new MockBuildEngine();
            csc.BuildEngine = buildEngine;  // needed before task can log

            csc.NoStandardLib = true;   // don't include std lib stuff -- we're feeding it silverlight
            csc.NoConfig = true;        // don't load the csc.rsp file to get references
            csc.TargetType = "library";
            csc.Sources = sources.ToArray();
            csc.References = references.ToArray();

            bool result = false;
            try
            {
                result = csc.Execute();
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception occurred invoking CSC task on " + sources[0].ItemSpec + ":\r\n" + ex);
            }

            if (!result)
            {
                string sourceList = string.Empty;
                foreach (TaskItem t in sources)
                {
                    sourceList += "    " + t.ItemSpec + "\r\n";
                }
                Assert.Fail("CSC failed to compile sources:\r\n" + sourceList + "\r\n" + buildEngine.ConsoleLogger.Errors + "\r\n\r\nReference assemblies were:\r\n" + ReferenceAssembliesAsString(referenceAssemblies));
            }
            return result;
        }
        /// <summary>
        /// Invokes CSC to build the given files against the given set of references
        /// </summary>
        /// <param name="files"></param>
        /// <param name="referenceAssemblies"></param>
        /// <param name="lang"></param>
        /// <param name="documentationFile">If nonblank, the documentation file to generate during the compile.</param>
        public static bool CompileCSharpSource(IEnumerable<string> files, IEnumerable<string> referenceAssemblies, string documentationFile)
        {
            List<ITaskItem> sources = new List<ITaskItem>();
            foreach (string f in files)
                sources.Add(new TaskItem(f));

            List<ITaskItem> references = new List<ITaskItem>();
            foreach (string s in referenceAssemblies)
                references.Add(new TaskItem(s));

            Csc csc = new Csc();
            MockBuildEngine buildEngine = new MockBuildEngine();
            csc.BuildEngine = buildEngine;  // needed before task can log

            csc.NoStandardLib = true;   // don't include std lib stuff -- we're feeding it silverlight
            csc.NoConfig = true;        // don't load the csc.rsp file to get references
            csc.TargetType = "library";
            csc.Sources = sources.ToArray();
            csc.References = references.ToArray();
            csc.DefineConstants += "SILVERLIGHT";
            if (!string.IsNullOrEmpty(documentationFile))
            {
                csc.DocumentationFile = documentationFile;
            }
 
            bool result = false;
            try
            {
                result = csc.Execute();
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception occurred invoking CSC task on " + sources[0].ItemSpec + ":\r\n" + ex);
            }
            
            Assert.IsTrue(result, "CSC failed to compile " + sources[0].ItemSpec + ":\r\n" + buildEngine.ConsoleLogger.Errors);
            return result;
        }
Example #3
0
        public override bool Execute()
        {
            string defDir = SafePath(ThriftDefinitionDir.ItemSpec);
            //look for last compilation timestamp
            string lastBuildPath = Path.Combine(defDir, lastCompilationName);
            DirectoryInfo defDirInfo = new DirectoryInfo(defDir);
            string lastWrite = LastWriteTime(defDir);
            if (File.Exists(lastBuildPath))
            {
                string lastComp = File.ReadAllText(lastBuildPath);
                //don't recompile if the thrift library has been updated since lastComp
                FileInfo f = new FileInfo(ThriftLibrary.ItemSpec);
                string thriftLibTime = f.LastWriteTimeUtc.ToFileTimeUtc().ToString();
                if (lastComp.CompareTo(thriftLibTime) < 0)
                {
                    //new thrift library, do a compile
                    lastWrite = thriftLibTime;
                }
                else if (lastComp == lastWrite || (lastComp == thriftLibTime && lastComp.CompareTo(lastWrite) > 0))
                {
                    //the .thrift dir hasn't been written to since last compilation, don't need to do anything
                    LogMessage("ThriftImpl up-to-date", MessageImportance.High);
                    return true;
                }
            }

            //find the directory of the thriftlibrary (that's where output will go)
            FileInfo thriftLibInfo = new FileInfo(SafePath(ThriftLibrary.ItemSpec));
            string thriftDir = thriftLibInfo.Directory.FullName;

            string genDir = Path.Combine(thriftDir, "gen-csharp");
            if (Directory.Exists(genDir))
            {
                try
                {
                    Directory.Delete(genDir, true);
                }
                catch { /*eh i tried, just over-write now*/}
            }

            //run the thrift executable to generate C#
            foreach (string thriftFile in Directory.GetFiles(defDir, "*.thrift"))
            {
                LogMessage("Generating code for: " + thriftFile, MessageImportance.Normal);
                Process p = new Process();
                p.StartInfo.FileName = SafePath(ThriftExecutable.ItemSpec);
                p.StartInfo.Arguments = "-csharp -o " + SafePath(thriftDir) + " -r " + thriftFile;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardOutput = false;
                p.Start();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    LogMessage("thrift.exe failed to compile " + thriftFile, MessageImportance.High);
                    return false;
                }
                if (p.ExitCode != 0)
                {
                    LogMessage("thrift.exe failed to compile " + thriftFile, MessageImportance.High);
                    return false;
                }
            }

            Csc csc = new Csc();
            csc.TargetType = "library";
            csc.References = new ITaskItem[] { new TaskItem(ThriftLibrary.ItemSpec) };
            csc.EmitDebugInformation = true;
            string outputPath = Path.Combine(thriftDir, OutputName.ItemSpec);
            csc.OutputAssembly = new TaskItem(outputPath);
            csc.Sources = FindSources(Path.Combine(thriftDir, "gen-csharp"));
            csc.BuildEngine = this.BuildEngine;
            LogMessage("Compiling generated cs...", MessageImportance.Normal);
            if (!csc.Execute())
            {
                return false;
            }

            //write file to defDir to indicate a build was successfully completed
            File.WriteAllText(lastBuildPath, lastWrite);

            thriftImpl = new TaskItem(outputPath);

            return true;
        }
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            if (!File.Exists(ProtocExe))
            {
                Log.LogError(string.Format("Could not find protoc.exe at path '{0}'", ProtocExe));
            }

            if (!Directory.Exists(tempDir))
            {
                Log.LogError(string.Format("Temporary directory does not exist '{0}'", TempDir));
                return false;
            }
            Directory.CreateDirectory(GetTempDir());

            if (!Directory.Exists(Output))
            {
                Log.LogError(string.Format("Output directory does not exist '{0}'", Output));
                return false;
            }

            if (Protos.Length < 1)
            {
                Log.LogError(string.Format("No input files where specified"));
                return false;
            }

            var files = Protos.Select(i => new FileInfo(i.ItemSpec)).ToArray();
            foreach (var file in files.Where(file => !file.Exists))
            {
                Log.LogError(string.Format("Could not find input file '{0}'", file.Name));
                return false;
            }

            if (!ExecuteProtoc(files) && GenerateProtos()) return false;

            if (OutputAssembly != null)
            {
                var compile = new Csc
                {
                    BuildEngine = BuildEngine,
                    OutputAssembly = OutputAssembly,
                    References = AssemblyReferences,
                    Sources = Directory.GetFiles(Output, "*.cs").Select(f => new TaskItem(f)).ToArray(),
                    DebugType = "pdbonly",
                    WarningLevel = 1,
                    TargetType = "library",
                    KeyFile = KeyFile
                };
                return compile.Execute();
            }

            return true;
        }
Example #5
0
		/// <summary>
		/// Executes a task.
		/// </summary>
		/// <returns>
		/// true if the task executed successfully; otherwise, false.
		/// </returns>
		public override bool Execute()
		{
			if (POFiles != null)
			{
				foreach (ITaskItem item in POFiles)
				{
					// Verify that POFile exists.
					if (!File.Exists(item.ItemSpec))
					{
						_LogMessage(string.Format(CultureInfo.InvariantCulture, "File {0} does not exists.", item.ItemSpec));
						return false;
					}

					// Get file info from file.
					FileInfo fileInfo = new FileInfo(item.ItemSpec);

					// Assume that FileName is in the format: locale.extension
					// Get locale from FileName.
					string locale = fileInfo.Name.Replace(fileInfo.Extension, string.Empty);

					string outputPath = OutputPath + "\\" + locale;

					// If OutputPath directory does not exist, create it.
					if (!Directory.Exists(outputPath))
						Directory.CreateDirectory(outputPath);

					// Create the output assembly name.
					string assemblyFileName = Path.Combine(outputPath, AssemblyName + ".resources.dll");

					// Verify if assemblyFile exists
					if (File.Exists(assemblyFileName))
					{
						//FileInfo dllInfo = new FileInfo(assemblyFileName);
						//if (dllInfo.LastWriteTime.CompareTo(fileInfo.LastWriteTime) > 0)
						//    continue; // Continue to next item cause Assembly is newer than current po file.
						//else
						File.Delete(assemblyFileName);
					}

					//Get the temporary path to store the C# classes.
					string csOutputPath = System.IO.Path.GetTempPath();

					// Get the C# file template from embedded resources.
					string template = Resource.template;

					// Get the file name for the C# class
					string csFileName = Path.Combine(csOutputPath, string.Format(CultureInfo.InvariantCulture, "{0}.{1}", AssemblyName, "cs"));

					// Get the class name for the C# class
					string className = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", ConstructClassName(AssemblyName), locale.Replace("-", "_"));

					// String builder to hold the key value pairs retrieved from the po file.
					StringBuilder s = new StringBuilder();
					using (FileStream fileStream = new FileStream(item.ItemSpec, FileMode.Open))
					{
						// Read the po file.
						_ReadPOFile(s, new StreamReader(fileStream, Encoding.UTF8));
					}

					// Get bytes for the new C# class
					byte[] bytes = Encoding.UTF8.GetBytes(template.Replace("{0}", className).Replace("{1}", s.ToString()));

					// Write the C# class to disk.
					using (FileStream csStream = new FileStream(csFileName, FileMode.Create))
					{
						csStream.Write(bytes, 0, bytes.Length);
					}

					_LogMessage(string.Format(CultureInfo.InvariantCulture, "Created file {0}", csFileName));

					// Log if GNU.Gettext.dll not found.
					if (!File.Exists(GNUGetTextAssemblyPath))
					{
						_LogMessage(string.Format(CultureInfo.InvariantCulture, "Unable to find dependency file: {0}", GNUGetTextAssemblyPath));
						return false;
					}

                    var fileinfo = new FileInfo(GNUGetTextAssemblyPath);

					// Compile c# class.
					Csc csc = new Csc();
					csc.HostObject = this.HostObject;
					csc.BuildEngine = this.BuildEngine;
                    csc.AdditionalLibPaths = new string[] { fileinfo.Directory.FullName };
					csc.TargetType = "library";
                    csc.References = new TaskItem[] { new TaskItem(fileinfo.Name) };
					csc.OutputAssembly = new TaskItem(assemblyFileName);
					csc.Sources = new TaskItem[] { new TaskItem(csFileName) };
					csc.Execute();

					_LogMessage(string.Format(CultureInfo.InvariantCulture, "Created assembly {0}", assemblyFileName));
				}

				return true;
			}
			return true;
		}
Example #6
0
        public void MultipleAnalyzers_HostObject()
        {
            IBuildEngine2 mockEngine = new MockEngine();
            Csc csc = new Csc();
            csc.BuildEngine = mockEngine;

            MockCscAnalyzerHostObject cscHostObject = new MockCscAnalyzerHostObject();
            cscHostObject.SetDesignTime(true);

            csc.HostObject = cscHostObject;
            csc.UseHostCompilerIfAvailable = true;

            Assert.IsNull(cscHostObject.Analyzers);

            csc.Analyzers = new TaskItem[]
            {
                new TaskItem("Foo.dll"),
                new TaskItem("Bar.dll")
            };

            csc.Sources = new TaskItem[] { new TaskItem("a.cs") };

            bool cscSuccess = csc.Execute();

            Assert.IsTrue(cscSuccess, "Csc task failed.");

            Assert.AreEqual(2, cscHostObject.Analyzers.Length);
            Assert.AreEqual("Foo.dll", cscHostObject.Analyzers[0].ItemSpec);
            Assert.AreEqual("Bar.dll", cscHostObject.Analyzers[1].ItemSpec);
        }
Example #7
0
        public void RuleSet_HostObject()
        {
            IBuildEngine2 mockEngine = new MockEngine();
            Csc csc = new Csc();
            csc.BuildEngine = mockEngine;

            MockCscAnalyzerHostObject cscHostObject = new MockCscAnalyzerHostObject();
            cscHostObject.SetDesignTime(true);

            csc.HostObject = cscHostObject;
            csc.UseHostCompilerIfAvailable = true;

            Assert.IsNull(cscHostObject.RuleSet);

            csc.CodeAnalysisRuleSet = "Bar.ruleset";

            csc.Sources = new TaskItem[] { new TaskItem("a.cs") };

            bool cscSuccess = csc.Execute();

            Assert.IsTrue(cscSuccess, "Csc task failed.");
            Assert.AreEqual("Bar.ruleset", cscHostObject.RuleSet);
        }
Example #8
0
        public void CscHostObject3()
        {
            IBuildEngine2 mockEngine = new MockEngine();
            Csc csc = new Csc();
            csc.BuildEngine = mockEngine;
            MockCscHostObject3 cscHostObject = new MockCscHostObject3();
            csc.HostObject = cscHostObject;
            csc.UseHostCompilerIfAvailable = true;

            Assert.IsTrue(!cscHostObject.CompileMethodWasCalled);

            csc.Sources = new TaskItem[] { new TaskItem("a.cs") };
            bool cscSuccess = csc.Execute();

            Assert.IsTrue(cscSuccess, "Csc task failed.");
            Assert.IsTrue(cscHostObject.CompileMethodWasCalled);
        }
Example #9
0
        public void NoAnalyzer_HostObject()
        {
            IBuildEngine2 mockEngine = new MockEngine();
            Csc csc = new Csc();
            csc.BuildEngine = mockEngine;

            MockCscAnalyzerHostObject cscHostObject = new MockCscAnalyzerHostObject();
            cscHostObject.SetDesignTime(true);

            csc.HostObject = cscHostObject;
            csc.UseHostCompilerIfAvailable = true;

            Assert.IsNull(cscHostObject.Analyzers);

            csc.Sources = new TaskItem[] { new TaskItem("a.cs") };

            bool cscSuccess = csc.Execute();

            Assert.IsTrue(cscSuccess, "Csc task failed.");
            Assert.IsNull(cscHostObject.Analyzers);
        }
        internal string CompileCSharpSource()
        {
            List<ITaskItem> sources = new List<ITaskItem>();
            string codeFile = this.GeneratedCodeFile;
            sources.Add(new TaskItem(codeFile));

            // If client has added extra user code into the
            // compile request, add it in now
            string userCodeFile = this.UserCodeFile;
            if (!string.IsNullOrEmpty(userCodeFile))
            {
                sources.Add(new TaskItem(userCodeFile));
            }

            List<ITaskItem> references = new List<ITaskItem>();
            foreach (string s in this.ReferenceAssemblies)
                references.Add(new TaskItem(s));

            Csc csc = new Csc();
            MockBuildEngine buildEngine = this.MockBuildEngine;
            csc.BuildEngine = buildEngine;  // needed before task can log

            csc.NoStandardLib = true;   // don't include std lib stuff -- we're feeding it silverlight
            csc.NoConfig = true;        // don't load the csc.rsp file to get references
            csc.TargetType = "library";
            csc.Sources = sources.ToArray();
            csc.References = references.ToArray();
            csc.DefineConstants += "SILVERLIGHT";
            csc.OutputAssembly = new TaskItem(this.OutputAssemblyName);
            bool result = false;
            try
            {
                result = csc.Execute();
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception occurred invoking CSC task on " + sources[0].ItemSpec + ":\r\n" + ex);
            }

            Assert.IsTrue(result, "CSC failed to compile " + sources[0].ItemSpec + ":\r\n" + buildEngine.ConsoleLogger.Errors);
            return csc.OutputAssembly.ItemSpec;
        }
Example #11
0
        public void AdditionalFile_HostObject()
        {
            IBuildEngine2 mockEngine = new MockEngine();
            Csc csc = new Csc();
            csc.BuildEngine = mockEngine;

            MockCscAnalyzerHostObject cscHostObject = new MockCscAnalyzerHostObject();
            cscHostObject.SetDesignTime(true);

            csc.HostObject = cscHostObject;
            csc.UseHostCompilerIfAvailable = true;

            Assert.IsNull(cscHostObject.AdditionalFiles);

            csc.AdditionalFiles = new TaskItem[]
            {
                new TaskItem("web.config")
            };

            csc.Sources = new TaskItem[] { new TaskItem("a.cs") };

            bool cscSuccess = csc.Execute();

            Assert.IsTrue(cscSuccess, "Csc task failed.");
            Assert.AreEqual(1, cscHostObject.AdditionalFiles.Length);
            Assert.AreEqual("web.config", cscHostObject.AdditionalFiles[0].ItemSpec);
        }
Example #12
0
        public override bool Execute()
        {
            string defDir = SafePath(ThriftDefinitionDir.ItemSpec);

            //look for last compilation timestamp
            string lastBuildPath = Path.Combine(defDir, LastCompilationName);
            string lastWrite = LastWriteTime(defDir);

            if (File.Exists(lastBuildPath))
            {
                string lastComp = File.ReadAllText(lastBuildPath);

                var f = new FileInfo(ThriftLibrary.ItemSpec);

                string thriftLibTime = f.LastWriteTimeUtc.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture);
                if (ThriftIsModified(thriftLibTime, lastComp))
                {
                    lastWrite = thriftLibTime;
                }
                else if (ThriftIsUpToDate(thriftLibTime, lastWrite, lastComp))
                {
                    LogMessage("ThriftImpl up-to-date", MessageImportance.High);
                    return true;
                }
            }

            //find the directory of the thriftlibrary (that's where output will go)
            var thriftLibInfo = new FileInfo(ThriftLibraryPath);
            if (thriftLibInfo.Directory == null)
            {
                LogMessage("ThriftLibraryPath directory does not exist.", MessageImportance.High);
                return false;
            }

            string thriftDir = thriftLibInfo.Directory.FullName;

            DeleteGeneratedFolder(thriftDir);

            LogMessage(defDir, MessageImportance.High);

            //run the thrift executable to generate C#
            foreach (string thriftFile in Directory.GetFiles(defDir, "*.thrift"))
            {
                LogMessage("Generating code for: " + thriftFile, MessageImportance.Normal);
                var p = new Process
                            {
                                StartInfo =
                                    {
                                        FileName = SafePath(ThriftExecutable.ItemSpec),
                                        Arguments = "--gen csharp -o " + SafePath(thriftDir) + " -r " + thriftFile,
                                        UseShellExecute = false,
                                        CreateNoWindow = true,
                                        RedirectStandardOutput = false
                                    }
                            };
                p.Start();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    LogMessage("thrift.exe failed to compile " + thriftFile, MessageImportance.High);
                    return false;
                }
                if (p.ExitCode != 0)
                {
                    LogMessage("thrift.exe failed to compile " + thriftFile, MessageImportance.High);
                    return false;
                }
            }

            string outputPath = Path.Combine(thriftDir, OutputName.ItemSpec);

            var csc = new Csc
                          {
                              TargetType = "library",
                              References = new ITaskItem[] {new TaskItem(ThriftLibrary.ItemSpec)},
                              EmitDebugInformation = true,
                              OutputAssembly = new TaskItem(outputPath),
                              Sources = FindSources(Path.Combine(thriftDir, "gen-csharp"), AssemblyInfoPath != null ? AssemblyInfoPath.ItemSpec : null),
                              BuildEngine = this.BuildEngine
                          };

            LogMessage("Compiling generated cs...", MessageImportance.Normal);
            if (!csc.Execute())
            {
                return false;
            }

            DeleteGeneratedFolder(thriftDir);

            //write file to defDir to indicate a build was successfully completed
            File.WriteAllText(lastBuildPath, lastWrite);

            ThriftImplementation = new TaskItem(outputPath);

            return true;
        }
Example #13
0
        // Ignore: Test requires installed toolset.
        public void FileTrackerDoNotRecordWriteAsRead()
        {
            Console.WriteLine("Test: FileTrackerDoNotRecordWriteAsRead");

            File.Delete("writenoread.read.1.tlog");
            File.Delete("writenoread.write.1.tlog");

            string testDirectory = Path.Combine(Environment.CurrentDirectory, "FileTrackerDoNotRecordWriteAsRead");

            if (Directory.Exists(testDirectory))
            {
                ObjectModelHelpers.DeleteDirectory(testDirectory);
                Directory.Delete(testDirectory, true /* recursive delete */);
            }

            Directory.CreateDirectory(testDirectory);
            string codeFile = null;
            string writeFile = null;
            string outputFile = Path.Combine(testDirectory, "writenoread.exe");

            try
            {
                writeFile = Path.Combine(testDirectory, "test.out");
                codeFile = Path.Combine(testDirectory, "code.cs");
                string codeContent = @"
using System.IO; 
using System.Runtime.InteropServices;
class X 
{ 
    static void Main() 
    { 
        FileStream f = File.Open(@""" + writeFile + @""", FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
        f.WriteByte(8);
        f.Close();
    }
}";

                File.WriteAllText(codeFile, codeContent);
                Csc csc = new Csc();
                csc.BuildEngine = new MockEngine();
                csc.Sources = new TaskItem[] { new TaskItem(codeFile) };
                csc.OutputAssembly = new TaskItem(outputFile);
                bool success = csc.Execute();

                Assert.IsTrue(success);

                string trackerPath = FileTracker.GetTrackerPath(ExecutableType.ManagedIL);
                string fileTrackerPath = FileTracker.GetFileTrackerPath(ExecutableType.ManagedIL);
                string commandArgs = "/d \"" + fileTrackerPath + "\" /o /c \"" + outputFile + "\"";

                int exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);
            }
            finally
            {
                // Doesn't delete the directory itself, but deletes its contents.  If you try to delete the directory, 
                // even after calling this method, it sometimes throws IO exceptions due to not recognizing that the 
                // contents have been deleted yet. 
                ObjectModelHelpers.DeleteDirectory(testDirectory);
            }

            if (writeFile != null)
            {
                FileTrackerTestHelper.AssertDidntFindStringInTLog("CreateFileW, Desired Access=0xc0000000, Creation Disposition=0x1:" + writeFile.ToUpperInvariant(), "writenoread.read.1.tlog");
                FileTrackerTestHelper.AssertFoundStringInTLog("CreateFileW, Desired Access=0xc0000000, Creation Disposition=0x1:" + writeFile.ToUpperInvariant(), "writenoread.write.1.tlog");
            }
            else
            {
                Assert.Fail("The output file was never assigned or written to");
            }
        }
Example #14
0
        // Ignore: Test requires installed toolset.
        public void FileTrackerFindStrInIncludeDuplicates()
        {
            Console.WriteLine("Test: FileTrackerFindStrInIncludeDuplicates");

            File.Delete("findstr.read.1.tlog");
            FileTrackerTestHelper.WriteAll("test.in", "foo");

            string codeFile = null;
            string outputFile = Path.Combine(Path.GetTempPath(), "readtwice.exe");
            File.Delete(outputFile);

            try
            {
                string inputPath = Path.GetFullPath("test.in");
                codeFile = FileUtilities.GetTemporaryFile();
                string codeContent = @"using System.IO; class X { static void Main() { File.ReadAllText(@""" + inputPath + @"""); File.ReadAllText(@""" + inputPath + @"""); }}";
                File.WriteAllText(codeFile, codeContent);
                Csc csc = new Csc();
                csc.BuildEngine = new MockEngine();
                csc.Sources = new TaskItem[] { new TaskItem(codeFile) };
                csc.OutputAssembly = new TaskItem(outputFile);
                csc.Execute();

                string trackerPath = FileTracker.GetTrackerPath(ExecutableType.ManagedIL);
                string fileTrackerPath = FileTracker.GetFileTrackerPath(ExecutableType.ManagedIL);
                string commandArgs = "/d \"" + fileTrackerPath + "\" /u /c \"" + outputFile + "\"";

                int exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);
            }
            finally
            {
                File.Delete(codeFile);
                File.Delete(outputFile);
            }

            FileTrackerTestHelper.AssertFoundStringInTLog(Path.GetFullPath("test.in").ToUpperInvariant(), "readtwice.read.1.tlog", 2);
        }
Example #15
0
        // Ignore: Test requires installed toolset.
        public void FileTrackerExtendedDirectoryTracking()
        {
            Console.WriteLine("Test: FileTrackerExtendedDirectoryTracking");

            File.Delete("directoryattributes.read.1.tlog");
            File.Delete("directoryattributes.write.1.tlog");

            string codeFile = null;
            string outputFile = Path.Combine(Path.GetTempPath(), "directoryattributes.exe");
            string codeContent = @"
using System.IO;
using System.Runtime.InteropServices;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            File.GetAttributes(Directory.GetCurrentDirectory());
            GetFileAttributes(Directory.GetCurrentDirectory()); 
        }

        [DllImport(""Kernel32.dll"", SetLastError = true, CharSet = CharSet.Unicode)]
        private extern static uint GetFileAttributes(string FileName); 
    }
}";

            File.Delete(outputFile);

            try
            {
                codeFile = FileUtilities.GetTemporaryFile();
                File.WriteAllText(codeFile, codeContent);
                Csc csc = new Csc();
                csc.BuildEngine = new MockEngine();
                csc.Sources = new ITaskItem[] { new TaskItem(codeFile) };
                csc.OutputAssembly = new TaskItem(outputFile);
                csc.Execute();

                string trackerPath = FileTracker.GetTrackerPath(ExecutableType.ManagedIL);
                string fileTrackerPath = FileTracker.GetFileTrackerPath(ExecutableType.ManagedIL);
                string commandArgs = "/d \"" + fileTrackerPath + "\" /o /u /e /c \"" + outputFile + "\"";

                int exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);

                // Should track directories when '/e' is passed
                FileTrackerTestHelper.AssertFoundStringInTLog("GetFileAttributesExW:" + FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");
                FileTrackerTestHelper.AssertFoundStringInTLog("GetFileAttributesW:" + FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");

                File.Delete("directoryattributes.read.1.tlog");
                File.Delete("directoryattributes.write.1.tlog");

                commandArgs = "/d \"" + fileTrackerPath + "\" /o /u /a /c \"" + outputFile + "\"";

                exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);

                // With '/a', should *not* track GetFileAttributes on directories, even though we do so on files. 
                FileTrackerTestHelper.AssertDidntFindStringInTLog("GetFileAttributesExW:" + FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");
                FileTrackerTestHelper.AssertDidntFindStringInTLog("GetFileAttributesW:" + FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");

                File.Delete("directoryattributes.read.1.tlog");
                File.Delete("directoryattributes.write.1.tlog");

                commandArgs = "/d \"" + fileTrackerPath + "\" /o /u /c \"" + outputFile + "\"";

                exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);

                // With neither '/a' nor '/e', should not do any directory tracking whatsoever
                FileTrackerTestHelper.AssertDidntFindStringInTLog("GetFileAttributesExW:" + FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");
                FileTrackerTestHelper.AssertDidntFindStringInTLog("GetFileAttributesW:" + FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");

                File.Delete("directoryattributes.read.1.tlog");
                File.Delete("directoryattributes.write.1.tlog");

                commandArgs = "/d \"" + fileTrackerPath + "\" /u /e /c \"" + outputFile + "\"";

                exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);

                // Should track directories when '/e' is passed
                FileTrackerTestHelper.AssertFoundStringInTLog(FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");

                File.Delete("directoryattributes.read.1.tlog");
                File.Delete("directoryattributes.write.1.tlog");

                commandArgs = "/d \"" + fileTrackerPath + "\" /u /a /c \"" + outputFile + "\"";

                exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);

                // With '/a', should *not* track GetFileAttributes on directories, even though we do so on files. 
                FileTrackerTestHelper.AssertDidntFindStringInTLog(FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");

                File.Delete("directoryattributes.read.1.tlog");
                File.Delete("directoryattributes.write.1.tlog");

                commandArgs = "/d \"" + fileTrackerPath + "\" /u /c \"" + outputFile + "\"";

                exit = FileTrackerTestHelper.RunCommand(trackerPath, commandArgs);
                Console.WriteLine("");
                Assert.AreEqual(0, exit);

                // With neither '/a' nor '/e', should not do any directory tracking whatsoever
                FileTrackerTestHelper.AssertDidntFindStringInTLog(FileUtilities.EnsureTrailingSlash(Directory.GetCurrentDirectory()).ToUpperInvariant(), "directoryattributes.read.1.tlog");
            }
            finally
            {
                File.Delete(codeFile);
                File.Delete(outputFile);
            }
        }
Example #16
0
        // Ignore: Test requires installed toolset.
        public void LaunchMultipleOfSameTool_ToolLaunchesOthers()
        {
            string testDir = Path.Combine(Path.GetTempPath(), "LaunchMultipleOfSameTool_ToolLaunchesOthers");

            try
            {
                if (FileUtilities.DirectoryExistsNoThrow(testDir))
                {
                    FileUtilities.DeleteDirectoryNoThrow(testDir, true);
                }

                Directory.CreateDirectory(testDir);

                // File to run findstr against. 
                string tempFilePath = Path.Combine(testDir, "bar.txt");
                File.WriteAllText(tempFilePath, "");

                // Sample app that runs findstr.
                string codeFile = null;
                string outputFile = Path.Combine(testDir, "FindstrLauncher.exe");
                string codeContent = @"
using System;
using System.Diagnostics;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 1)
            {
                for (int i = 0; i < Int32.Parse(args[0]); i++)
                {
                    Process p = Process.Start(""findstr"", ""/i foo "" + args[1]);
                    p.WaitForExit();
                }
            }
        }
    }
}";

                File.Delete(outputFile);

                codeFile = Path.Combine(testDir, "Program.cs");
                File.WriteAllText(codeFile, codeContent);
                Csc csc = new Csc();
                csc.BuildEngine = new MockEngine();
                csc.Sources = new ITaskItem[] { new TaskItem(codeFile) };
                csc.OutputAssembly = new TaskItem(outputFile);
                csc.Platform = "x86";
                bool compileSucceeded = csc.Execute();

                Assert.IsTrue(compileSucceeded);

                // Item1: appname
                // Item2: command line
                // Item3: number of times to launch
                IList<Tuple<string, string, int>> toolsToLaunch = new List<Tuple<string, string, int>>();
                toolsToLaunch.Add(new Tuple<string, string, int>(outputFile, outputFile + " 3 " + tempFilePath, 3));

                // Item1: FileTracker context name
                // Item2: Tuple <string, string, int> as described above
                IList<Tuple<string, IList<Tuple<string, string, int>>>> contextSpecifications = new List<Tuple<string, IList<Tuple<string, string, int>>>>();
                contextSpecifications.Add(new Tuple<string, IList<Tuple<string, string, int>>>("ProcessLaunchTest", toolsToLaunch));
                contextSpecifications.Add(new Tuple<string, IList<Tuple<string, string, int>>>("ProcessLaunchTest2", toolsToLaunch));

                // Item1: tlog pattern
                // Item2: # times it's expected to appear
                IList<Tuple<string, int>> tlogPatterns = new List<Tuple<string, int>>();
                tlogPatterns.Add(new Tuple<string, int>("ProcessLaunchTest-FindstrLauncher-findstr*tlog", 3));
                tlogPatterns.Add(new Tuple<string, int>("ProcessLaunchTest-FindstrLauncher.*-findstr*tlog", 6));
                tlogPatterns.Add(new Tuple<string, int>("ProcessLaunchTest2-FindstrLauncher-findstr*tlog", 3));
                tlogPatterns.Add(new Tuple<string, int>("ProcessLaunchTest2-FindstrLauncher.*-findstr*tlog", 6));

                LaunchDuplicateToolsAndVerifyTlogExistsForEach(testDir, contextSpecifications, tlogPatterns, createTestDirectory: false);
            }
            finally
            {
                if (FileUtilities.DirectoryExistsNoThrow(testDir))
                {
                    FileUtilities.DeleteDirectoryNoThrow(testDir, true);
                }
            }
        }