public void CreatePackageAddsVersionStampIfFrameworkAssembliesAreUsed() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = "A", Version = new Version("1.0"), Description = "Descriptions", }; builder.Authors.Add("David"); builder.FrameworkReferences.Add(new FrameworkAssemblyReference("System.Web")); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata schemaVersion=""2""> <id>A</id> <version>1.0</version> <authors>David</authors> <owners>David</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Descriptions</description> <frameworkAssemblies> <frameworkAssembly assemblyName=""System.Web"" targetFramework="""" /> </frameworkAssemblies> </metadata> </package>", ms.ReadToEnd()); }
public void OwnersFallsBackToAuthorsIfNoneSpecified() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = "A", Version = new SemanticVersion("1.0"), Description = "Description" }; builder.Authors.Add("JohnDoe"); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.Equal(@"<?xml version=""1.0""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>A</id> <version>1.0</version> <authors>JohnDoe</authors> <owners>JohnDoe</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Description</description> </metadata> </package>", ms.ReadToEnd()); }
public void ReleaseNotesAttributeIsRecognized() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = "A", Version = new SemanticVersion("1.0"), Description = "Description", ReleaseNotes = "Release Notes" }; builder.Authors.Add("David"); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.Equal(@"<?xml version=""1.0""?> <package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd""> <metadata> <id>A</id> <version>1.0</version> <authors>David</authors> <owners>David</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Description</description> <releaseNotes>Release Notes</releaseNotes> </metadata> </package>", ms.ReadToEnd()); }
public void ReadToEnd_should_return_all_bytes() { var data = new byte[] { 0x1, 0x2, 0x3 }; var stream = new MemoryStream(data); stream.ReadToEnd().Should().ContainInOrder(data); }
public void AddingBindingRedirectToEmptyConfig() { // Arrange var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem.Setup(m => m.FileExists("config")).Returns(true); mockFileSystem.Setup(m => m.OpenFile("config")).Returns(@"<configuration></configuration>".AsStream()); var ms = new MemoryStream(); mockFileSystem.Setup(m => m.AddFile("config", It.IsAny<Stream>())).Callback<string, Stream>((path, stream) => { stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); }); var bindingRedirectManager = new BindingRedirectManager(mockFileSystem.Object, "config"); AssemblyBinding assemblyBinding = GetAssemblyBinding("AssemblyName", "token", "3.0.0.0"); // Act bindingRedirectManager.AddBindingRedirects(new[] { assemblyBinding }); // Assert Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <dependentAssembly> <assemblyIdentity name=""AssemblyName"" publicKeyToken=""token"" culture=""neutral"" /> <bindingRedirect oldVersion=""0.0.0.0-3.0.0.0"" newVersion=""3.0.0.0"" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>", ms.ReadToEnd()); }
public static byte[] GetThumbnail(this Stream stream, int width, int height) { Image image = new Bitmap(width, height); System.Drawing.Graphics.FromImage(image).DrawImage(Bitmap.FromStream(stream), 0, 0, width, height); Stream buffer = new MemoryStream(); image.Save(buffer, ImageFormat.Jpeg); return buffer.ReadToEnd(); }
private static string ReadStream(Action<Stream> write) { using (var stream = new MemoryStream()) { write(stream); return stream.ReadToEnd(); } }
private string ToNuspecFileText() { using (var stream = new MemoryStream()) { _manifest.Save(stream, validate: false); stream.Seek(0, SeekOrigin.Begin); var content = stream.ReadToEnd(); return RemoveSchemaNamespace(content); } }
public static byte[] GetThumbnail(this byte[] buffer, int width, int height) { Image sourceImage=Bitmap.FromStream(new MemoryStream(buffer)); Image image = new Bitmap(width, height); var graphic = System.Drawing.Graphics.FromImage(image); graphic.DrawImage(sourceImage, 0, 0, width, height); Stream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); return stream.ReadToEnd(); }
public static string ToCSharp(this CodeCompileUnit unit) { using (var stream = new MemoryStream()) { var csharp = new CSharpCodeProvider(); var writer = new IndentedTextWriter(new StreamWriter(stream)); csharp.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions()); writer.Flush(); return stream.ReadToEnd(); } }
public static IEnumerable<byte[]> GetThumbnail(this byte[] buffer,IEnumerable<int[]> sizes) { Image sourceImage = Bitmap.FromStream(new MemoryStream(buffer)); Image image; Graphics graphic; Stream stream ; foreach (var size in sizes) { if (size.Length > 1) { image = new Bitmap(size[0], size[1]); graphic = System.Drawing.Graphics.FromImage(image); graphic.DrawImage(sourceImage, 0, 0, size[0], size[1]); stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); yield return stream.ReadToEnd(); } } }
private void OnOpenFile(string fileName) { // Show message. this.textBox.AppendText(string.Format("Opening file \'{0}\'...{1}", fileName, Environment.NewLine)); try { // Open a stream to the ZIP file. using (FileStream fileInStream = new FileStream(fileName, FileMode.Open)) { // Open the ZIP archive. using (ZipArchive zipArchive = new ZipArchive(fileInStream, ZipArchiveMode.Read)) { // The shape file name. string shapeFileName = null; this.textBox.AppendText(string.Format("Extracting shape ZIP archive...{0}", Environment.NewLine)); foreach (ZipArchiveEntry entry in zipArchive.Entries) { // If this is the shape file, save the name. if (Path.GetExtension(entry.Name) == ".shp") { shapeFileName = entry.Name; } this.textBox.AppendText(string.Format("- {0}: {1} bytes {2} bytes compressed{3}", entry.Name, entry.Length, entry.CompressedLength, Environment.NewLine)); } // If there are no entries, throw an exception. if (null == shapeFileName) throw new FileNotFoundException("The ZIP archive does not contain a shape file."); // Create the name of a temporary folder. string tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); this.textBox.AppendText(string.Format("Shape file name is: \'{0}\'{1}", shapeFileName, Environment.NewLine)); // Create the temporary folder. System.IO.Directory.CreateDirectory(tempFolder); this.textBox.AppendText(string.Format("Creating temporary folder \'{0}\'...{1}", tempFolder, Environment.NewLine)); try { // Extract the shapefile contents. zipArchive.ExtractToDirectory(tempFolder); // Open the shapefile. using (Shapefile shapefile = new Shapefile(Path.Combine(tempFolder, shapeFileName))) { this.textBox.AppendText(Environment.NewLine); // Write the basic information. this.textBox.AppendText(string.Format("Type: {0}, Shapes: {1:n0}{2}", shapefile.Type, shapefile.Count, Environment.NewLine)); this.textBox.AppendText(Environment.NewLine); // Create a map object. Map map = new Map(new MapRectangle( shapefile.BoundingBox.Left, shapefile.BoundingBox.Top, shapefile.BoundingBox.Right, shapefile.BoundingBox.Bottom)); // Write the bounding box of this shape file. this.textBox.AppendText(string.Format("Bounds: {0},{1} -> {2},{3}{4}", shapefile.BoundingBox.Left, shapefile.BoundingBox.Top, shapefile.BoundingBox.Right, shapefile.BoundingBox.Bottom, Environment.NewLine)); // Enumerate all shapes. foreach (Shape shape in shapefile) { // Shape basic information. //this.textBox.AppendText(string.Format("{0} {1} {2} ", shape.RecordNumber, shape.Type, shape.GetMetadata("name"))); // Create a new shape. MapShape mapShape; switch (shape.Type) { case ShapeType.Point: ShapePoint shapePoint = shape as ShapePoint; mapShape = new MapShapePoint(new MapPoint(shapePoint.Point.X, shapePoint.Point.Y)); break; case ShapeType.Polygon: ShapePolygon shapePolygon = shape as ShapePolygon; //this.textBox.AppendText(string.Format(": {0}", shapePolygon.Parts.Count)); MapShapePolygon mapShapePolygon = new MapShapePolygon(new MapRectangle( shapePolygon.BoundingBox.Left, shapePolygon.BoundingBox.Top, shapePolygon.BoundingBox.Right, shapePolygon.BoundingBox.Bottom)); foreach(PointD[] part in shapePolygon.Parts) { MapPart mapPart = new MapPart(); foreach (PointD point in part) { mapPart.Points.Add(point.X, point.Y); } mapShapePolygon.Parts.Add(mapPart); } mapShape = mapShapePolygon; break; default: throw new NotSupportedException(string.Format("Shape type {0} is not supported.", shape.Type)); } // Add the shape metadata. foreach (string name in shape.GetMetadataNames()) { mapShape.Metadata[name] = shape.GetMetadata(name); } // Add the shape to the map. map.Shapes.Add(mapShape); //this.textBox.AppendText(Environment.NewLine); } this.textBox.AppendText(Environment.NewLine); // Create a memory stream. using (MemoryStream memoryStream = new MemoryStream()) { // Serialize the map data. map.Write(memoryStream); // Display the XML. this.textBox.AppendText(Encoding.UTF8.GetString(memoryStream.ReadToEnd())); this.textBox.AppendText(Environment.NewLine); this.textBox.AppendText(Environment.NewLine); // Set the stream position to zero. memoryStream.Position = 0; // Display a dialog to save the file. if (this.saveFileDialog.ShowDialog(this) == DialogResult.OK) { // Create a file stream. using (FileStream fileOutStream = System.IO.File.Create(this.saveFileDialog.FileName)) { // Compress the stream. //using (GZipStream zipStream = new GZipStream(fileOutStream, CompressionLevel.Optimal)) //{ this.textBox.AppendText("Uncompressed data is {0} bytes.{1}".FormatWith(memoryStream.Length, Environment.NewLine)); memoryStream.CopyTo(fileOutStream); this.textBox.AppendText("Compressed data is {0} bytes.{1}".FormatWith(fileOutStream.Length, Environment.NewLine)); //} } } } //this.textBox.AppendText(map.ToXml().ToString()); this.textBox.AppendText(Environment.NewLine); } } finally { // Delete the temporary folder. this.textBox.AppendText(Environment.NewLine); System.IO.Directory.Delete(tempFolder, true); this.textBox.AppendText(string.Format("Temporary folder \'{0}\' deleted.{1}", tempFolder, Environment.NewLine)); } } } } catch (Exception exception) { this.textBox.AppendText(string.Format("An exception occurred. {0}", exception.Message)); } this.textBox.AppendText(Environment.NewLine); this.textBox.AppendText("Done."); }
public override void ExecuteCommand() { var manifest = new Manifest(); string projectFile = null; string fileName = null; if (!String.IsNullOrEmpty(AssemblyPath)) { // Extract metadata from the assembly string path = Path.Combine(Directory.GetCurrentDirectory(), AssemblyPath); AssemblyMetadata metadata = AssemblyMetadataExtractor.GetMetadata(path); manifest.Metadata.Id = metadata.Name; manifest.Metadata.Version = metadata.Version.ToString(); manifest.Metadata.Authors = metadata.Company; manifest.Metadata.Description = metadata.Description; } else { if (!ProjectHelper.TryGetProjectFile(out projectFile)) { manifest.Metadata.Id = Arguments.Any() ? Arguments[0] : "Package"; manifest.Metadata.Version = "1.0.0"; } else { fileName = Path.GetFileNameWithoutExtension(projectFile); manifest.Metadata.Id = "$id$"; manifest.Metadata.Title = "$title$"; manifest.Metadata.Version = "$version$"; manifest.Metadata.Description = "$description$"; manifest.Metadata.Authors = "$author$"; } } // Get the file name from the id or the project file fileName = fileName ?? manifest.Metadata.Id; // If we're using a project file then we want the a minimal nuspec if (String.IsNullOrEmpty(projectFile)) { manifest.Metadata.Description = manifest.Metadata.Description ?? SampleDescription; if (String.IsNullOrEmpty(manifest.Metadata.Authors)) { manifest.Metadata.Authors = Environment.UserName; } manifest.Metadata.DependencySets = new List<ManifestDependencySet>(); manifest.Metadata.DependencySets.Add(new ManifestDependencySet { Dependencies = new List<ManifestDependency> { SampleManifestDependency } }); } manifest.Metadata.ProjectUrl = SampleProjectUrl; manifest.Metadata.LicenseUrl = SampleLicenseUrl; manifest.Metadata.IconUrl = SampleIconUrl; manifest.Metadata.Tags = SampleTags; manifest.Metadata.Copyright = "Copyright " + DateTime.Now.Year; manifest.Metadata.ReleaseNotes = SampleReleaseNotes; string nuspecFile = fileName + Constants.ManifestExtension; // Skip the creation if the file exists and force wasn't specified if (File.Exists(nuspecFile) && !Force) { Console.WriteLine(NuGetResources.SpecCommandFileExists, nuspecFile); } else { try { using (var stream = new MemoryStream()) { manifest.Save(stream, validate: false); stream.Seek(0, SeekOrigin.Begin); string content = stream.ReadToEnd(); File.WriteAllText(nuspecFile, RemoveSchemaNamespace(content)); } Console.WriteLine(NuGetResources.SpecCommandCreatedNuSpec, nuspecFile); } catch { // Cleanup the file if it fails to save for some reason File.Delete(nuspecFile); throw; } } }
public void VersionFormatIsPreserved() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = "A", Version = new SemanticVersion("1.0"), Description = "Descriptions", Summary = "Summary", }; builder.Authors.Add("David"); var dependencySet = new PackageDependencySet(null, new [] { new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.0"), IsMinInclusive = true }), new PackageDependency("C", new VersionSpec { MinVersion = new SemanticVersion("1.0"), MaxVersion = new SemanticVersion("5.0"), IsMinInclusive = false }) }); builder.DependencySets.Add(dependencySet); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.Equal(@"<?xml version=""1.0""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>A</id> <version>1.0</version> <authors>David</authors> <owners>David</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Descriptions</description> <summary>Summary</summary> <dependencies> <dependency id=""B"" version=""1.0"" /> <dependency id=""C"" version=""(1.0, 5.0)"" /> </dependencies> </metadata> </package>", ms.ReadToEnd()); }
public void CreatePackageTrimsExtraWhitespace() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = " A ", Version = new SemanticVersion("1.0"), Description = "Descriptions ", Summary = " Summary", Language = " en-us ", Copyright = " Copyright 2012 " }; builder.Authors.Add("David"); builder.Owners.Add("John"); builder.Tags.Add("t1"); builder.Tags.Add("t2"); builder.Tags.Add("t3"); var dependencies = new PackageDependency[] { new PackageDependency(" X ") }; builder.DependencySets.Add(new PackageDependencySet(null, dependencies)); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.Equal(@"<?xml version=""1.0""?> <package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd""> <metadata> <id>A</id> <version>1.0</version> <authors>David</authors> <owners>John</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Descriptions</description> <summary>Summary</summary> <copyright>Copyright 2012</copyright> <language>en-us</language> <tags>t1 t2 t3</tags> <dependencies> <dependency id=""X"" /> </dependencies> </metadata> </package>", ms.ReadToEnd()); }
private byte[] Decrypt(byte[] encrypteData) { // Extract the IV from the encryptedData using (var stream = new MemoryStream(encrypteData)) { var ivLength = stream.ReadByte(); var iv = stream.Read(ivLength); var data = stream.ReadToEnd(); return CryptoUtils.AesDecrypt(data, encryptionKey, iv); } }
public void CreatePackageUsesV4SchemaNamespaceIfDependecyHasTargetFramework() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = "A", Version = new SemanticVersion("1.0"), Description = "Descriptions", }; builder.Authors.Add("Luan"); var fx = new FrameworkName("Silverlight", new Version("4.0")); var dependencies = new PackageDependency[] { new PackageDependency("B", null) }; builder.DependencySets.Add(new PackageDependencySet(fx, dependencies)); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.Equal(@"<?xml version=""1.0""?> <package xmlns=""http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd""> <metadata> <id>A</id> <version>1.0</version> <authors>Luan</authors> <owners>Luan</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Descriptions</description> <dependencies> <group targetFramework=""Silverlight4.0""> <dependency id=""B"" /> </group> </dependencies> </metadata> </package>", ms.ReadToEnd()); }
public void CreatePackageUsesV2SchemaNamespaceIfReferenceAssembliesAreUsed() { // Arrange PackageBuilder builder = new PackageBuilder() { Id = "A", Version = new SemanticVersion("1.0"), Description = "Descriptions", }; builder.PackageAssemblyReferences.Add(new PackageReferenceSet(null, new string[] { "foo.dll" })); builder.Authors.Add("David"); var ms = new MemoryStream(); // Act Manifest.Create(builder).Save(ms); ms.Seek(0, SeekOrigin.Begin); // Assert Assert.Equal(@"<?xml version=""1.0""?> <package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd""> <metadata> <id>A</id> <version>1.0</version> <authors>David</authors> <owners>David</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Descriptions</description> <references> <reference file=""foo.dll"" /> </references> </metadata> </package>", ms.ReadToEnd()); }
private void CreateAndOutputNuSpecFile(string assemblyOutput, List<ManifestDependency> manifestDependencies) { var manifest = new Manifest { Metadata = { Dependencies = manifestDependencies, Id = Id ?? assemblyOutput, Title = Title ?? assemblyOutput, Version = "$version$", Description = Description ?? assemblyOutput, Authors = Author ?? "$author$", Tags = Tags ?? "$tags$", LicenseUrl = LicenseUrl ?? "$licenseurl$", RequireLicenseAcceptance = RequireLicenseAcceptance, Copyright = Copyright ?? "$copyright$", IconUrl = IconUrl ?? "$iconurl$", ProjectUrl = ProjectUrl ?? "$projrcturl$", Owners = Owners ?? Author ?? "$author$" }, Files = new List<ManifestFile> { new ManifestFile { Source = assemblyOutput + ".dll", Target = "lib" } } }; string nuspecFile = assemblyOutput + Constants.ManifestExtension; //Dont add a releasenotes node if we dont have any to add... if (!string.IsNullOrEmpty(ReleaseNotes)) manifest.Metadata.ReleaseNotes = ReleaseNotes; try { Console.WriteLine("Saving new NuSpec: {0}", nuspecFile); using (var stream = new MemoryStream()) { manifest.Save(stream, validate: false); stream.Seek(0, SeekOrigin.Begin); var content = stream.ReadToEnd(); File.WriteAllText(nuspecFile, RemoveSchemaNamespace(content)); } } catch (Exception) { Console.WriteError("Could not save file: {0}", nuspecFile); throw; } }
public override byte[] DecryptSecret(byte[] blob) { // Blob structure Win2k: Algorithm ID (2B), Flags (2B), PEK ID (4B), Salt (16B), Encrypted secret (rest) const int EncryptedDataOffsetDES = 2 * sizeof(short) + sizeof(uint) + SaltSize; // Validate (DES has shorter blob) Validator.AssertMinLength(blob, EncryptedDataOffsetDES + 1, "blob"); // Extract salt and metadata from the blob byte[] decryptionKey; byte[] encryptedSecret; byte[] salt; SecretEncryptionType encryptionType; using (var stream = new MemoryStream(blob, false)) { using (var reader = new BinaryReader(stream)) { encryptionType = (SecretEncryptionType) reader.ReadUInt16(); // The flags field is actually not used by AD and is always 0. uint flags = reader.ReadUInt16(); uint keyId = reader.ReadUInt32(); // TODO: Check if the key exists decryptionKey = this.Keys[keyId]; salt = reader.ReadBytes(SaltSize); // Read the underlaying stream to end encryptedSecret = stream.ReadToEnd(); } } // Decrypt byte[] decryptedSecret; switch (encryptionType) { case SecretEncryptionType.DatabaseRC4WithSalt: decryptedSecret = DecryptUsingRC4(encryptedSecret, salt, decryptionKey); break; default: // TODO: Extract as resource var ex = new FormatException("Unsupported encryption type."); ex.Data.Add("SecretEncryptionType", encryptionType); throw ex; } return decryptedSecret; }
private byte[] DecryptPekList(byte[] encryptedBlob, byte[] bootKey) { // Blob structure: Version (4B), Flags (4B), Salt (16B), Encrypted PEK List Validator.AssertMinLength(encryptedBlob, EncryptedPekListOffset + 1, "blob"); Validator.AssertLength(bootKey, BootKeyRetriever.BootKeyLength, "bootKey"); // Parse blob byte[] salt; PekListFlags flags; byte[] encryptedPekList; using (var stream = new MemoryStream(encryptedBlob)) { using (var reader = new BinaryReader(stream)) { this.Version = (PekListVersion) reader.ReadUInt32(); flags = (PekListFlags) reader.ReadUInt32(); salt = reader.ReadBytes(SaltSize); encryptedPekList = stream.ReadToEnd(); } } // Decrypt byte[] decryptedPekList; switch(flags) { case PekListFlags.Encrypted: // Decrypt switch(this.Version) { case PekListVersion.W2k: decryptedPekList = DecryptUsingRC4(encryptedPekList, salt, bootKey, BootKeySaltHashRounds); break; default: // TODO: Extract as resource. throw new FormatException("Unsupported PEK list version."); } break; case PekListFlags.Clear: // No decryption is needed. This is a very rare case. decryptedPekList = encryptedPekList; break; default: // TODO: Extract as a resource. throw new FormatException("Unsupported PEK list flags"); } return decryptedPekList; }
public void UserSettings_CallingDeleteValueWithValidSectionAndKeyDeletesTheEntryAndReturnsTrue() { // Arrange var mockFileSystem = new Mock<IFileSystem>(); var nugetConfigPath = "NuGet.Config"; mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true); var ms = new MemoryStream(); mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) => { stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); }); string config = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <SectionName> <add key=""DeleteMe"" value=""value"" /> <add key=""keyNotToDelete"" value=""value"" /> </SectionName> <SectionName2> <add key=""key"" value=""value"" /> </SectionName2> </configuration>"; mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream()); UserSettings settings = new UserSettings(mockFileSystem.Object); // Act & Assert Assert.IsTrue(settings.DeleteValue("SectionName", "DeleteMe")); Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <SectionName> <add key=""keyNotToDelete"" value=""value"" /> </SectionName> <SectionName2> <add key=""key"" value=""value"" /> </SectionName2> </configuration>", ms.ReadToEnd()); }
public void UserSettings_CallingSetValuseWillAddSectionIfItDoesNotExist() { // Arrange var mockFileSystem = new Mock<IFileSystem>(); var nugetConfigPath = "NuGet.Config"; mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true); var ms = new MemoryStream(); mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) => { stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); }); string config = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <SectionName> <add key=""key"" value=""value"" /> </SectionName> </configuration>"; mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream()); var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key", "value") }; UserSettings settings = new UserSettings(mockFileSystem.Object); // Act settings.SetValues("NewSectionName", values); // Assert Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <SectionName> <add key=""key"" value=""value"" /> </SectionName> <NewSectionName> <add key=""key"" value=""value"" /> </NewSectionName> </configuration>", ms.ReadToEnd()); }
public void UserSettingsExtentions_SetEncryptedValue() { // Arrange var mockFileSystem = new Mock<IFileSystem>(); var nugetConfigPath = "NuGet.Config"; mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true); var ms = new MemoryStream(); mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) => { stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); }); string config = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <SectionName> <add key=""key"" value=""value"" /> </SectionName> </configuration>"; mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream()); UserSettings settings = new UserSettings(mockFileSystem.Object); // Act settings.SetEncryptedValue("SectionName", "key", "NewValue"); // Assert Assert.IsFalse(ms.ReadToEnd().Contains("NewValue"), "Value Should Be Ecrypted and Base64 encoded."); }
public void Save_SavesHostFileToStream() { var actualStream = new MemoryStream(); var expectedStream = TestContext.GetResourceStream("FluentInstallation.Web.Hosts.Hosts.txt"); var hostsFile = new HostsFile(); hostsFile.AddComment("This is a test comment line 1"); hostsFile.AddComment("This is a test comment line 2"); hostsFile.AddHostEntry(new HostEntry() { IpAddress = "172.0.1.1", HostName = "mysite.co.uk", Description = string.Empty, IsEnabled = true }); hostsFile.AddHostEntry(new HostEntry() { IpAddress = "172.0.1.2", HostName = "mysite.de", Description = string.Empty, IsEnabled = true }); hostsFile.AddHostEntry(new HostEntry() { IpAddress = "172.0.1.3", HostName = "mysite.ie", Description = "This is a comment", IsEnabled = true }); hostsFile.Save(actualStream); actualStream.Position = 0; var actual = actualStream.ReadToEnd(); var expected = expectedStream.ReadToEnd(); Assert.Equal(expected, actual); }