Exemplo n.º 1
0
 public void Constructor_Empty_FileNameExtensionTmp()
 {
     using (var temporaryFile = new TemporaryFile())
     {
         Assert.That(Path.GetExtension(temporaryFile.FileName), Is.EqualTo(".tmp"));
     }
 }
Exemplo n.º 2
0
        public void TestExportFeeds()
        {
            using (var feedFile1 = new TemporaryFile("0install-unit-tests"))
            using (var feedFile2 = new TemporaryFile("0install-unit-tests"))
            {
                var feedCacheMock = CreateMock<IFeedCache>();

                feedCacheMock.Setup(x => x.GetPath(FeedTest.Sub1Uri)).Returns(feedFile1);
                feedCacheMock.Setup(x => x.GetPath(FeedTest.Sub2Uri)).Returns(feedFile2);

                var signature = new ValidSignature(123, new byte[0], new DateTime(2000, 1, 1));
                feedCacheMock.Setup(x => x.GetSignatures(FeedTest.Sub1Uri)).Returns(new OpenPgpSignature[] { signature });
                feedCacheMock.Setup(x => x.GetSignatures(FeedTest.Sub2Uri)).Returns(new OpenPgpSignature[] { signature });

                var openPgpMock = CreateMock<IOpenPgp>();
                openPgpMock.Setup(x => x.ExportKey(signature)).Returns("abc");

                _target.ExportFeeds(feedCacheMock.Object, openPgpMock.Object);

                string contentDir = Path.Combine(_destination, "content");
                FileAssert.AreEqual(
                    expected: new FileInfo(feedFile1),
                    actual: new FileInfo(Path.Combine(contentDir, FeedTest.Sub1Uri.PrettyEscape())),
                    message: "Feed should be exported.");
                FileAssert.AreEqual(
                    expected: new FileInfo(feedFile2),
                    actual: new FileInfo(Path.Combine(contentDir, FeedTest.Sub2Uri.PrettyEscape())),
                    message: "Feed should be exported.");

                File.ReadAllText(Path.Combine(contentDir, "000000000000007B.gpg")).Should()
                    .Be("abc", because: "GPG keys should be exported.");
            }
        }
Exemplo n.º 3
0
        public void ShouldApplyDeltaToPreviousPackageToCreateNewPackage()
        {
            using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0.0")))
            using (var signatureFile = new TemporaryFile(basisFile.FilePath + ".octosig"))
            {
                var signatureResult = Invoke(OctoDiff()
                    .Action("signature")
                    .PositionalArgument(basisFile.FilePath)
                    .PositionalArgument(signatureFile.FilePath));
                
                signatureResult.AssertZero();
                Assert.That(File.Exists(signatureFile.FilePath));

                using (var newFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0.1", true)))
                using (var deltaFile = new TemporaryFile(basisFile.FilePath + "_to_" + NewFileName + ".octodelta"))
                {
                    var deltaResult = Invoke(OctoDiff()
                        .Action("delta")
                        .PositionalArgument(signatureFile.FilePath)
                        .PositionalArgument(newFile.FilePath)
                        .PositionalArgument(deltaFile.FilePath));

                    deltaResult.AssertZero();
                    Assert.That(File.Exists(deltaFile.FilePath));

                    var patchResult = ApplyDelta(basisFile.FilePath, basisFile.Hash, deltaFile.FilePath, NewFileName);
                    patchResult.AssertZero();
                    patchResult.AssertOutput("Applying delta to {0} with hash {1} and storing as {2}", basisFile.FilePath,
                        basisFile.Hash, Path.Combine(DownloadPath, NewFileName));
                    patchResult.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Compiles a string of C# code using the newest C# compiler available on the system.
        /// </summary>
        /// <param name="compilerParameters">The compiler configuration (e.g. output file path).</param>
        /// <param name="code">The C# code to compile.</param>
        /// <param name="manifest">The contents of the Win32 manifest to apply to the output file. Will only be applied if a C# 3.0 or newer compiler is available.</param>
        public static void CompileCSharp([NotNull] this CompilerParameters compilerParameters, [NotNull, Localizable(false)] string code, [NotNull, Localizable(false)] string manifest)
        {
            #region Sanity checks
            if (compilerParameters == null) throw new ArgumentNullException(nameof(compilerParameters));
            if (string.IsNullOrEmpty(code)) throw new ArgumentNullException(nameof(code));
            if (string.IsNullOrEmpty(manifest)) throw new ArgumentNullException(nameof(manifest));
            #endregion

            // Make sure the containing directory exists
            string directory = Path.GetDirectoryName(Path.GetFullPath(compilerParameters.OutputAssembly));
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) Directory.CreateDirectory(directory);

            using (var manifestFile = new TemporaryFile("0install"))
            {
                File.WriteAllText(manifestFile, manifest);

                var compiler = GetCSharpCompiler(compilerParameters, manifestFile);
                var compilerResults = compiler.CompileAssemblyFromSource(compilerParameters, code);

                if (compilerResults.Errors.HasErrors)
                {
                    var error = compilerResults.Errors[0];
                    if (error.ErrorNumber == "CS0016") throw new IOException(error.ErrorText);
                    else throw new InvalidOperationException("Compilation error " + error.ErrorNumber + " in line " + error.Line + Environment.NewLine + error.ErrorText);
                }
            }
        }
Exemplo n.º 5
0
        public void ShouldFindOneEarlierPackageVersion()
        {
            using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion)))
            {
                var destinationFilePath = Path.Combine(downloadPath,
                    Path.GetFileName(acmeWeb.FilePath) + "-" + Guid.NewGuid());
                File.Copy(acmeWeb.FilePath, destinationFilePath);

                using (var newAcmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, newpackageVersion)))
                {
                    var result = FindPackages(packageId, newpackageVersion, newAcmeWeb.Hash);

                    result.AssertZero();
                    result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, newpackageVersion,
                        newAcmeWeb.Hash);
                    result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle");
                    result.AssertOutput("Found 1 earlier version of {0} on this Tentacle", packageId);
                    result.AssertOutput("  - {0}: {1}", packageVersion, destinationFilePath);

                    result.AssertServiceMessage(ServiceMessageNames.FoundPackage.Name, Is.True,
                        new Dictionary<string, object>
                    {
                        {"Metadata.Id", packageId},
                        {"Metadata.Version", packageVersion},
                        {"Metadata.Hash", acmeWeb.Hash},
                        {"FullPath", destinationFilePath}
                    });
                }
            }
        }
Exemplo n.º 6
0
        /// <inheritdoc/>
        public IEnumerable<OpenPgpSignature> Verify(byte[] data, byte[] signature)
        {
            #region Sanity checks
            if (data == null) throw new ArgumentNullException(nameof(data));
            if (signature == null) throw new ArgumentNullException(nameof(signature));
            #endregion

            string result;
            using (var signatureFile = new TemporaryFile("0install-sig"))
            {
                File.WriteAllBytes(signatureFile, signature);
                result = new CliControl(HomeDir, data).Execute("--batch", "--no-secmem-warning", "--status-fd", "1", "--verify", signatureFile.Path, "-");
            }
            string[] lines = result.SplitMultilineText();

            // Each signature is represented by one line of encoded information
            var signatures = new List<OpenPgpSignature>(lines.Length);
            foreach (var line in lines)
            {
                try
                {
                    var parsedSignature = ParseSignatureLine(line);
                    if (parsedSignature != null) signatures.Add(parsedSignature);
                }
                    #region Error handling
                catch (FormatException ex)
                {
                    // Wrap exception since only certain exception types are allowed
                    throw new IOException(ex.Message, ex);
                }
                #endregion
            }

            return signatures;
        }
        public void Execute(BoostTestRunnerCommandLineArgs args, BoostTestRunnerSettings settings, IProcessExecutionContext executionContext)
        {
            var fixedArgs = args;

            if (args != null)
            {
                // Adapt a copy of the command-line arguments to avoid changing the original
                fixedArgs = AdaptArguments(args.Clone());
            }

            using (var stderr = new TemporaryFile(IsStandardErrorFileDifferent(args, fixedArgs) ? fixedArgs.StandardErrorFile : null))
            {
                this.Runner.Execute(fixedArgs, settings, executionContext);

                // Extract the report output to its intended location
                string source = (fixedArgs == null) ? null : fixedArgs.StandardErrorFile;
                string destination = (args == null) ? null : args.ReportFile;

                if ((source != null) && (destination != null))
                {
                    try
                    {
                        ExtractReport(source, destination, string.IsNullOrEmpty(stderr.Path));
                    }
                    catch (Exception ex)
                    {
                        Logger.Exception(ex, "Failed to extract test report from standard error [{0}] to report file [{1}] ({2})", source, destination, ex.Message);
                    }
                }
            }
        }
Exemplo n.º 8
0
 private static TemporaryFile Deploy(Stream stream)
 {
     var tempFile = new TemporaryFile("0install-unit-tests");
     using (var fileStream = File.Create(tempFile))
         stream.CopyTo(fileStream);
     return tempFile;
 }
Exemplo n.º 9
0
        public override void Activation()
        {
            base.Activation();

            m_prevActive = false;
            string report = Exec("pfctl -si");
            if (report.IndexOf ("denied") != -1)
                throw new Exception("Permission denied.");
            else if (report.IndexOf ("Status: Enabled") != -1)
                m_prevActive = true;
            else if (report.IndexOf("Status: Disabled") != -1)
                m_prevActive = false;
            else
                throw new Exception("Unexpected PF Firewall status");

            if (m_prevActive == false) {
                string reportActivation = Exec ("pfctl -e");
                if (reportActivation.IndexOf ("pf enabled") == -1)
                    throw new Exception ("Unexpected PF Firewall activation failure");
            }
            m_filePfConf = new TemporaryFile("pf.conf");

            OnUpdateIps();

            if (m_prevActive == false)
            {
                Exec("pfctl -e");
            }
        }
Exemplo n.º 10
0
        public void ConvertCsvToExcel_MicrosoftOfficeInteropExcel()
        {
            StringBuilder content = new StringBuilder();
            content.AppendLine("param1\tparam2\tstatus");
            content.AppendLine("0.5\t10\tpassed");
            content.AppendLine("10\t20\tfail");

            using (TemporaryFile xlsxFile = new TemporaryFile(".xlsx"))
            {
                Clipboard.SetText(content.ToString());
                Microsoft.Office.Interop.Excel.Application xlexcel;
                Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
                Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;
                xlexcel = new Microsoft.Office.Interop.Excel.Application();
                // for excel visibility
                //xlexcel.Visible = true;
                // Creating a new workbook
                xlWorkBook = xlexcel.Workbooks.Add(misValue);
                // Putting Sheet 1 as the sheet you want to put the data within
                xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1);
                // creating the range
                Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range) xlWorkSheet.Cells[1, 1];
                CR.Select();
                xlWorkSheet.Paste(CR, false);
                xlWorkSheet.SaveAs(xlsxFile.FileName);                
                xlexcel.Quit();
                Console.WriteLine("Created file {0}", xlsxFile.FileName);
            }
        }
Exemplo n.º 11
0
 public void Constructor_Empty_FileExists()
 {
     using (var temporaryFile = new TemporaryFile())
     {
         Assert.That(File.Exists(temporaryFile.FileName), Is.True);
     }
 }
Exemplo n.º 12
0
        public DownloadResult( ILog logger, Stream zipContent )
        {
            File = new TemporaryFile( ".zip" );
            using( zipContent )
            using( var sw = System.IO.File.Open( File.Path, FileMode.Open ) )
                zipContent.CopyTo( sw );

            try
            {
                // open the zip file
                using( ZipFile zip = ZipFile.Read( File.Path ) )
                {
                    var manifestEntry = zip.Where( z => z.FileName == "manifest.xml" ).FirstOrDefault();
                    if( manifestEntry != null )
                    {
                        var ms = new MemoryStream();
                        manifestEntry.Extract( ms );
                        try
                        {
                            Manifest = HelpManifestData.Deserialize( ms );
                        }
                        catch( Exception ex )
                        {
                            logger.Error( "Unable to parse manifest", ex );
                            throw;
                        }
                    }
                }
            }
            catch( Exception ex )
            {
                logger.Error( "Unable to read downloaded help content as a zip file", ex );
                throw;
            }
        }
Exemplo n.º 13
0
 public void MatchingFile()
 {
     using (var file = new TemporaryFile())
     {
         Assert.IsTrue(filter.IsMatch(file.FileInfo, environment));
     }
 }
Exemplo n.º 14
0
 public void Constructor_Empty_FilePlacedIntoTemporaryFolder()
 {
     using (var temporaryFile = new TemporaryFile())
     {
         Assert.That(Path.GetDirectoryName(temporaryFile.FileName) + @"\", Is.EqualTo(Path.GetTempPath()));
     }
 }
Exemplo n.º 15
0
 public void OldFile_IsMatch_ReturnsTrue()
 {
     using (var file = new TemporaryFile())
     {
         file.FileInfo.LastWriteTime = DateTime.Now.Subtract(TimeSpan.FromDays(2));
         Assert.IsTrue(filter.IsMatch(file.FileInfo, environment));
     }
 }
Exemplo n.º 16
0
 public void NewFile_IsMatch_ReturnsFalse()
 {
     using (var file = new TemporaryFile())
     {
         file.FileInfo.LastWriteTime = DateTime.Now;
         Assert.IsFalse(filter.IsMatch(file.FileInfo, environment));
     }
 }
Exemplo n.º 17
0
 public void TestCopyToFile()
 {
     using (var tempFile = new TemporaryFile("unit-tests"))
     {
         "abc".ToStream().CopyToFile(tempFile);
         new FileInfo(tempFile).ReadFirstLine(Encoding.UTF8).Should().Be("abc");
     }
 }
Exemplo n.º 18
0
 public void NonMatchingFile()
 {
     using (var file = new TemporaryFile())
     {
         file.Contents = "01234";
         Assert.IsFalse(filter.IsMatch(file.FileInfo, environment));
     }
 }
Exemplo n.º 19
0
 public void Dispose_Empty_FileDeleted()
 {
     string fileName;
     using (var temporaryFile = new TemporaryFile())
     {
         fileName = temporaryFile.FileName;
     }
     Assert.That(File.Exists(fileName), Is.False);
 }
Exemplo n.º 20
0
 public void PowershellDecryptsSensitiveVariables()
 {
     using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1")))
     {
         File.WriteAllText(scriptFile.FilePath, "Write-Host $mysecrect");
         var result = ExecuteScript(new PowerShellScriptEngine(), scriptFile.FilePath, GetDictionaryWithSecret());
         result.AssertOutput("KingKong");
     }
 }
Exemplo n.º 21
0
 public void CSharpDecryptsSensitiveVariables()
 {
     using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "cs")))
     {
         File.WriteAllText(scriptFile.FilePath, "System.Console.WriteLine(Octopus.Parameters[\"mysecrect\"]);");
         var result = ExecuteScript(new ScriptCSScriptEngine(), scriptFile.FilePath, GetDictionaryWithSecret());
         result.AssertOutput("KingKong");
     }
 }
Exemplo n.º 22
0
 public void BashDecryptsSensitiveVariables()
 {
     using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "sh")))
     {
         File.WriteAllText(scriptFile.FilePath, "#!/bin/bash\necho $(get_octopusvariable \"mysecrect\")");
         var result = ExecuteScript(new BashScriptEngine(), scriptFile.FilePath, GetDictionaryWithSecret());
         result.AssertOutput("KingKong");
     }
 }
 public void Test_WithContent()
 {
     // Act.
     using (var temp = new TemporaryFile("stuff"))
     {
         // Assert.
         Assert.True(temp.File.Exists);
         Assert.Equal("stuff", File.ReadAllText(temp.File.FullName));
     }
 }
Exemplo n.º 24
0
        public void TestSet()
        {
            using (var flagFile = new TemporaryFile("0install-unit-tests"))
            {
                FlagUtils.Set(flagFile, Path.Combine("dir1", "file1"));
                File.ReadAllText(flagFile).Should().Be("/dir1/file1\n");

                FlagUtils.Set(flagFile, Path.Combine("dir2", "file2"));
                File.ReadAllText(flagFile).Should().Be("/dir1/file1\n/dir2/file2\n");
            }
        }
Exemplo n.º 25
0
        public void TemporaryFileSimpleDemo()
        {
            using (TemporaryFile temporaryFile = new TemporaryFile())
            {
                File.WriteAllText(temporaryFile.FileName, "[0]: test");
                File.AppendAllText(temporaryFile.FileName, "[1]: additional text");

                string allText = File.ReadAllText(temporaryFile.FileName);
                Assert.That(allText, Is.EqualTo("[0]: test" + "[1]: additional text"));
            }
        }
        public void Test_File()
        {
            // Arrange.
            var temp = new TemporaryFile();

            // Act.
            var file = temp.File;

            // Assert.
            Assert.NotNull(file);
            Assert.Equal(Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar), file.DirectoryName.TrimEnd(Path.DirectorySeparatorChar));
        }
Exemplo n.º 27
0
        public void ShouldFindNoEarlierPackageVersions()
        {
            using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion)))
            {
                var result = FindPackages(packageId, packageVersion, acmeWeb.Hash);

                result.AssertZero();
                result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, packageVersion, acmeWeb.Hash);
                result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle");
                result.AssertOutput("No earlier packages for {0} has been uploaded", packageId);
            }
        }
        public void Test_Dispose()
        {
            // Arrange.
            var temp = new TemporaryFile().Touch();

            // Act.
            temp.Dispose();
            temp.File.Refresh();

            // Assert.
            Assert.False(temp.File.Exists);
        }
Exemplo n.º 29
0
 public static string HashWithGit(Stream file)
 {
     // Write the data to a file and insert that, so that git will handle any
     // EOL and encoding issues.
     using (var tempFile = new TemporaryFile())
     {
         using (var tempStream = File.Create(tempFile))
         {
             file.CopyTo(tempStream);
         }
         return HashWithGit(tempFile);
     }
 }
Exemplo n.º 30
0
        CalamariResult DeployPackage(string packageName)
        {
            using (var variablesFile = new TemporaryFile(Path.GetTempFileName()))
            using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageName, "1.0.0")))
            {
                variables.Save(variablesFile.FilePath);

                return Invoke(Calamari()
                    .Action("deploy-azure-web")
                    .Argument("package", acmeWeb.FilePath)
                    .Argument("variables", variablesFile.FilePath));       
            }
        }
Exemplo n.º 31
0
        public CommandResult ExecuteScript(IScriptEngine scriptEngine, Script script, CalamariVariableDictionary variables, ICommandLineRunner commandLineRunner)
        {
            if (!ServiceFabricHelper.IsServiceFabricSdkKeyInRegistry())
            {
                throw new Exception("Could not find the Azure Service Fabric SDK on this server. This SDK is required before running Service Fabric commands.");
            }

            var workingDirectory = Path.GetDirectoryName(script.File);

            variables.Set("OctopusFabricTargetScript", "\"" + script.File + "\"");
            variables.Set("OctopusFabricTargetScriptParameters", script.Parameters);

            // Azure PS modules are required for looking up Azure environments (needed for AAD url lookup in Service Fabric world).
            SetAzureModulesLoadingMethod(variables);

            // Read thumbprint from our client cert variable (if applicable).
            var securityMode         = variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode);
            var clientCertThumbprint = string.Empty;

            if (securityMode == AzureServiceFabricSecurityMode.SecureClientCertificate.ToString())
            {
                var certificateVariable = GetMandatoryVariable(variables, SpecialVariables.Action.ServiceFabric.ClientCertVariable);
                clientCertThumbprint = variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Thumbprint}");
            }

            // Set output variables for our script to access.
            SetOutputVariable("OctopusFabricConnectionEndpoint", variables.Get(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint), variables);
            SetOutputVariable("OctopusFabricSecurityMode", variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode), variables);
            SetOutputVariable("OctopusFabricServerCertThumbprint", variables.Get(SpecialVariables.Action.ServiceFabric.ServerCertThumbprint), variables);
            SetOutputVariable("OctopusFabricClientCertThumbprint", clientCertThumbprint, variables);
            SetOutputVariable("OctopusFabricCertificateFindType", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateFindType, "FindByThumbprint"), variables);
            SetOutputVariable("OctopusFabricCertificateFindValueOverride", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateFindValueOverride), variables);
            SetOutputVariable("OctopusFabricCertificateStoreLocation", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreLocation, "LocalMachine"), variables);
            SetOutputVariable("OctopusFabricCertificateStoreName", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreName, "MY"), variables);
            SetOutputVariable("OctopusFabricAadCredentialType", variables.Get(SpecialVariables.Action.ServiceFabric.AadCredentialType), variables);
            SetOutputVariable("OctopusFabricAadClientCredentialSecret", variables.Get(SpecialVariables.Action.ServiceFabric.AadClientCredentialSecret), variables);
            SetOutputVariable("OctopusFabricAadUserCredentialUsername", variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialUsername), variables);
            SetOutputVariable("OctopusFabricAadUserCredentialPassword", variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialPassword), variables);

            using (new TemporaryFile(Path.Combine(workingDirectory, "AzureProfile.json")))
                using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory)))
                {
                    return(scriptEngine.Execute(new Script(contextScriptFile.FilePath), variables, commandLineRunner));
                }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Compiles a string of C# code using the newest C# compiler available on the system.
        /// </summary>
        /// <param name="compilerParameters">The compiler configuration (e.g. output file path).</param>
        /// <param name="code">The C# code to compile.</param>
        /// <param name="manifest">The contents of the Win32 manifest to apply to the output file. Will only be applied if a C# 3.0 or newer compiler is available.</param>
        public static void CompileCSharp([NotNull] this CompilerParameters compilerParameters, [NotNull, Localizable(false)] string code, [NotNull, Localizable(false)] string manifest)
        {
            #region Sanity checks
            if (compilerParameters == null)
            {
                throw new ArgumentNullException(nameof(compilerParameters));
            }
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException(nameof(code));
            }
            if (string.IsNullOrEmpty(manifest))
            {
                throw new ArgumentNullException(nameof(manifest));
            }
            #endregion

            // Make sure the containing directory exists
            string directory = Path.GetDirectoryName(Path.GetFullPath(compilerParameters.OutputAssembly));
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            using (var manifestFile = new TemporaryFile("0install"))
            {
                File.WriteAllText(manifestFile, manifest);

                var compiler        = GetCSharpCompiler(compilerParameters, manifestFile);
                var compilerResults = compiler.CompileAssemblyFromSource(compilerParameters, code);

                if (compilerResults.Errors.HasErrors)
                {
                    var error = compilerResults.Errors[0];
                    if (error.ErrorNumber == "CS0016")
                    {
                        throw new IOException(error.ErrorText);
                    }
                    else
                    {
                        throw new InvalidOperationException("Compilation error " + error.ErrorNumber + " in line " + error.Line + Environment.NewLine + error.ErrorText);
                    }
                }
            }
        }
Exemplo n.º 33
0
        public void VerifyAllConfigOptionsMappedToConfigObject()
        {
            var pipelineConfigObj = new Dictionary<string, object>
            {
                ["outputs"] = new List<Dictionary<string, object>>
                {
                    new Dictionary<string, object>
                    {
                        ["type"] = "ElasticSearch",
                        ["indexNamePrefix"] = "myprefix",
                        ["eventDocumentTypeName"] = "mytype",
                        ["serviceUri"] = "http://localhost:1000",
                        ["basicAuthenticationUserName"] = "******",
                        ["basicAuthenticationUserPassword"] = "******",
                        ["numberOfShards"] = 10,
                        ["numberOfReplicas"] = 20,
                        ["refreshInterval"] = "60s",
                    }
                }
            };

            using (var configFile = new TemporaryFile())
            {
                var pipelineConfig = JsonConvert.SerializeObject(pipelineConfigObj);

                configFile.Write(pipelineConfig);
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile(configFile.FilePath);
                var configuration = configBuilder.Build();
                var outputConfigSection = configuration.GetSection("outputs");
                var configFragments = outputConfigSection.GetChildren().ToList();

                var esOutputConfiguration = new ElasticSearchOutputConfiguration();
                configFragments[0].Bind(esOutputConfiguration);

                Assert.Equal(esOutputConfiguration.IndexNamePrefix, "myprefix");
                Assert.Equal(esOutputConfiguration.EventDocumentTypeName, "mytype");
                Assert.Equal(esOutputConfiguration.ServiceUri, "http://localhost:1000");
                Assert.Equal(esOutputConfiguration.BasicAuthenticationUserName, "myesuser");
                Assert.Equal(esOutputConfiguration.BasicAuthenticationUserPassword, "myespass");
                Assert.Equal(esOutputConfiguration.NumberOfShards, 10);
                Assert.Equal(esOutputConfiguration.NumberOfReplicas, 20);
                Assert.Equal(esOutputConfiguration.RefreshInterval, "60s");
            }
        }
Exemplo n.º 34
0
        private void DoLosslessCompress(FileInfo file)
        {
            using (MagickImage image = new MagickImage(file))
            {
                CheckFormat(image);

                image.Strip();
                image.Settings.SetDefine(MagickFormat.Png, "exclude-chunks", "all");
                image.Settings.SetDefine(MagickFormat.Png, "include-chunks", "tRNS,gAMA");
                CheckTransparency(image);

                Collection <TemporaryFile> tempFiles = new Collection <TemporaryFile>();

                try
                {
                    TemporaryFile bestFile = null;

                    foreach (int quality in GetQualityList())
                    {
                        TemporaryFile tempFile = new TemporaryFile();
                        tempFiles.Add(tempFile);

                        image.Quality = quality;
                        image.Write(tempFile);

                        if (bestFile == null || bestFile.Length > tempFile.Length)
                        {
                            bestFile = tempFile;
                        }
                    }

                    if (bestFile.Length < file.Length)
                    {
                        bestFile.CopyTo(file);
                    }
                }
                finally
                {
                    foreach (TemporaryFile tempFile in tempFiles)
                    {
                        tempFile.Dispose();
                    }
                }
            }
        }
Exemplo n.º 35
0
        public void ApplySettings(IActivityMonitor monitor)
        {
            using (monitor.OpenInfo($"Executing {_scripts.Count} script(s) on this Workstation."))
                using (var tempPS1 = new TemporaryFile("ps1"))
                {
                    bool             hasError         = false;
                    HashSet <EnvVar> currentVariables = null;
                    foreach (var o in _scripts)
                    {
                        if (hasError)
                        {
                            break;
                        }
                        switch (o)
                        {
                        case HashSet <EnvVar> v: currentVariables = v; break;

                        case ScriptLine script:
                        {
                            using (monitor.OpenTrace($"Executing script Type='{script.Type}', WorkingDir='{script.WorkingDir}', Arguments='{script.Arguments}', ContinueOnNonZeroExitCode='{script.ContinueOnNonZeroExitCode}'."))
                            {
                                monitor.Debug($"With EnvironmentVariables: {currentVariables?.Select( v => v.ToString() ).Concatenate()}.");
                                monitor.Debug(script.Script);
                                System.IO.File.WriteAllText(tempPS1.Path, script.Script);
                                if (!ProcessRunner.RunPowerShell(
                                        monitor,
                                        script.WorkingDir,
                                        tempPS1.Path,
                                        new[] { script.Arguments },
                                        stdErrorLevel: LogLevel.Warn,
                                        currentVariables?.Select(v => (v.Name, Environment.ExpandEnvironmentVariables(v.Value)))))
                                {
                                    hasError |= !script.ContinueOnNonZeroExitCode;
                                    if (!hasError)
                                    {
                                        monitor.Warn("ContinueOnNonZeroExitCode is true: error is ignored.");
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
        }
Exemplo n.º 36
0
        string Upload(string packageName, List <S3FileSelectionProperties> fileSelections)
        {
            var bucketKeyPrefix = $"test/{Guid.NewGuid():N}/";

            fileSelections.ForEach(properties =>
            {
                if (properties is S3MultiFileSelectionProperties multiFileSelectionProperties)
                {
                    multiFileSelectionProperties.BucketKeyPrefix = bucketKeyPrefix;
                }
                if (properties is S3SingleFileSelectionProperties singleFileSelectionProperties)
                {
                    singleFileSelectionProperties.BucketKeyPrefix = bucketKeyPrefix;
                }
            });


            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount");
            variables.Set("AWSAccount.AccessKey", Environment.GetEnvironmentVariable("AWS_Calamari_Access"));
            variables.Set("AWSAccount.SecretKey", Environment.GetEnvironmentVariable("AWS_Calamari_Secret"));
            variables.Set("Octopus.Action.Aws.Region", RegionEndpoint.APSoutheast1.SystemName);
            variables.Set(AwsSpecialVariables.S3.FileSelections, JsonConvert.SerializeObject(fileSelections, GetEnrichedSerializerSettings()));
            variables.Save(variablesFile);

            var packageDirectory = TestEnvironment.GetTestPath("AWS", "S3", packageName);

            using (var package = new TemporaryFile(PackageBuilder.BuildSimpleZip(packageName, "1.0.0", packageDirectory)))
                using (new TemporaryFile(variablesFile))
                {
                    var command = new UploadAwsS3Command();
                    var result  = command.Execute(new[] {
                        "--package", $"{package.FilePath}",
                        "--variables", $"{variablesFile}",
                        "--bucket", BucketName,
                        "--targetMode", S3TargetMode.FileSelections.ToString()
                    });

                    result.Should().Be(0);
                }

            return(bucketKeyPrefix);
        }
Exemplo n.º 37
0
        public void TestSaveLoad()
        {
            using (var tempFile = new TemporaryFile("unit-tests"))
            {
                var grid = new NibbleGrid(new byte[, ] {
                    { 2, 4 }, { 5, 10 }
                });
                grid.Save(tempFile);

                using (var stream = File.OpenRead(tempFile))
                    grid = NibbleGrid.Load(stream);

                grid[0, 0].Should().Be(2);
                grid[0, 1].Should().Be(4);
                grid[1, 0].Should().Be(5);
                grid[1, 1].Should().Be(10);
            }
        }
Exemplo n.º 38
0
        public void TestSaveLoad()
        {
            using (var tempFile = new TemporaryFile("unit-tests"))
            {
                var grid = new ByteGrid(new byte[, ] {
                    { 10, 20 }, { 100, 200 }
                });
                grid.Save(tempFile);

                using (var stream = File.OpenRead(tempFile))
                    grid = ByteGrid.Load(stream);

                grid[0, 0].Should().Be(10);
                grid[0, 1].Should().Be(20);
                grid[1, 0].Should().Be(100);
                grid[1, 1].Should().Be(200);
            }
        }
Exemplo n.º 39
0
        public async Task CompressedContentsDoNotDependOnInputPath()
        {
            var patchBuilder = new XdeltaPatchBuilder(XdeltaPatchSystemFactory.Preferred);

            using (var newFile1 = new TemporaryFile())
                using (var newFile2 = new TemporaryFile())
                    using (var patchFile1 = new TemporaryFile())
                        using (var patchFile2 = new TemporaryFile())
                        {
                            File.WriteAllText(newFile1.Path, "b");
                            File.WriteAllText(newFile2.Path, "b");
                            await patchBuilder.CompressAsync(newFile1.Path, patchFile1.Path);

                            await patchBuilder.CompressAsync(newFile2.Path, patchFile2.Path);

                            CollectionAssert.AreEquivalent(File.ReadAllBytes(patchFile1.Path), File.ReadAllBytes(patchFile2.Path));
                        }
        }
Exemplo n.º 40
0
        public void ShouldNotFindEarlierPackageVersionWhenExactMatchRequested()
        {
            using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion)))
            {
                var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(packageId, VersionFactory.CreateSemanticVersion(packageVersion), ".nupkg"));
                File.Copy(acmeWeb.FilePath, destinationFilePath);

                using (var newAcmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, newpackageVersion)))
                {
                    var result = FindPackagesExact(packageId, newpackageVersion, newAcmeWeb.Hash, true);

                    result.AssertSuccess();
                    result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, newpackageVersion,
                                        newAcmeWeb.Hash);
                    result.AssertNoOutput("Finding earlier packages that have been uploaded to this Tentacle");
                }
            }
        }
Exemplo n.º 41
0
        public void OutOfProcessPowerShellDeployAgent_should_expose_live_output_to_the_deployment_event_recorder()
        {
            var deploymentEventRecorder = new StubDeploymentEventRecorder();

            using (var scriptFile = new TemporaryFile(".ps1", "'hello there'"))
            {
                var data = new DeployAgentData
                {
                    DeployScriptFile = scriptFile.FileInfo.Name,
                    DeployScriptRoot = scriptFile.FileInfo.DirectoryName
                };

                var agent = new OutOfProcessPowerShellDeployAgent(deploymentEventRecorder, ClrVersion.Version2);
                agent.Deploy(data);
            }

            StringAssert.Contains(deploymentEventRecorder.OutputDelegate(), "hello there");
        }
Exemplo n.º 42
0
        private static void TestSaveLoad(AppList appList)
        {
            Assert.That(appList, Is.XmlSerializable);

            AppList appList2;

            using (var tempFile = new TemporaryFile("0install-unit-tests"))
            {
                // Write and read file
                appList.SaveXml(tempFile);
                appList2 = XmlStorage.LoadXml <AppList>(tempFile);
            }

            // Ensure data stayed the same
            appList2.Should().Be(appList, because: "Serialized objects should be equal.");
            appList2.GetHashCode().Should().Be(appList.GetHashCode(), because: "Serialized objects' hashes should be equal.");
            appList2.Should().NotBeSameAs(appList, because: "Serialized objects should not return the same reference.");
        }
Exemplo n.º 43
0
        [Fact] // Ensures local Selections XMLs are correctly detected and parsed.
        public void TestImportSelections()
        {
            var selections = Fake.Selections;

            ExpectFetchUncached(selections,
                                new Implementation {
                ID = "id1", ManifestDigest = new ManifestDigest(sha256: "abc"), Version = new ImplementationVersion("1.0")
            },
                                new Implementation {
                ID = "id2", ManifestDigest = new ManifestDigest(sha256: "xyz"), Version = new ImplementationVersion("1.0")
            });

            using var tempFile = new TemporaryFile("0install-unit-tests");
            selections.SaveXml(tempFile);

            selections.Normalize();
            RunAndAssert(Resources.AllComponentsDownloaded, 0, selections, tempFile);
        }
        public void ShouldPerformReplacementInXmlFileWithANonXmlExtension()
        {
            using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion)))
            {
                Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables);
                Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, XmlFileNameWithNonXmlExtension);
                Variables.Set("/document/key", "new-value");

                var result = DeployPackage(file.FilePath);
                result.AssertSuccess();

                var extractedPackageUpdatedXmlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, XmlFileNameWithNonXmlExtension));

                result.AssertOutput("The file will be tried as multiple formats and will be treated as the first format that can be successfully parsed");
                result.AssertOutput("couldn't be parsed as Json");
                this.Assent(extractedPackageUpdatedXmlFile, TestEnvironment.AssentXmlConfiguration);
            }
        }
Exemplo n.º 45
0
        public void Compress_WithQualitySetTo40_FileIsSmallerThanNormalCompression()
        {
            using (TemporaryFile tempFile = new TemporaryFile(Files.ImageMagickJPG))
            {
                JpegOptimizer optimizer = new JpegOptimizer();
                optimizer.Compress(tempFile);

                IMagickImageInfo info = new MagickImageInfo(tempFile);
                Assert.AreEqual(85, info.Quality);

                File.Copy(Files.ImageMagickJPG, tempFile.FullName, true);

                optimizer.Compress(tempFile, 40);

                info = new MagickImageInfo(tempFile);
                Assert.AreEqual(40, info.Quality);
            }
        }
 public void ExecutionUsingPodServiceAccount_WithServerCert()
 {
     variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString());
     variables.Set(PowerShellVariables.Edition, "Desktop");
     using (var dir = TemporaryDirectory.Create())
         using (var podServiceAccountToken = new TemporaryFile(Path.Combine(dir.DirectoryPath, "podServiceAccountToken")))
             using (var certificateAuthority = new TemporaryFile(Path.Combine(dir.DirectoryPath, "certificateAuthority")))
             {
                 File.WriteAllText(podServiceAccountToken.FilePath, "podServiceAccountToken");
                 File.WriteAllText(certificateAuthority.FilePath, "certificateAuthority");
                 redactMap[podServiceAccountToken.FilePath] = "<podServiceAccountTokenPath>";
                 redactMap[certificateAuthority.FilePath]   = "<certificateAuthorityPath>";
                 variables.Set("Octopus.Action.Kubernetes.PodServiceAccountTokenPath", podServiceAccountToken.FilePath);
                 variables.Set("Octopus.Action.Kubernetes.CertificateAuthorityPath", certificateAuthority.FilePath);
                 var wrapper = CreateWrapper();
                 TestScriptInReadOnlyMode(wrapper).AssertSuccess();
             }
 }
Exemplo n.º 47
0
        public void PowerShellDoesntForceTraceMode(string variableValue)
        {
            using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1")))
            {
                File.WriteAllText(scriptFile.FilePath, "Write-Host $mysecrect");
                var calamariVariableDictionary = GetVariables();
                if (!string.IsNullOrEmpty(variableValue))
                {
                    calamariVariableDictionary.Set("Octopus.Action.PowerShell.PSDebug.Trace", variableValue);
                }

                var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath,
                                           calamariVariableDictionary);

                result.AssertOutput("KingKong");
                result.AssertNoOutput("DEBUG:    1+  >>>> Write-Host $mysecrect");
            }
        }
Exemplo n.º 48
0
        public void LogFileCopiesTheContentsOfTheSourceFile()
        {
            using (TemporaryFile sourceFile = new TemporaryFile())
            {
                string sourceContent = "Source file content";

                File.WriteAllText(sourceFile.FileName, sourceContent);

                using (FilesContainer filesContainer = new FilesContainer(new Logger()))
                {
                    LoggedFile file = filesContainer.LogFile(sourceFile.FileName, null);

                    string content = File.ReadAllText(file.FilePath);

                    Assert.AreEqual(sourceContent, content);
                }
            }
        }
Exemplo n.º 49
0
        /// <summary>
        /// Compare a given sting against the contents of a file with test data and show a diff tool when they are not equal
        /// </summary>
        public static void AreEqual(string actual, string fileExtension, [CallerMemberName] string fileName = null)
        {
            string expectedFileName = Path.Combine("TestData", fileName + fileExtension);
            string expected         = File.ReadAllText(expectedFileName);

            try
            {
                Assert.AreEqual(expected, actual);
            }
            catch (AssertFailedException)
            {
                // Show diff tool when two strings aren't equal
                using var actualFile = new TemporaryFile(actual, fileExtension);
                using Process diff   = Process.Start(DiffExecutable, string.Format(DiffArguments, actualFile.Name, expectedFileName));
                diff.WaitForExit();
                throw;
            }
        }
Exemplo n.º 50
0
    public void SaveLoad()
    {
        Config config1;
        object config2;

        using (var tempFile = new TemporaryFile("0install-test-config"))
        {
            // Write and read file
            config1 = CreateTestConfig();
            config1.Save(tempFile);
            config2 = Config.Load(tempFile);
        }

        // Ensure data stayed the same
        config2.Should().Be(config1, because: "Serialized objects should be equal.");
        config2.GetHashCode().Should().Be(config1.GetHashCode(), because: "Serialized objects' hashes should be equal.");
        config2.Should().NotBeSameAs(config1, because: "Serialized objects should not return the same reference.");
    }
        public async Task <ActionResult> ParseFile(HttpPostedFileBase file)
        {
            var service = new GetPackagesService(_nuGetPackagesRepository, _uiLibraryPackageRepository);

            PackagesFileResult <IPackage> result = null;

            using (TemporaryFile tempFile = new TemporaryFile())
            {
                file.SaveAs(tempFile.FileName);

                result = await service.ParseFileAsync(tempFile.FileName, file.FileName);
            }

            var builder   = new ParseResultViewModelBuilder();
            var viewModel = builder.Build(new[] { result });

            return(View(_outputView, viewModel));
        }
Exemplo n.º 52
0
    public static void RethrowWithLockingInformation_GivenIOExceptionWithNoLockedFiles_ReturnsFalse()
    {
        using var tmpPath = new TemporaryFile();
        try
        {
            using (var file = tmpPath.FileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                using (var innerFile = tmpPath.FileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                    _ = "won't get here";

            Assert.Fail("The file locking did not throw an exception when it should have.");
        }
        catch (IOException ex)
        {
            var result = ex.RethrowWithLockingInformation(tmpPath.FileInfo);

            Assert.That(result, Is.False);
        }
    }
        public void CanPerformReplacementOnMultipleTargetFiles()
        {
            using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion)))
            {
                Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables);
                Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, $"{JsonFileName}\n{YamlFileName}");
                Variables.Set("key", "new-value");

                var result = DeployPackage(file.FilePath);
                result.AssertSuccess();

                var extractedPackageUpdatedJsonFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, JsonFileName));
                var extractedPackageUpdatedYamlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, YamlFileName));

                this.Assent(extractedPackageUpdatedJsonFile, TestEnvironment.AssentJsonConfiguration);
                this.Assent(extractedPackageUpdatedYamlFile, TestEnvironment.AssentYamlConfiguration);
            }
        }
Exemplo n.º 54
0
        /// <inheritdoc/>
        public IEnumerable <OpenPgpSignature> Verify(byte[] data, byte[] signature)
        {
            #region Sanity checks
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (signature == null)
            {
                throw new ArgumentNullException(nameof(signature));
            }
            #endregion

            string result;
            using (var signatureFile = new TemporaryFile("0install-sig"))
            {
                File.WriteAllBytes(signatureFile, signature);
                result = new CliControl(_homeDir, data).Execute("--batch", "--no-secmem-warning", "--status-fd", "1", "--verify", signatureFile.Path, "-");
            }
            var lines = result.SplitMultilineText();

            // Each signature is represented by one line of encoded information
            var signatures = new List <OpenPgpSignature>(lines.Length);
            foreach (string line in lines)
            {
                try
                {
                    var parsedSignature = ParseSignatureLine(line);
                    if (parsedSignature != null)
                    {
                        signatures.Add(parsedSignature);
                    }
                }
                #region Error handling
                catch (FormatException ex)
                {
                    // Wrap exception since only certain exception types are allowed
                    throw new IOException(ex.Message, ex);
                }
                #endregion
            }

            return(signatures);
        }
Exemplo n.º 55
0
        public void TestGetUncachedSelectionsPackageManager()
        {
            using (var tempFile = new TemporaryFile("0install-unit-tests"))
            {
                var impl1 = new ExternalImplementation("RPM", "firefox", new ImplementationVersion("1.0"))
                {
                    IsInstalled = false
                };
                var impl2 = new ExternalImplementation("RPM", "thunderbird", new ImplementationVersion("1.0"))
                {
                    IsInstalled = true
                };
                var impl3 = new ExternalImplementation("RPM", "vlc", new ImplementationVersion("1.0"))
                {
                    IsInstalled = true, QuickTestFile = tempFile
                };

                var selections = new Selections
                {
                    InterfaceUri    = FeedTest.Test1Uri,
                    Command         = Command.NameRun,
                    Implementations =
                    {
                        new ImplementationSelection {
                            InterfaceUri = FeedTest.Test1Uri, FromFeed = new FeedUri(FeedUri.FromDistributionPrefix + FeedTest.Test1Uri), ID = impl1.ID, QuickTestFile = impl1.QuickTestFile
                        },
                        new ImplementationSelection {
                            InterfaceUri = FeedTest.Test1Uri, FromFeed = new FeedUri(FeedUri.FromDistributionPrefix + FeedTest.Test1Uri), ID = impl2.ID, QuickTestFile = impl2.QuickTestFile
                        },
                        new ImplementationSelection {
                            InterfaceUri = FeedTest.Test1Uri, FromFeed = new FeedUri(FeedUri.FromDistributionPrefix + FeedTest.Test1Uri), ID = impl3.ID, QuickTestFile = impl3.QuickTestFile
                        }
                    }
                };

                PackageManagerMock.Setup(x => x.Lookup(selections.Implementations[0])).Returns(impl1);
                PackageManagerMock.Setup(x => x.Lookup(selections.Implementations[1])).Returns(impl2);

                var implementationSelections = Target.GetUncachedSelections(selections);

                // Only the first implementation should be listed as uncached
                implementationSelections.Should().BeEquivalentTo(new[] { selections.Implementations[0] }, because: "Only the first implementation should be listed as uncached");
            }
        }
Exemplo n.º 56
0
        public static async Task <DependencyGraphSpec> GenerateRestoreGraphFile(ILogger logger, string projectPath)
        {
            DependencyGraphSpec spec = null;

            using (var restoreGraphResult = new TemporaryFile())
            {
                await Task.Run(() =>
                {
                    var pc = new Microsoft.Build.Evaluation.ProjectCollection();

                    try
                    {
                        var parameters = new BuildParameters(pc)
                        {
                            Loggers = new[] { new LoggerRedirect(logger, true) } //Instance of ILogger instantiated earlier
                        };

                        // Run a MSBuild /t:Restore <projectfile>
                        var request = new BuildRequestData(projectPath, new Dictionary <string, string> {
                            { "RestoreGraphOutputPath", restoreGraphResult.Path }, { "RestoreRecursive", "false" }
                        }, null, new[] { "GenerateRestoreGraphFile" }, null, BuildRequestDataFlags.None);

                        mainBuildManager.Build(parameters, request);
                    }
                    finally
                    {
                        pc.UnloadAllProjects();
                        pc.Dispose();
                    }
                });

                if (File.Exists(restoreGraphResult.Path) && new FileInfo(restoreGraphResult.Path).Length != 0)
                {
                    spec = DependencyGraphSpec.Load(restoreGraphResult.Path);
                    File.Delete(restoreGraphResult.Path);
                }
                else
                {
                    spec = new DependencyGraphSpec();
                }
            }

            return(spec);
        }
Exemplo n.º 57
0
        public void VerifyAllConfigOptionsMappedToConfigObject()
        {
            var pipelineConfigObj = new Dictionary <string, object>
            {
                ["outputs"] = new List <Dictionary <string, object> >
                {
                    new Dictionary <string, object>
                    {
                        ["type"]       = "Http",
                        ["format"]     = "JsonLines",
                        ["ServiceUri"] = "http://localhost:1000",
                        ["basicAuthenticationUserName"]     = "******",
                        ["basicAuthenticationUserPassword"] = "******",
                        ["httpContentType"] = "application/x-custom",
                        ["headers"]         = new Dictionary <string, string>
                        {
                            ["X-Foo"] = "example"
                        }
                    }
                }
            };

            using (var configFile = new TemporaryFile())
            {
                var pipelineConfig = JsonConvert.SerializeObject(pipelineConfigObj, EventFlowJsonUtilities.GetDefaultSerializerSettings());

                configFile.Write(pipelineConfig);
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile(configFile.FilePath);
                var configuration       = configBuilder.Build();
                var outputConfigSection = configuration.GetSection("outputs");
                var configFragments     = outputConfigSection.GetChildren().ToList();

                var httpOutputConfiguration = new HttpOutputConfiguration();
                configFragments[0].Bind(httpOutputConfiguration);

                Assert.Equal("http://localhost:1000", httpOutputConfiguration.ServiceUri);
                Assert.Equal(HttpOutputFormat.JsonLines, httpOutputConfiguration.Format);
                Assert.Equal("mywebuser", httpOutputConfiguration.BasicAuthenticationUserName);
                Assert.Equal("mywebpass", httpOutputConfiguration.BasicAuthenticationUserPassword);
                Assert.Equal("application/x-custom", httpOutputConfiguration.HttpContentType);
                Assert.Equal("example", httpOutputConfiguration.Headers["X-Foo"]);
            }
        }
Exemplo n.º 58
0
        public void CanSaveAsOverwriteExistingFile()
        {
            using (var existing = new TemporaryFile())
            {
                // Arrange
                File.WriteAllText(existing.Path, "");

                // Act
                using (var wb = new XLWorkbook())
                {
                    var sheet = wb.Worksheets.Add("TestSheet");
                    wb.SaveAs(existing.Path);
                }

                // Assert
                Assert.IsTrue(File.Exists(existing.Path));
                Assert.Greater(new FileInfo(existing.Path).Length, 0);
            }
        }
Exemplo n.º 59
0
 internal ServerChunkRecord(HttpxServer Server, string Id, string From, string To, HttpRequest Request,
                            IEndToEndEncryption E2e, string EndpointReference, TemporaryFile File, int MaxChunkSize, bool Sipub, bool Ibb,
                            bool Socks5, bool Jingle)
     : base()
 {
     this.server       = Server;
     this.id           = Id;
     this.from         = From;
     this.to           = To;
     this.request      = Request;
     this.e2e          = E2e;
     this.e2eReference = EndpointReference;
     this.file         = File;
     this.maxChunkSize = MaxChunkSize;
     this.sipub        = Sipub;
     this.ibb          = Ibb;
     this.s5           = Socks5;
     this.jingle       = Jingle;
 }
Exemplo n.º 60
0
        public void ShouldApplyDeltaToPreviousPackageToCreateNewPackage()
        {
            using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0")))
                using (var signatureFile = new TemporaryFile(basisFile.FilePath + ".octosig"))
                {
#if USE_OCTODIFF_EXE
                    var signatureResult = Invoke(OctoDiff()
                                                 .Action("signature")
                                                 .PositionalArgument(basisFile.FilePath)
                                                 .PositionalArgument(signatureFile.FilePath));

                    signatureResult.AssertSuccess();
#else
                    var exitCode = Octodiff.Program.Main(new[] { "signature", basisFile.FilePath, signatureFile.FilePath });
                    Assert.That(exitCode, Is.EqualTo(0), string.Format("Expected command to return exit code 0, received {0}", exitCode));
#endif
                    Assert.That(File.Exists(signatureFile.FilePath));

                    using (var newFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.1", true)))
                        using (var deltaFile = new TemporaryFile(basisFile.FilePath + "_to_" + NewFileName + ".octodelta"))
                        {
#if USE_OCTODIFF_EXE
                            var deltaResult = Invoke(OctoDiff()
                                                     .Action("delta")
                                                     .PositionalArgument(signatureFile.FilePath)
                                                     .PositionalArgument(newFile.FilePath)
                                                     .PositionalArgument(deltaFile.FilePath));

                            deltaResult.AssertSuccess();
#else
                            var deltaExitCode = Octodiff.Program.Main(new[] { "delta", signatureFile.FilePath, newFile.FilePath, deltaFile.FilePath });
                            Assert.That(deltaExitCode, Is.EqualTo(0), string.Format("Expected command to return exit code 0, received {0}", exitCode));
#endif
                            Assert.That(File.Exists(deltaFile.FilePath));

                            var patchResult = ApplyDelta(basisFile.FilePath, basisFile.Hash, deltaFile.FilePath, NewFileName);
                            patchResult.AssertSuccess();
                            patchResult.AssertOutput("Applying delta to {0} with hash {1} and storing as {2}", basisFile.FilePath,
                                                     basisFile.Hash, Path.Combine(DownloadPath, NewFileName));
                            patchResult.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name);
                        }
                }
        }