Ejemplo n.º 1
0
        public void DisposeTest()
        {
            var collection = new DisposableCollection <TempFolder>();

            using (collection)
            {
                collection.Add(TempFolder.Create());
                collection.Add(TempFolder.Create());
                collection.Add(TempFolder.Create());
                collection.Add(TempFolder.Create());
                collection.Add(TempFolder.Create());
                collection.Add(TempFolder.Create());

                foreach (var item in collection)
                {
                    Assert.IsTrue(Directory.Exists(item.FullName));
                }
            }

            Assert.IsTrue(collection.Count == 6);

            foreach (var item in collection)
            {
                Assert.IsFalse(Directory.Exists(item.FullName));
            }
        }
Ejemplo n.º 2
0
		public static IChannel AddTo(this IChannel channel, DisposableCollection disposables)
		{
			Verify.ArgumentNotNull(disposables, "disposables");
			Verify.ArgumentNotNull(channel, "channel");
			disposables.Add(channel);
			return channel;
		}
		public void Dispose_Count_IsEmpty()
		{
			var collection = new DisposableCollection();
			collection.Dispose();
			var count = collection.Count;
			Assert.AreEqual(0, count);
		}
 public RandomizedImageVisibilityCellRenderer(
     IEnumerable <Image <Rgba32> > textures,
     bool disposeTexturesWhenClose)
 {
     _disposeTexturesWhenClose = disposeTexturesWhenClose;
     _textures = new DisposableCollection <Image <Rgba32> >(textures);
 }
 public DisposableTopicRouter(IPublishTopicRouter publishRouter, IRequestTopicRouter requestRouter, IScatterTopicRouter scatterRouter, DisposableCollection tokens)
 {
     _publishRouter = publishRouter;
     _requestRouter = requestRouter;
     _scatterRouter = scatterRouter;
     _tokens        = tokens;
 }
Ejemplo n.º 6
0
 public Saga(IPubSubBus messageBus, ISagaDataRepository <TState, TKey> repository, int threadId)
 {
     MessageBus  = messageBus;
     _repository = repository;
     _threadId   = threadId;
     _tokens     = new DisposableCollection();
 }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            using (var token = event1.Register(Event1))
            {
                event1.Invoke();         // Outputs "Received event1!"
            }
            event1.Invoke();             // Outputs nothing

            var token1 = event2.Register(x => Console.WriteLine("Got: " + x));
            var token2 = event2.Register(x => Console.WriteLine("Really got: " + x));
            var token3 = event2.Register(x => Console.WriteLine("Yes! I've got: " + x));

            event2.Invoke("Ham");             // Outputs "Got: Ham", "Really got: Ham", "Yes! I've got: Ham"

            token2.Dispose();

            event2.Invoke("Ham");             // Outputs "Got: Ham", "Yes! I've got: Ham"

            var tokens = new DisposableCollection();

            tokens.Add(token1);
            tokens.Add(token3);

            tokens.Dispose();

            event2.Invoke("Milk?");             // Outputs nothing
        }
Ejemplo n.º 8
0
 public void AddTo()
 {
     var collection = new DisposableCollection();
     var disposable = new Component();
     disposable.AddTo(collection);
     Assert.AreEqual(1, collection.Count);
     Assert.IsTrue(collection.Contains(disposable));
 }
Ejemplo n.º 9
0
 protected KeyedImageCellRenderer(
     IDictionary <string, Image <Rgba32> > map,
     bool disposeTexturesWhenClose)
 {
     _disposeTextureWhenClose = disposeTexturesWhenClose;
     _textures = new DisposableCollection <Image <Rgba32> >(map.Values);
     _map      = map;
 }
Ejemplo n.º 10
0
        public void TestDisposing()
        {
            var disposable  = new Disposable();
            var disposables = new DisposableCollection(disposable);

            disposables.Dispose();
            Assert.True(disposable.IsDisposed);
        }
 public SubscriptionCollection(IMessageBus messageBus)
 {
     _messageBus    = messageBus;
     _subscriptions = new DisposableCollection();
     WorkerPool     = new DisposableWorkerPool(messageBus.WorkerPool, _subscriptions);
     _router        = new DisposableTopicRouter(messageBus.PublishRouter, messageBus.RequestRouter, messageBus.ScatterRouter, _subscriptions);
     Modules        = new ReadOnlyModules(messageBus);
 }
Ejemplo n.º 12
0
        public void Ctor_DefaultWorks()
        {
            //Act
            var target = new DisposableCollection();

            //Assert
            target.Should().BeEmpty();
        }
		public void TearDown()
		{
			if (_disposables != null)
			{
				_disposables.Dispose();
				_disposables = null;
			}
		}
Ejemplo n.º 14
0
        private static void PackPC(string sourcePath, string saveFileName, bool useCryptography, bool updateSng)
        {
            var bins = Directory.EnumerateFiles(sourcePath, "NamesBlock.bin", SearchOption.AllDirectories).Where(File.Exists);

            foreach (var namesBlock in bins)
            {
                File.Delete(namesBlock);
            }

            if (Path.GetExtension(saveFileName) != ".dat")
            {
                saveFileName += ".dat";
            }

            using (var streamCollection = new DisposableCollection <Stream>())
                using (var outputFileStream = File.Create(saveFileName))
                {
                    var psarc = new PSARC.PSARC();
                    foreach (var x in Directory.EnumerateFiles(sourcePath))
                    {
                        var fileStream = File.OpenRead(x);
                        streamCollection.Add(fileStream);
                        psarc.AddEntry(Path.GetFileName(x), fileStream);
                    }

                    foreach (var directory in Directory.EnumerateDirectories(sourcePath))
                    {
                        var innerPsarcStream = new MemoryStream();
                        streamCollection.Add(innerPsarcStream);
                        var directoryName = Path.GetFileName(directory);

                        // Recreate SNG
                        if (updateSng)
                        {
                            if (directory.ToLower().IndexOf("dlc_tone_") < 0)
                            {
                                UpdateSng(directory, new Platform(GamePlatform.Pc, GameVersion.RS2012));
                            }
                        }

                        PackInnerPC(innerPsarcStream, directory);
                        psarc.AddEntry(directoryName + ".psarc", innerPsarcStream);
                    }
                    if (useCryptography)
                    {
                        using (var psarcStream = new MemoryStream())
                        {
                            psarc.Write(psarcStream, false);
                            psarcStream.Seek(0, SeekOrigin.Begin);
                            psarcStream.Flush();
                            RijndaelEncryptor.EncryptFile(psarcStream, outputFileStream, RijndaelEncryptor.DLCKey);
                            return;
                        }
                    }
                    psarc.Write(outputFileStream, false);
                }
        }
Ejemplo n.º 15
0
        public IDisposable Subscribe(IObserver <TTarget> observer)
        {
            var disposableCollection = new DisposableCollection();
            var operatorObserver     = this.Create(observer, disposableCollection);
            var subscription         = this.observable.Subscribe(operatorObserver);

            disposableCollection.Add(subscription);
            return(disposableCollection);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Create Channel/Lobby
 /// </summary>
 /// <param name="name">lobby name</param>
 /// <param name="maxPlayers">lobby max players</param>
 /// <param name="id">lobby id</param>
 /// <param name="flag">Lobby Type/Flag</param>
 public Lobby(string name, ushort maxPlayers, byte id, uint flag)
 {
     Name       = name;
     MaxPlayers = maxPlayers;
     Id         = id;
     Flag       = flag;
     Games      = new GameCollection(this);
     Players    = new DisposableCollection <Session>(10);
 }
Ejemplo n.º 17
0
        public void CreateAndAdd_WithDelegate()
        {
            var target = new DisposableCollection();
            var actual = target.CreateAndAdd(() => new TestDisposableObject());

            //Assert
            target.Should().HaveCount(1);
            target.Should().Contain(actual);
        }
Ejemplo n.º 18
0
        public void ConstructorFromEnumerable()
        {
            var list = new List<SomeDisposable> {
                new SomeDisposable(),
                new SomeDisposable()
            };

            var coll = new DisposableCollection(list);
            Assert.AreEqual(2, coll.Count);
        }
        public void SetUp()
        {
            _disposableCollection = new DisposableCollection();

            _configuration = Mock.Create <IConfiguration>();
            _disposableCollection.Add(new ConfigurationAutoResponder(_configuration));

            _connectionHandler = Mock.Create <IConnectionHandler>();
            _scheduler         = Mock.Create <IScheduler>();
        }
Ejemplo n.º 20
0
 public void Setup()
 {
     _disposable1          = new Disposable();
     _disposable2          = new Disposable();
     _disposableCollection = new DisposableCollection
     {
         _disposable1,
         _disposable2,
     };
 }
Ejemplo n.º 21
0
 public Class_DisposableCollection()
 {
     _disposable1          = new Disposable();
     _disposable2          = new Disposable();
     _disposableCollection = new DisposableCollection
     {
         _disposable1,
         _disposable2,
     };
 }
Ejemplo n.º 22
0
        public void Ctor_EmptyListIsEmpty()
        {
            var expected = new List <IDisposable>();

            //Act
            var target = new DisposableCollection(expected);

            //Assert
            target.Should().BeEmpty();
        }
Ejemplo n.º 23
0
        public void Ctor_NullListIsEmpty()
        {
            List <IDisposable> items = null;

            //Act
            var target = new DisposableCollection(items);

            //Assert
            target.Should().BeEmpty();
        }
Ejemplo n.º 24
0
        protected override void InitializeCore()
        {
            // get the theme from the current application
            var theme = ThemeManager.DetectAppStyle(Application.Current);

            // now set the Green accent and dark theme
            ThemeManager.ChangeAppStyle(Application.Current,
                                        ThemeManager.GetAccent(AppConfig.AccentColor),
                                        ThemeManager.GetAppTheme(AppConfig.AppTheme));

            _explorerCleaner          = new ExplorerCleaner(AppConfig);
            _explorerCleaner.Cleaned += (sender, args) => OnCleaned(args);
            _actionExecuter           =
                new ActionExecuter <ExplorerWindowCleanerClientOperator>(new ExplorerWindowCleanerClientOperator(this,
                                                                                                                 _explorerCleaner));
            DisposableCollection.Add(_actionExecuter);
            ResetBackgroundWorker(AppConfig.Interval, new BackgroundAction[] { new CleanerAction(this) });

            if (AppConfig.IsMouseHook)
            {
                RestoreClipboardHistories();

                MonitoringClipboard();

                CreateShortcutContextMenu();
                CreateClipboardContextMenu();

                _globalMouseHook              = new GlobalMouseHook();
                _globalMouseHook.MouseHooked += (sender, args) =>
                {
                    if (args.MouseButton == MouseButtons.Left)
                    {
                        _contextMenuClipboardHistories.Close(ToolStripDropDownCloseReason.AppFocusChange);
                        _contextMenuShortcuts.Close(ToolStripDropDownCloseReason.AppFocusChange);
                    }

                    if (args.IsDoubleClick)
                    {
                        if (args.MouseButton == MouseButtons.Right)
                        {
                            _contextMenuClipboardHistories.Tag = GetForegroundWindow();
                            _contextMenuClipboardHistories.Show(args.Point);
                        }
                        else if (args.MouseButton == MouseButtons.Left && args.IsDesktop)
                        {
                            _contextMenuShortcuts.Show(args.Point);
                            Debug.WriteLine($"Show Shortcut Menu. {args.Point}");
                        }
                        Debug.WriteLine("DoubleClick Mouse.");
                    }
                };
            }
        }
		public void Add_Dispose()
		{
			var collection = new DisposableCollection();

			var disposable = new Mock<IDisposable>(MockBehavior.Strict);
			disposable.Setup(_ => _.Dispose());
			collection.Add(disposable.Object);

			collection.Dispose();
			disposable.Verify(_ => _.Dispose(), Times.Once);
			Assert.AreEqual(0, collection.Count);
		}
Ejemplo n.º 26
0
        public void CreateAndAdd_WithValue()
        {
            var expected = new TestDisposableObject();

            var target = new DisposableCollection();
            var actual = target.CreateAndAdd(expected);

            //Assert
            actual.Should().Be(expected);
            target.Should().HaveCount(1);
            target.Should().Contain(expected);
        }
Ejemplo n.º 27
0
        public void Throws_ObjectDisposedException()
        {
            var d1 = new Component();
            var collection = new DisposableCollection {d1};
            collection.Dispose();

            Assert.Throws<ObjectDisposedException>(() => collection.Add(d1));
            Assert.Throws<ObjectDisposedException>(() => collection.Insert(0, d1));

            // Cannot test object disposed exception for removal, as the collection
            // is empty after it has been disposed.
            Assert.AreEqual(0, collection.Count);
        }
Ejemplo n.º 28
0
        public static void DisposeWith([NotNull] this IDisposable disposable, [NotNull] DisposableCollection collection)
        {
            if (disposable == null)
            {
                throw new ArgumentNullException(nameof(disposable));
            }
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            collection.Add(disposable);
        }
Ejemplo n.º 29
0
        public void Remove_DisposesOfItem()
        {
            var target = new DisposableCollection();
            var item   = new TestDisposableObject();

            //Act
            target.Add(item);
            var actual = target.Remove(item);

            //Assert
            actual.Should().BeTrue();
            item.IsDisposed.Should().BeTrue();
        }
Ejemplo n.º 30
0
 internal PARTY_DATA_BUFFER(Byte[] publicObject, DisposableCollection disposableCollection)
 {
     this.bufferByteCount = checked ((UInt32)publicObject.Length);
     if (bufferByteCount > 0)
     {
         this.buffer = disposableCollection.Add(new DisposableBuffer(publicObject.Length)).IntPtr;
         Marshal.Copy(publicObject, 0, this.buffer, publicObject.Length);
     }
     else
     {
         this.buffer = IntPtr.Zero;
     }
 }
Ejemplo n.º 31
0
        public void Dispose_UsingDisposesObjects()
        {
            var expected = new TestDisposableObject();

            //Act
            using (var target = new DisposableCollection())
            {
                target.Add(expected);
            };

            //Assert
            expected.IsDisposed.Should().BeTrue();
        }
        public IDisposable Set(IntPtr address, UIntPtr size, DataBreakpointTrigger trigger)
        {
            var breakpoints = new DisposableCollection();
            var threads     = Process.GetCurrentProcess().Threads
                              .Cast <ProcessThread>().ToArray();

            foreach (var thread in threads)
            {
                breakpoints.Add(this.Set(thread.Id, address, size, trigger));
            }

            return(breakpoints);
        }
Ejemplo n.º 33
0
        public void Clear_ValidCollectionWithNoDisposeFlagIsNotDisposed()
        {
            var expected = new TestDisposableObject();
            var target   = new DisposableCollection();

            target.Add(expected);

            //Act
            target.Clear(false);

            //Assert
            expected.IsDisposed.Should().BeFalse();
        }
Ejemplo n.º 34
0
        public void Clear_ObjectsAreDisposed()
        {
            var expected = new TestDisposableObject();
            var target   = new DisposableCollection();

            target.Add(expected);

            //Act
            target.Clear();

            //Assert
            expected.IsDisposed.Should().BeTrue();
        }
Ejemplo n.º 35
0
        public WorkerManager(JobStorage storage, ServerContext context, int workerCount)
        {
            _workers = new DisposableCollection<Worker>();

            for (var i = 1; i <= workerCount; i++)
            {
                var workerContext = new WorkerContext(context, i);

                var worker = new Worker(storage, workerContext);
                worker.Start();

                _workers.Add(worker);
            }
        }
Ejemplo n.º 36
0
        public void ItemSet_DisposesOriginalItem()
        {
            var target       = new DisposableCollection();
            var originalItem = new TestDisposableObject();
            var newItem      = new TestDisposableObject();

            //Act
            target.Add(originalItem);
            target[0] = newItem;

            //Assert
            originalItem.IsDisposed.Should().BeTrue();
            newItem.IsDisposed.Should().BeFalse();
        }
Ejemplo n.º 37
0
        public void Detach_DoesNotDispose()
        {
            var target   = new DisposableCollection();
            var expected = new TestDisposableObject();

            target.Add(expected);

            //Act
            var actual = target.Detach(expected);

            //Assert
            actual.Should().BeTrue();
            expected.IsDisposed.Should().BeFalse();
        }
Ejemplo n.º 38
0
 private static void PackInnerPC(Stream output, string directory)
 {
     using (var streamCollection = new DisposableCollection <Stream>())
     {
         var innerPsarc = new PSARC.PSARC();
         WalkThroughDirectory("", directory, (a, b) =>
         {
             var fileStream = File.OpenRead(b);
             streamCollection.Add(fileStream);
             innerPsarc.AddEntry(a, fileStream);
         });
         innerPsarc.Write(output, false);
     }
 }
		public void Add_Remove_Dispose()
		{
			var collection = new DisposableCollection();

			var disposable = new Mock<IDisposable>(MockBehavior.Strict);
			disposable.Setup(_ => _.Dispose());
			collection.Add(disposable.Object);

			var contains = collection.Remove(disposable.Object);
			Assert.IsTrue(contains);

			collection.Dispose();
			disposable.Verify(_ => _.Dispose(), Times.Never);
			Assert.AreEqual(0, collection.Count);
		}
        private static DisposableCollection<Device> CreateSubDevices(ClDeviceID device, IntPtr[] properties)
        {
            uint required;
            ErrorHandler.ThrowOnFailure(clCreateSubDevices(device, properties, 0, null, out required));

            ClDeviceID[] devices = new ClDeviceID[required];
            uint actual;
            ErrorHandler.ThrowOnFailure(clCreateSubDevices(device, properties, required, devices, out actual));

            DisposableCollection<Device> result = new DisposableCollection<Device>(false);
            for (int i = 0; i < actual; i++)
                result.Add(new Device(devices[i], new DeviceSafeHandle(devices[i])));

            return result;
        }
		public void SetUp()
		{
			_disposables = new DisposableCollection();
			_waitEvent = new ManualResetEvent(false);
			_disposables.Add(_waitEvent);
			_stompServer = new StompServer();
			_stompServer.ListenOn(new IPEndPoint(IPAddress.Loopback, 0));
			_disposables.Add(_stompServer);
			var ipEndPoint = (IPEndPoint) _stompServer.EndPoints.First();
			var url = "tcp://" + ipEndPoint.Address + ":" + ipEndPoint.Port;
			_serverUrl = new Uri(url);

			_client1 = new SprocketClient();
			_disposables.Add(_client1);
			_client1.Open(_serverUrl);

			_client2 = new SprocketClient();
			_disposables.Add(_client2);
			_client2.Open(_serverUrl);
		}
Ejemplo n.º 42
0
        public void Add_and_dispose()
        {
            var collection = new DisposableCollection();
            var d1 = new Component();
            var d2 = new DodgyDisposable();
            var d3 = new Component();

            collection.Add(d1);
            collection.Add(d2);
            collection.Add(d3);

            var d1Disposed = false;
            d1.Disposed += (sender, args) => d1Disposed = true;
            var d3Disposed = false;
            d3.Disposed += (sender, args) => d3Disposed = true;

            Assert.IsFalse(collection.IsDisposed);
            collection.Dispose();
            Assert.IsTrue(collection.IsDisposed);
            Assert.IsTrue(d1Disposed);
            Assert.IsTrue(d3Disposed);
            Assert.AreEqual(1, d2.DisposeCount);
        }
        private static void GenerateSongPsarc(Stream output, DLCPackageData info, GamePlatform platform)
        {
            var soundBankName = String.Format("Song_{0}", info.Name);
            Stream albumArtStream = null;
            try
            {
                if (File.Exists(info.AlbumArtPath))
                {
                    albumArtStream = File.OpenRead(info.AlbumArtPath);
                }
                else
                {
                    albumArtStream = new MemoryStream(Resources.albumart);
                }
                using (var aggregateGraphStream = new MemoryStream())
                using (var manifestStream = new MemoryStream())
                using (var xblockStream = new MemoryStream())
                using (var soundbankStream = new MemoryStream())
                using (var packageIdStream = new MemoryStream())
                using (var soundStream = OggFile.ConvertOgg(platform.GetOgg(info)))
                using (var arrangementFiles = new DisposableCollection<Stream>())
                {
                    var manifestBuilder = new ManifestBuilder
                    {
                        AggregateGraph = new AggregateGraph.AggregateGraph
                        {
                            SoundBank = new SoundBank { File = soundBankName + ".bnk" },
                            AlbumArt = new AlbumArt { File = info.AlbumArtPath }
                        }
                    };

                    foreach (var x in info.Arrangements)
                    {
                        //Generate sng file in execution time
                        GenerateSNG(x, platform);

                        manifestBuilder.AggregateGraph.SongFiles.Add(x.SongFile);
                        manifestBuilder.AggregateGraph.SongXMLs.Add(x.SongXml);
                    }
                    manifestBuilder.AggregateGraph.XBlock = new XBlockFile { File = info.Name + ".xblock" };
                    manifestBuilder.AggregateGraph.Write(info.Name, platform.GetPathName(), platform, aggregateGraphStream);
                    aggregateGraphStream.Flush();
                    aggregateGraphStream.Seek(0, SeekOrigin.Begin);

                    {
                        var manifestData = manifestBuilder.GenerateManifest(info.Name, info.Arrangements, info.SongInfo, platform);
                        var writer = new StreamWriter(manifestStream);
                        writer.Write(manifestData);
                        writer.Flush();
                        manifestStream.Seek(0, SeekOrigin.Begin);
                    }

                    XBlockGenerator.Generate(info.Name, manifestBuilder.Manifest, manifestBuilder.AggregateGraph, xblockStream);
                    xblockStream.Flush();
                    xblockStream.Seek(0, SeekOrigin.Begin);

                    var soundFileName = SoundBankGenerator.GenerateSoundBank(info.Name, soundStream, soundbankStream, info.Volume, platform);
                    soundbankStream.Flush();
                    soundbankStream.Seek(0, SeekOrigin.Begin);

                    GenerateSongPackageId(packageIdStream, info.Name);

                    var songPsarc = new PSARC.PSARC();
                    songPsarc.AddEntry("PACKAGE_ID", packageIdStream);
                    songPsarc.AddEntry("AggregateGraph.nt", aggregateGraphStream);
                    songPsarc.AddEntry("Manifests/songs.manifest.json", manifestStream);
                    songPsarc.AddEntry(String.Format("Exports/Songs/{0}.xblock", info.Name), xblockStream);
                    songPsarc.AddEntry(String.Format("Audio/{0}/{1}.bnk", platform.GetPathName()[0], soundBankName), soundbankStream);
                    songPsarc.AddEntry(String.Format("Audio/{0}/{1}.ogg", platform.GetPathName()[0], soundFileName), soundStream);
                    songPsarc.AddEntry(String.Format("GRAssets/AlbumArt/{0}.dds", manifestBuilder.AggregateGraph.AlbumArt.Name), albumArtStream);

                    foreach (var x in info.Arrangements)
                    {
                        var xmlFile = File.OpenRead(x.SongXml.File);
                        arrangementFiles.Add(xmlFile);
                        var sngFile = File.OpenRead(x.SongFile.File);
                        arrangementFiles.Add(sngFile);
                        songPsarc.AddEntry(String.Format("GR/Behaviors/Songs/{0}.xml", Path.GetFileNameWithoutExtension(x.SongXml.File)), xmlFile);
                        songPsarc.AddEntry(String.Format("GRExports/{0}/{1}.sng", platform.GetPathName()[1], Path.GetFileNameWithoutExtension(x.SongFile.File)), sngFile);
                    }
                    songPsarc.Write(output);
                    output.Flush();
                    output.Seek(0, SeekOrigin.Begin);
                }
            }
            finally
            {
                if (albumArtStream != null)
                {
                    albumArtStream.Dispose();
                }
            }
        }
		public void Dispose_Reverse()
		{
			var order = String.Empty;
			var collection = new DisposableCollection();

			const int count = 6;
			for (var i = 1; i <= count; ++i)
			{
				var local = i;
				var disposable = new Mock<IDisposable>(MockBehavior.Strict);
				disposable.Setup(_ => _.Dispose()).Callback(() => order += local);
				collection.Add(disposable.Object);
			}

			Assert.AreEqual(count, collection.Count);
			collection.Dispose();

			Assert.AreEqual(0, collection.Count);
			Assert.AreEqual("654321", order);
		}
		public void GetEnumerator_ThenAdd_IsSnapshot()
		{
			var collection = new DisposableCollection();

			collection.Add(Disposable.Empty);
			Assert.AreEqual(1, collection.Count);

			var enumerator = collection.GetEnumerator();

			collection.Add(Disposable.Empty);
			Assert.AreEqual(2, collection.Count);

			var count = 0;
			while (enumerator.MoveNext())
			{
				++count;
			}

			Assert.AreEqual(1, count);
		}
        private static void GenerateSongPsarcRS1(Stream output, DLCPackageData info, Platform platform)
        {
            var soundBankName = String.Format("Song_{0}", info.Name);

            try
            {
                Stream albumArtStream = null,
                       audioStream = null;

                string albumArtPath;
                if (File.Exists(info.AlbumArtPath)) {
                    albumArtPath = info.AlbumArtPath;
                } else {
                    using (var defaultArtStream = new MemoryStream(Resources.albumart)) {
                        albumArtPath = GeneralExtensions.GetTempFileName(".dds");
                        defaultArtStream.WriteFile(albumArtPath);
                        defaultArtStream.Dispose();
                        TMPFILES_ART.Add(albumArtPath);
                    }
                }

                var ddsfiles = info.ArtFiles;
                if (ddsfiles == null) {
                    ddsfiles = new List<DDSConvertedFile>();
                    ddsfiles.Add(new DDSConvertedFile() { sizeX = 512, sizeY = 512, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                    ToDDS(ddsfiles);

                    // Save for reuse
                    info.ArtFiles = ddsfiles;
                }

                albumArtStream = new FileStream(ddsfiles[0].destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                // AUDIO
                var audioFile = info.OggPath;
                if (File.Exists(audioFile))
                    if (platform.IsConsole != audioFile.GetAudioPlatform().IsConsole)
                        audioStream = OggFile.ConvertAudioPlatform(audioFile);
                    else
                        audioStream = File.OpenRead(audioFile);
                else
                    throw new InvalidOperationException(String.Format("Audio file '{0}' not found.", audioFile));

                using (var aggregateGraphStream = new MemoryStream())
                using (var manifestStream = new MemoryStream())
                using (var xblockStream = new MemoryStream())
                using (var soundbankStream = new MemoryStream())
                using (var packageIdStream = new MemoryStream())
                using (var soundStream = OggFile.ConvertOgg(audioStream))
                using (var arrangementFiles = new DisposableCollection<Stream>()) {
                    var manifestBuilder = new ManifestBuilder {
                        AggregateGraph = new AggregateGraph.AggregateGraph {
                            SoundBank = new SoundBank { File = soundBankName + ".bnk" },
                            AlbumArt = new AlbumArt { File = info.AlbumArtPath }
                        }
                    };

                    foreach (var x in info.Arrangements) {
                        //Generate sng file in execution time
                        GenerateSNG(x, platform);

                        manifestBuilder.AggregateGraph.SongFiles.Add(x.SongFile);
                        manifestBuilder.AggregateGraph.SongXMLs.Add(x.SongXml);
                    }
                    manifestBuilder.AggregateGraph.XBlock = new XBlockFile { File = info.Name + ".xblock" };
                    manifestBuilder.AggregateGraph.Write(info.Name, platform.GetPathName(), platform, aggregateGraphStream);
                    aggregateGraphStream.Flush();
                    aggregateGraphStream.Seek(0, SeekOrigin.Begin);

                    {
                        var manifestData = manifestBuilder.GenerateManifest(info.Name, info.Arrangements, info.SongInfo, platform);
                        var writer = new StreamWriter(manifestStream);
                        writer.Write(manifestData);
                        writer.Flush();
                        manifestStream.Seek(0, SeekOrigin.Begin);
                    }

                    GameXblock<Entity>.Generate(info.Name, manifestBuilder.Manifest, manifestBuilder.AggregateGraph, xblockStream);
                    xblockStream.Flush();
                    xblockStream.Seek(0, SeekOrigin.Begin);

                    var soundFileName = SoundBankGenerator.GenerateSoundBank(info.Name, soundStream, soundbankStream, info.Volume, platform);
                    soundbankStream.Flush();
                    soundbankStream.Seek(0, SeekOrigin.Begin);

                    GenerateSongPackageId(packageIdStream, info.Name);

                    var songPsarc = new PSARC.PSARC();
                    songPsarc.AddEntry("PACKAGE_ID", packageIdStream);
                    songPsarc.AddEntry("AggregateGraph.nt", aggregateGraphStream);
                    songPsarc.AddEntry("Manifests/songs.manifest.json", manifestStream);
                    songPsarc.AddEntry(String.Format("Exports/Songs/{0}.xblock", info.Name), xblockStream);
                    songPsarc.AddEntry(String.Format("Audio/{0}/{1}.bnk", platform.GetPathName()[0], soundBankName), soundbankStream);
                    songPsarc.AddEntry(String.Format("Audio/{0}/{1}.ogg", platform.GetPathName()[0], soundFileName), soundStream);
                    songPsarc.AddEntry(String.Format("GRAssets/AlbumArt/{0}.dds", manifestBuilder.AggregateGraph.AlbumArt.Name), albumArtStream);

                    foreach (var x in info.Arrangements) {
                        var xmlFile = File.OpenRead(x.SongXml.File);
                        arrangementFiles.Add(xmlFile);
                        var sngFile = File.OpenRead(x.SongFile.File);
                        arrangementFiles.Add(sngFile);
                        songPsarc.AddEntry(String.Format("GR/Behaviors/Songs/{0}.xml", Path.GetFileNameWithoutExtension(x.SongXml.File)), xmlFile);
                        songPsarc.AddEntry(String.Format("GRExports/{0}/{1}.sng", platform.GetPathName()[1], Path.GetFileNameWithoutExtension(x.SongFile.File)), sngFile);
                    }
                    songPsarc.Write(output, false);
                    output.Flush();
                    output.Seek(0, SeekOrigin.Begin);
                }
            }
            finally
            {
            }
        }
        private static void GenerateRS2014SongPsarc(MemoryStream output, DLCPackageData info, Platform platform)
        {
            var dlcName = info.Name.ToLower();

            {
                var packPsarc = new PSARC.PSARC();

                // Stream objects
                Stream soundStream = null,
                       soundPreviewStream = null,
                       rsenumerableRootStream = null,
                       rsenumerableSongStream = null;

                try {
                    // ALBUM ART
                    var ddsfiles = info.ArtFiles;

                    if (ddsfiles == null) {
                        string albumArtPath;
                        if (File.Exists(info.AlbumArtPath)) {
                            albumArtPath = info.AlbumArtPath;
                        } else {
                            using (var albumArtStream = new MemoryStream(Resources.albumart2014_256))
                            {
                                albumArtPath = GeneralExtensions.GetTempFileName(".dds");
                                albumArtStream.WriteFile(albumArtPath);
                                TMPFILES_ART.Add(albumArtPath);
                            }
                        }

                        ddsfiles = new List<DDSConvertedFile>();
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 64, sizeY = 64, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 128, sizeY = 128, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 256, sizeY = 256, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });

                        // Convert to DDS
                        ToDDS(ddsfiles);

                        // Save for reuse
                        info.ArtFiles = ddsfiles;
                    }

                    foreach (var dds in ddsfiles)
                        packPsarc.AddEntry(String.Format("gfxassets/album_art/album_{0}_{1}.dds", dlcName, dds.sizeX), new FileStream(dds.destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read));

                    //Lyrics Font Texture
                    if (File.Exists(info.LyricsTex))
                        packPsarc.AddEntry(String.Format("assets/ui/lyrics/{0}/lyrics_{0}.dds", dlcName), new FileStream(info.LyricsTex, FileMode.Open, FileAccess.Read, FileShare.Read));

                    // AUDIO
                    var audioFile = info.OggPath;
                    if (File.Exists(audioFile))
                        if (platform.IsConsole != audioFile.GetAudioPlatform().IsConsole)
                            soundStream = OggFile.ConvertAudioPlatform(audioFile);
                        else
                            soundStream = File.OpenRead(audioFile);
                    else
                        throw new InvalidOperationException(String.Format("Audio file '{0}' not found.", audioFile));

                    // AUDIO PREVIEW
                    var previewAudioFile = info.OggPreviewPath;
                    if (File.Exists(previewAudioFile))
                        if (platform.IsConsole != previewAudioFile.GetAudioPlatform().IsConsole)
                            soundPreviewStream = OggFile.ConvertAudioPlatform(previewAudioFile);
                        else
                            soundPreviewStream = File.OpenRead(previewAudioFile);
                    else
                        soundPreviewStream = soundStream;

                    // FLAT MODEL
                    rsenumerableRootStream = new MemoryStream(Resources.rsenumerable_root);
                    packPsarc.AddEntry("flatmodels/rs/rsenumerable_root.flat", rsenumerableRootStream);
                    rsenumerableSongStream = new MemoryStream(Resources.rsenumerable_song);
                    packPsarc.AddEntry("flatmodels/rs/rsenumerable_song.flat", rsenumerableSongStream);

                    using (var toolkitVersionStream = new MemoryStream())
                    using (var appIdStream = new MemoryStream())
                    using (var packageListStream = new MemoryStream())
                    using (var soundbankStream = new MemoryStream())
                    using (var soundbankPreviewStream = new MemoryStream())
                    using (var aggregateGraphStream = new MemoryStream())
                    using (var manifestHeaderHSANStream = new MemoryStream())
                    using (var manifestHeaderHSONStreamList = new DisposableCollection<Stream>())
                    using (var manifestStreamList = new DisposableCollection<Stream>())
                    using (var arrangementStream = new DisposableCollection<Stream>())
                    using (var showlightStream = new MemoryStream())
                    using (var xblockStream = new MemoryStream())
                    {
                        // TOOLKIT VERSION
                        GenerateToolkitVersion(toolkitVersionStream, info.PackageVersion);
                        packPsarc.AddEntry("toolkit.version", toolkitVersionStream);

                        // APP ID
                        if (!platform.IsConsole)
                        {
                            GenerateAppId(appIdStream, info.AppId, platform);
                            packPsarc.AddEntry("appid.appid", appIdStream);
                        }

                        if (platform.platform == GamePlatform.XBox360) {
                            var packageListWriter = new StreamWriter(packageListStream);
                            packageListWriter.Write(dlcName);
                            packageListWriter.Flush();
                            packageListStream.Seek(0, SeekOrigin.Begin);
                            string packageList = "PackageList.txt";
                            packageListStream.WriteTmpFile(packageList, platform);
                        }

                        // SOUNDBANK
                        var soundbankFileName = String.Format("song_{0}", dlcName);
                        var audioFileNameId = SoundBankGenerator2014.GenerateSoundBank(info.Name, soundStream, soundbankStream, info.Volume, platform);
                        packPsarc.AddEntry(String.Format("audio/{0}/{1}.bnk", platform.GetPathName()[0].ToLower(), soundbankFileName), soundbankStream);
                        packPsarc.AddEntry(String.Format("audio/{0}/{1}.wem", platform.GetPathName()[0].ToLower(), audioFileNameId), soundStream);

                        // SOUNDBANK PREVIEW
                        var soundbankPreviewFileName = String.Format("song_{0}_preview", dlcName);
                        dynamic audioPreviewFileNameId;
                        var previewVolume = (info.PreviewVolume != null) ? (float)info.PreviewVolume : info.Volume;
                        if (!soundPreviewStream.Equals(soundStream))
                            audioPreviewFileNameId = SoundBankGenerator2014.GenerateSoundBank(info.Name + "_Preview", soundPreviewStream, soundbankPreviewStream, previewVolume, platform, true);
                        else
                            audioPreviewFileNameId = SoundBankGenerator2014.GenerateSoundBank(info.Name + "_Preview", soundPreviewStream, soundbankPreviewStream, info.Volume, platform, true, true);
                        packPsarc.AddEntry(String.Format("audio/{0}/{1}.bnk", platform.GetPathName()[0].ToLower(), soundbankPreviewFileName), soundbankPreviewStream);
                        if (!soundPreviewStream.Equals(soundStream)) packPsarc.AddEntry(String.Format("audio/{0}/{1}.wem", platform.GetPathName()[0].ToLower(), audioPreviewFileNameId), soundPreviewStream);

                        // AGGREGATE GRAPH
                        var aggregateGraphFileName = String.Format("{0}_aggregategraph.nt", dlcName);
                        var aggregateGraph = new AggregateGraph2014(info, platform);
                        aggregateGraph.Serialize(aggregateGraphStream);
                        aggregateGraphStream.Flush();
                        aggregateGraphStream.Seek(0, SeekOrigin.Begin);
                        packPsarc.AddEntry(aggregateGraphFileName, aggregateGraphStream);

                        var manifestHeader = new ManifestHeader2014<AttributesHeader2014>(platform);
                        var songPartition = new SongPartition();
                        var songPartitionCount = new SongPartition();

                        foreach (var arrangement in info.Arrangements)
                        {
                            var arrangementFileName = songPartition.GetArrangementFileName(arrangement.Name, arrangement.ArrangementType).ToLower();

                            // GAME SONG (SNG)
                            UpdateToneDescriptors(info);
                            GenerateSNG(arrangement, platform);
                            var sngSongFile = File.OpenRead(arrangement.SongFile.File);
                            arrangementStream.Add(sngSongFile);
                            packPsarc.AddEntry(String.Format("songs/bin/{0}/{1}_{2}.sng", platform.GetPathName()[1].ToLower(), dlcName, arrangementFileName), sngSongFile);

                            // XML SONG
                            var xmlSongFile = File.OpenRead(arrangement.SongXml.File);
                            arrangementStream.Add(xmlSongFile);
                            packPsarc.AddEntry(String.Format("songs/arr/{0}_{1}.xml", dlcName, arrangementFileName), xmlSongFile);

                            // MANIFEST
                            var manifest = new Manifest2014<Attributes2014>();
                            var attribute = new Attributes2014(arrangementFileName, arrangement, info, platform);
                            if (arrangement.ArrangementType != Sng.ArrangementType.Vocal)
                            {
                                attribute.SongPartition = songPartitionCount.GetSongPartition(arrangement.Name, arrangement.ArrangementType);
                                if (attribute.SongPartition > 1)
                                { // Make the second arrangement with the same arrangement type as ALTERNATE arrangement ingame
                                    attribute.Representative = 0;
                                    attribute.ArrangementProperties.Represent = 0;
                                }
                            }
                            var attributeDictionary = new Dictionary<string, Attributes2014> { { "Attributes", attribute } };
                            manifest.Entries.Add(attribute.PersistentID, attributeDictionary);
                            var manifestStream = new MemoryStream();
                            manifestStreamList.Add(manifestStream);
                            manifest.Serialize(manifestStream);
                            manifestStream.Seek(0, SeekOrigin.Begin);

                            var jsonPathPC = "manifests/songs_dlc_{0}/{0}_{1}.json";
                            var jsonPathConsole = "manifests/songs_dlc/{0}_{1}.json";
                            packPsarc.AddEntry(String.Format((platform.IsConsole ? jsonPathConsole : jsonPathPC), dlcName, arrangementFileName), manifestStream);

                            // MANIFEST HEADER
                            var attributeHeaderDictionary = new Dictionary<string, AttributesHeader2014> { { "Attributes", new AttributesHeader2014(attribute) } };

                            if (platform.IsConsole) {
                                // One for each arrangements (Xbox360/PS3)
                                manifestHeader = new ManifestHeader2014<AttributesHeader2014>(platform);
                                manifestHeader.Entries.Add(attribute.PersistentID, attributeHeaderDictionary);
                                var manifestHeaderStream = new MemoryStream();
                                manifestHeaderHSONStreamList.Add(manifestHeaderStream);
                                manifestHeader.Serialize(manifestHeaderStream);
                                manifestStream.Seek(0, SeekOrigin.Begin);
                                packPsarc.AddEntry(String.Format("manifests/songs_dlc/{0}_{1}.hson", dlcName, arrangementFileName), manifestHeaderStream);
                            } else {
                                // One for all arrangements (PC/Mac)
                                manifestHeader.Entries.Add(attribute.PersistentID, attributeHeaderDictionary);
                            }
                        }

                        if (!platform.IsConsole) {
                            manifestHeader.Serialize(manifestHeaderHSANStream);
                            manifestHeaderHSANStream.Seek(0, SeekOrigin.Begin);
                            packPsarc.AddEntry(String.Format("manifests/songs_dlc_{0}/songs_dlc_{0}.hsan", dlcName), manifestHeaderHSANStream);
                        }

                        // SHOWLIGHT
                        Showlights showlight = new Showlights(info);
                        showlight.Serialize(showlightStream);
                        if(showlightStream.CanRead)
                            packPsarc.AddEntry(String.Format("songs/arr/{0}_showlights.xml", dlcName), showlightStream);

                        // XBLOCK
                        GameXblock<Entity2014> game = GameXblock<Entity2014>.Generate2014(info, platform);
                        game.SerializeXml(xblockStream);
                        xblockStream.Flush();
                        xblockStream.Seek(0, SeekOrigin.Begin);
                        packPsarc.AddEntry(String.Format("gamexblocks/nsongs/{0}.xblock", dlcName), xblockStream);

                        // WRITE PACKAGE
                        packPsarc.Write(output, !platform.IsConsole);
                        output.Flush();
                        output.Seek(0, SeekOrigin.Begin);
                        output.WriteTmpFile(String.Format("{0}.psarc", dlcName), platform);
                    }
                } catch (Exception ex) {
                    throw ex;
                } finally {
                    // Dispose all objects
                    if (soundStream != null)
                        soundStream.Dispose();
                    if (soundPreviewStream != null)
                        soundPreviewStream.Dispose();
                    if (rsenumerableRootStream != null)
                        rsenumerableRootStream.Dispose();
                    if (rsenumerableSongStream != null)
                        rsenumerableSongStream.Dispose();
                    DeleteTmpFiles(TMPFILES_SNG);
                    DeleteTmpFiles(TMPFILES_ART);
                }
            }
        }
		public void Dispose_Add_Fail()
		{
			var collection = new DisposableCollection();
			collection.Dispose();
			collection.Add(Disposable.Empty);
		}
		public void Dispose_Remove_Fail()
		{
			var collection = new DisposableCollection();
			collection.Dispose();
			collection.Remove(Disposable.Empty);
		}
		public void Dispose_Clear_Fail()
		{
			var collection = new DisposableCollection();
			collection.Dispose();
			collection.Clear();
		}
        private static void GenerateRS2014SongPsarc(Stream output, DLCPackageData info, Platform platform, int pnum = -1)
        {
            // TODO: Benchmark processes and optimize speed
            dlcName = info.Name.ToLower();
            packPsarc = new PSARC.PSARC();

            // Stream objects
            Stream soundStream = null,
                   soundPreviewStream = null,
                   rsenumerableRootStream = null,
                   rsenumerableSongStream = null;

            try
            {
                // ALBUM ART
                var ddsfiles = info.ArtFiles;

                if (ddsfiles == null)
                {
                    string albumArtPath;
                    if (File.Exists(info.AlbumArtPath))
                    {
                        albumArtPath = info.AlbumArtPath;
                    }
                    else
                    {
                        using (var albumArtStream = new MemoryStream(Resources.albumart2014_256))
                        {
                            albumArtPath = GeneralExtensions.GetTempFileName(".dds");
                            albumArtStream.WriteFile(albumArtPath);
                            TMPFILES_ART.Add(albumArtPath);
                        }
                    }

                    ddsfiles = new List<DDSConvertedFile>();
                    ddsfiles.Add(new DDSConvertedFile() { sizeX = 64, sizeY = 64, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                    ddsfiles.Add(new DDSConvertedFile() { sizeX = 128, sizeY = 128, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                    ddsfiles.Add(new DDSConvertedFile() { sizeX = 256, sizeY = 256, sourceFile = albumArtPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });

                    // Convert to DDS
                    ToDDS(ddsfiles);

                    // Save for reuse
                    info.ArtFiles = ddsfiles;
                }

                foreach (var dds in info.ArtFiles)
                {
                    packPsarc.AddEntry(String.Format("gfxassets/album_art/album_{0}_{1}.dds", dlcName, dds.sizeX), new FileStream(dds.destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read));
                    TMPFILES_ART.Add(dds.destinationFile);
                }

                // Lyric Art Texture
                if (File.Exists(info.LyricArtPath))
                    packPsarc.AddEntry(String.Format("assets/ui/lyrics/{0}/lyrics_{0}.dds", dlcName), new FileStream(info.LyricArtPath, FileMode.Open, FileAccess.Read, FileShare.Read));

                // AUDIO
                var audioFile = info.OggPath;
                if (File.Exists(audioFile))
                    if (platform.IsConsole != audioFile.GetAudioPlatform().IsConsole)
                        soundStream = OggFile.ConvertAudioPlatform(audioFile);
                    else
                        soundStream = File.OpenRead(audioFile);
                else
                    throw new InvalidOperationException(String.Format("Audio file '{0}' not found.", audioFile));

                // AUDIO PREVIEW
                var previewAudioFile = info.OggPreviewPath;
                if (File.Exists(previewAudioFile))
                    if (platform.IsConsole != previewAudioFile.GetAudioPlatform().IsConsole)
                        soundPreviewStream = OggFile.ConvertAudioPlatform(previewAudioFile);
                    else
                        soundPreviewStream = File.OpenRead(previewAudioFile);
                else
                    soundPreviewStream = soundStream;

                // FLAT MODEL
                rsenumerableRootStream = new MemoryStream(Resources.rsenumerable_root);
                packPsarc.AddEntry("flatmodels/rs/rsenumerable_root.flat", rsenumerableRootStream);
                rsenumerableSongStream = new MemoryStream(Resources.rsenumerable_song);
                packPsarc.AddEntry("flatmodels/rs/rsenumerable_song.flat", rsenumerableSongStream);

                using (var toolkitVersionStream = new MemoryStream())
                using (var appIdStream = new MemoryStream())
                using (var packageListStream = new MemoryStream())
                using (var soundbankStream = new MemoryStream())
                using (var soundbankPreviewStream = new MemoryStream())
                using (var aggregateGraphStream = new MemoryStream())
                using (var manifestHeaderHSANStream = new MemoryStream())
                using (var manifestHeaderHSONStreamList = new DisposableCollection<Stream>())
                using (var manifestStreamList = new DisposableCollection<Stream>())
                using (var arrangementStream = new DisposableCollection<Stream>())
                using (var showlightStream = new MemoryStream())
                using (var xblockStream = new MemoryStream())
                {
                    // TOOLKIT VERSION
                    var stopHere = info;
                    GenerateToolkitVersion(toolkitVersionStream, info.ToolkitInfo.PackageAuthor, info.ToolkitInfo.PackageVersion, info.ToolkitInfo.PackageComment);
                    packPsarc.AddEntry("toolkit.version", toolkitVersionStream);

                    // APP ID
                    if (!platform.IsConsole)
                    {
                        GenerateAppId(appIdStream, info.AppId, platform);
                        packPsarc.AddEntry("appid.appid", appIdStream);
                    }

                    if (platform.platform == GamePlatform.XBox360)
                    {
                        var packageListWriter = new StreamWriter(packageListStream);
                        packageListWriter.Write(dlcName);
                        packageListWriter.Flush();
                        packageListStream.Seek(0, SeekOrigin.Begin);
                        packageListStream.WriteTmpFile("PackageList.txt", platform);
                    }

                    // SOUNDBANK
                    var soundbankFileName = String.Format("song_{0}", dlcName);
                    var audioFileNameId = SoundBankGenerator2014.GenerateSoundBank(info.Name, soundStream, soundbankStream, info.Volume, platform);
                    packPsarc.AddEntry(String.Format("audio/{0}/{1}.bnk", platform.GetPathName()[0].ToLower(), soundbankFileName), soundbankStream);
                    packPsarc.AddEntry(String.Format("audio/{0}/{1}.wem", platform.GetPathName()[0].ToLower(), audioFileNameId), soundStream);

                    // SOUNDBANK PREVIEW
                    var soundbankPreviewFileName = String.Format("song_{0}_preview", dlcName);
                    dynamic audioPreviewFileNameId;
                    var previewVolume = info.PreviewVolume ?? info.Volume;
                    audioPreviewFileNameId = SoundBankGenerator2014.GenerateSoundBank(info.Name + "_Preview", soundPreviewStream, soundbankPreviewStream, previewVolume, platform, true, !(File.Exists(previewAudioFile)));
                    packPsarc.AddEntry(String.Format("audio/{0}/{1}.bnk", platform.GetPathName()[0].ToLower(), soundbankPreviewFileName), soundbankPreviewStream);
                    if (!soundPreviewStream.Equals(soundStream)) packPsarc.AddEntry(String.Format("audio/{0}/{1}.wem", platform.GetPathName()[0].ToLower(), audioPreviewFileNameId), soundPreviewStream);

                    // AGGREGATE GRAPH
                    var aggregateGraphFileName = String.Format("{0}_aggregategraph.nt", dlcName);
                    var aggregateGraph = new AggregateGraph2014.AggregateGraph2014(info, platform);
                    aggregateGraph.Serialize(aggregateGraphStream);
                    aggregateGraphStream.Flush();
                    aggregateGraphStream.Seek(0, SeekOrigin.Begin);
                    packPsarc.AddEntry(aggregateGraphFileName, aggregateGraphStream);

                    var manifestHeader = new ManifestHeader2014<AttributesHeader2014>(platform);
                    var songPartition = new SongPartition();
                    var songPartitionCount = new SongPartition();

                    foreach (var arrangement in info.Arrangements)
                    {
                        if (arrangement.ArrangementType == ArrangementType.ShowLight)
                            continue;

                        var arrangementFileName = songPartition.GetArrangementFileName(arrangement.Name, arrangement.ArrangementType).ToLower();

                        // GAME SONG (SNG)
                        UpdateToneDescriptors(info);
                        GenerateSNG(arrangement, platform);
                        var sngSongFile = File.OpenRead(arrangement.SongFile.File);
                        arrangementStream.Add(sngSongFile);
                        packPsarc.AddEntry(String.Format("songs/bin/{0}/{1}_{2}.sng", platform.GetPathName()[1].ToLower(), dlcName, arrangementFileName), sngSongFile);

                        // XML SONG
                        var xmlSongFile = File.OpenRead(arrangement.SongXml.File);
                        arrangementStream.Add(xmlSongFile);
                        packPsarc.AddEntry(String.Format("songs/arr/{0}_{1}.xml", dlcName, arrangementFileName), xmlSongFile);

                        // MANIFEST
                        var manifest = new Manifest2014<Attributes2014>();
                        var attribute = new Attributes2014(arrangementFileName, arrangement, info, platform);
                        if (arrangement.ArrangementType == ArrangementType.Bass || arrangement.ArrangementType == ArrangementType.Guitar)
                        {
                            // TODO: monitor this new code for bugs
                            // represent is set to "1" by default, if there is a bonus then set represent to "0"
                            attribute.Representative = arrangement.BonusArr ? 0 : 1;
                            attribute.ArrangementProperties.Represent = arrangement.BonusArr ? 0 : 1;

                            attribute.SongPartition = songPartitionCount.GetSongPartition(arrangement.Name, arrangement.ArrangementType);
                            if (attribute.SongPartition > 1 && !arrangement.BonusArr)
                            {
                                // for alternate arrangement then both represent and bonus are set to "0"
                                attribute.Representative = 0;
                                attribute.ArrangementProperties.Represent = 0;
                            }
                        }

                        var attributeDictionary = new Dictionary<string, Attributes2014> { { "Attributes", attribute } };
                        manifest.Entries.Add(attribute.PersistentID, attributeDictionary);
                        var manifestStream = new MemoryStream();
                        manifestStreamList.Add(manifestStream);
                        manifest.Serialize(manifestStream);
                        manifestStream.Seek(0, SeekOrigin.Begin);

                        const string jsonPathPC = "manifests/songs_dlc_{0}/{0}_{1}.json";
                        const string jsonPathConsole = "manifests/songs_dlc/{0}_{1}.json";
                        packPsarc.AddEntry(String.Format((platform.IsConsole ? jsonPathConsole : jsonPathPC), dlcName, arrangementFileName), manifestStream);

                        // MANIFEST HEADER
                        var attributeHeaderDictionary = new Dictionary<string, AttributesHeader2014> { { "Attributes", new AttributesHeader2014(attribute) } };

                        if (platform.IsConsole)
                        {
                            // One for each arrangements (Xbox360/PS3)
                            manifestHeader = new ManifestHeader2014<AttributesHeader2014>(platform);
                            manifestHeader.Entries.Add(attribute.PersistentID, attributeHeaderDictionary);
                            var manifestHeaderStream = new MemoryStream();
                            manifestHeaderHSONStreamList.Add(manifestHeaderStream);
                            manifestHeader.Serialize(manifestHeaderStream);
                            manifestStream.Seek(0, SeekOrigin.Begin);
                            packPsarc.AddEntry(String.Format("manifests/songs_dlc/{0}_{1}.hson", dlcName, arrangementFileName), manifestHeaderStream);
                        }
                        else
                        {
                            // One for all arrangements (PC/Mac)
                            manifestHeader.Entries.Add(attribute.PersistentID, attributeHeaderDictionary);
                        }
                    }

                    if (!platform.IsConsole)
                    {
                        manifestHeader.Serialize(manifestHeaderHSANStream);
                        manifestHeaderHSANStream.Seek(0, SeekOrigin.Begin);
                        packPsarc.AddEntry(String.Format("manifests/songs_dlc_{0}/songs_dlc_{0}.hsan", dlcName), manifestHeaderHSANStream);
                    }

                    // XML SHOWLIGHTS
                    var shlArr = info.Arrangements.FirstOrDefault(ar => ar.ArrangementType == ArrangementType.ShowLight);
                    if (shlArr != null && shlArr.SongXml.File != null)
                        using (var fs = File.OpenRead(shlArr.SongXml.File))
                            fs.CopyTo(showlightStream);
                    else
                    {
                        var showlight = new Showlights(info);
                        showlight.Serialize(showlightStream);
                        string shlFilePath = Path.Combine(Path.GetDirectoryName(info.Arrangements[0].SongXml.File), String.Format("{0}_showlights.xml", "cst"));
                        using (FileStream file = new FileStream(shlFilePath, FileMode.Create, FileAccess.Write))
                            showlightStream.WriteTo(file);
                    }

                    if (showlightStream.CanRead && showlightStream.Length > 0)
                        packPsarc.AddEntry(String.Format("songs/arr/{0}_showlights.xml", dlcName), showlightStream);

                    // XBLOCK
                    var game = GameXblock<Entity2014>.Generate2014(info, platform);
                    game.SerializeXml(xblockStream);
                    xblockStream.Flush();
                    xblockStream.Seek(0, SeekOrigin.Begin);
                    packPsarc.AddEntry(String.Format("gamexblocks/nsongs/{0}.xblock", dlcName), xblockStream);

                    // WRITE PACKAGE
                    packPsarc.Write(output, !platform.IsConsole);
                    output.WriteTmpFile(String.Format("{0}.psarc", dlcName), platform);
                }
            }
            finally
            {
                // Dispose all objects
                if (soundStream != null)
                    soundStream.Dispose();
                if (soundPreviewStream != null)
                    soundPreviewStream.Dispose();
                if (rsenumerableRootStream != null)
                    rsenumerableRootStream.Dispose();
                if (rsenumerableSongStream != null)
                    rsenumerableSongStream.Dispose();
                if (pnum <= 1)
                    DeleteTmpFiles(TMPFILES_ART);
                DeleteTmpFiles(TMPFILES_SNG);
            }
        }
Ejemplo n.º 52
0
        private static void PackPC(string sourcePath, string saveFileName, bool useCryptography, bool updateSng)
        {
            string[] namesBlock = Directory.GetFiles(sourcePath, "NamesBlock.bin", SearchOption.AllDirectories);
            foreach (var nb in namesBlock) {
                if (File.Exists(nb))
                    File.Delete(nb);
            }

            using (var psarcStream = new MemoryStream())
            using (var streamCollection = new DisposableCollection<Stream>())
            {
                var psarc = new PSARC.PSARC();

                foreach (var x in Directory.EnumerateFiles(sourcePath))
                {
                    var fileStream = File.OpenRead(x);
                    streamCollection.Add(fileStream);
                    var entry = new PSARC.Entry
                    {
                        Name = Path.GetFileName(x),
                        Data = fileStream,
                        Length = (ulong)fileStream.Length
                    };
                    psarc.AddEntry(entry);
                }

                foreach (var directory in Directory.EnumerateDirectories(sourcePath))
                {
                    var innerPsarcStream = new MemoryStream();
                    streamCollection.Add(innerPsarcStream);
                    var directoryName = Path.GetFileName(directory);

                    // Recreate SNG
                    if (updateSng)
                        if (directory.ToLower().IndexOf("dlc_tone_") < 0)
                            UpdateSng(directory, new Platform(GamePlatform.Pc, GameVersion.RS2012));

                    PackInnerPC(innerPsarcStream, directory);
                    psarc.AddEntry(directoryName + ".psarc", innerPsarcStream);
                }

                psarc.Write(psarcStream, false);
                psarcStream.Flush();
                psarcStream.Seek(0, SeekOrigin.Begin);

                if (Path.GetExtension(saveFileName) != ".dat")
                    saveFileName += ".dat";

                using (var outputFileStream = File.Create(saveFileName))
                {
                    if (useCryptography)
                        RijndaelEncryptor.EncryptFile(psarcStream, outputFileStream, RijndaelEncryptor.DLCKey);
                    else
                        psarcStream.CopyTo(outputFileStream);
                }
            }
        }
Ejemplo n.º 53
0
 private static void PackInnerPC(Stream output, string directory)
 {
     using (var streamCollection = new DisposableCollection<Stream>())
     {
         var innerPsarc = new PSARC.PSARC();
         WalkThroughDirectory("", directory, (a, b) =>
         {
             var fileStream = File.OpenRead(b);
             streamCollection.Add(fileStream);
             innerPsarc.AddEntry(a, fileStream);
         });
         innerPsarc.Write(output, false, false);
     }
 }
Ejemplo n.º 54
0
        private IDisposable SetupOpenCL(out Context context, out Device device, out CommandQueue commandQueue, out Kernel kernel, out Kernel kernel4, bool runOnGPU, bool useRelaxedMath, bool enableProfiling)
        {
            DisposableCollection<IDisposable> disposables = new DisposableCollection<IDisposable>(true);
            try
            {
                string buildOptions = "-cl-fast-relaxed-math";

                if (runOnGPU)
                    Console.WriteLine("Trying to run on a processor graphics");
                else
                    Console.WriteLine("Trying to run on a CPU");

                Platform platform = GetIntelOpenCLPlatform();
                Assert.IsNotNull(platform, "Failed to find Intel OpenCL platform.");

                // create the OpenCL context
                if (runOnGPU)
                {
                    Device[] devices = platform.GetDevices(DeviceType.Gpu);
                    device = devices[0];
                    context = Context.Create(device);
                    disposables.Add(context);
                }
                else
                {
                    Device[] devices = platform.GetDevices(DeviceType.Cpu);
                    device = devices[0];
                    context = Context.Create(device);
                }

                commandQueue = context.CreateCommandQueue(device, enableProfiling ? CommandQueueProperties.ProfilingEnable : 0);
                disposables.Add(commandQueue);

                string source = @"
            __kernel void
            SimpleKernel( const __global float *input, __global float *output)
            {
            size_t index = get_global_id(0);
            output[index] = rsqrt(fabs(input[index]));
            }

            __kernel /*__attribute__((vec_type_hint(float4))) */ void
            SimpleKernel4( const __global float4 *input, __global float4 *output)
            {
            size_t index = get_global_id(0);
            output[index] = rsqrt(fabs(input[index]));
            }
            ";
                Program program = context.CreateProgramWithSource(source);
                disposables.Add(program);

                program.Build(useRelaxedMath ? buildOptions : null);
                kernel = program.CreateKernel("SimpleKernel");
                disposables.Add(kernel);

                kernel4 = program.CreateKernel("SimpleKernel4");
                disposables.Add(kernel4);

                Console.WriteLine("Using device {0}...", device.Name);
                Console.WriteLine("Using {0} compute units...", device.MaxComputeUnits);
                Console.WriteLine("Buffer alignment required for zero-copying is {0} bytes", device.MemoryBaseAddressAlignment);
            }
            catch
            {
                disposables.Dispose();
                throw;
            }

            return disposables;
        }
		public void Add_Contains()
		{
			var collection = new DisposableCollection();

			var disposable = new Mock<IDisposable>(MockBehavior.Strict);
			disposable.Setup(_ => _.Dispose());
			collection.Add(disposable.Object);

			var contains = collection.Contains(disposable.Object);
			Assert.IsTrue(contains);
			Assert.AreEqual(1, collection.Count);
		}
        private static void GenerateRS2014InlayPsarc(MemoryStream output, DLCPackageData info, Platform platform)
        {
            var dlcName = info.Inlay.DLCSixName;
            // TODO updateProgress remotely from here
            {
                var packPsarc = new PSARC.PSARC();

                // Stream objects
                Stream rsenumerableRootStream = null,
                       rsenumerableGuitarStream = null;

                try {
                    // ICON/INLAY FILES
                    var ddsfiles = info.ArtFiles;

                    if (ddsfiles == null) {
                        string iconPath;
                        if (File.Exists(info.Inlay.IconPath)) {
                            iconPath = info.Inlay.IconPath;
                        } else {
                            using (var iconStream = new MemoryStream(Resources.cgm_default_icon)) {
                                iconPath = Path.ChangeExtension(Path.GetTempFileName(), ".png");
                                iconStream.WriteFile(iconPath);
                                TMPFILES_ART.Add(iconPath);
                            }
                        }

                        string inlayPath;
                        if (File.Exists(info.Inlay.InlayPath)) {
                            inlayPath = info.Inlay.InlayPath;
                        } else {
                            using (var inlayStream = new MemoryStream(Resources.cgm_default_inlay)) {
                                inlayPath = GeneralExtensions.GetTempFileName(".png");
                                inlayStream.WriteFile(inlayPath);
                                TMPFILES_ART.Add(inlayPath);
                            }
                        }

                        ddsfiles = new List<DDSConvertedFile>();
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 64, sizeY = 64, sourceFile = iconPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 128, sizeY = 128, sourceFile = iconPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 256, sizeY = 256, sourceFile = iconPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 512, sizeY = 512, sourceFile = iconPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });
                        ddsfiles.Add(new DDSConvertedFile() { sizeX = 1024, sizeY = 512, sourceFile = inlayPath, destinationFile = GeneralExtensions.GetTempFileName(".dds") });

                        // Convert to DDS
                        ToDDS(ddsfiles, DLCPackageType.Inlay);

                        // Save for reuse
                        info.ArtFiles = ddsfiles;
                    }

                    foreach (var dds in ddsfiles)
                        if (dds.sizeX == 1024)
                            packPsarc.AddEntry(String.Format("assets/gameplay/inlay/inlay_{0}.dds", dlcName), new FileStream(dds.destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read));
                        else
                            packPsarc.AddEntry(String.Format("gfxassets/rewards/guitar_inlays/reward_inlay_{0}_{1}.dds", dlcName, dds.sizeX), new FileStream(dds.destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read));

                    // FLAT MODEL
                    rsenumerableRootStream = new MemoryStream(Resources.rsenumerable_root);
                    packPsarc.AddEntry("flatmodels/rs/rsenumerable_root.flat", rsenumerableRootStream);
                    rsenumerableGuitarStream = new MemoryStream(Resources.rsenumerable_guitar);
                    packPsarc.AddEntry("flatmodels/rs/rsenumerable_guitars.flat", rsenumerableGuitarStream);

                    using (var toolkitVersionStream = new MemoryStream())
                    using (var appIdStream = new MemoryStream())
                    using (var packageListStream = new MemoryStream())
                    using (var aggregateGraphStream = new MemoryStream())
                    using (var manifestStreamList = new DisposableCollection<Stream>())
                    using (var manifestHeaderStream = new MemoryStream())
                    using (var nifStream = new MemoryStream())
                    using (var xblockStream = new MemoryStream()) {
                        // TOOLKIT VERSION
                        GenerateToolkitVersion(toolkitVersionStream);
                        packPsarc.AddEntry("toolkit.version", toolkitVersionStream);

                        // APP ID
                        if (!platform.IsConsole) {
                            GenerateAppId(appIdStream, info.AppId, platform);
                            packPsarc.AddEntry("appid.appid", appIdStream);
                        }

                        if (platform.platform == GamePlatform.XBox360) {
                            var packageListWriter = new StreamWriter(packageListStream);
                            packageListWriter.Write(dlcName);
                            packageListWriter.Flush();
                            packageListStream.Seek(0, SeekOrigin.Begin);
                            string packageList = "PackageList.txt";
                            packageListStream.WriteTmpFile(packageList, platform);
                        }

                        // AGGREGATE GRAPH
                        var aggregateGraphFileName = String.Format("{0}_aggregategraph.nt", dlcName);
                        var aggregateGraph = new AggregateGraph2014(info, platform, DLCPackageType.Inlay);
                        aggregateGraph.Serialize(aggregateGraphStream);
                        aggregateGraphStream.Flush();
                        aggregateGraphStream.Seek(0, SeekOrigin.Begin);
                        packPsarc.AddEntry(aggregateGraphFileName, aggregateGraphStream);

                        // MANIFEST
                        var attribute = new InlayAttributes2014(info);
                        var attributeDictionary = new Dictionary<string, InlayAttributes2014> { { "Attributes", attribute } };
                        var manifest = new Manifest2014<InlayAttributes2014>(DLCPackageType.Inlay);
                        manifest.Entries.Add(attribute.PersistentID, attributeDictionary);
                        var manifestStream = new MemoryStream();
                        manifestStreamList.Add(manifestStream);
                        manifest.Serialize(manifestStream);
                        manifestStream.Seek(0, SeekOrigin.Begin);
                        var jsonPathPC = "manifests/songs_dlc_{0}/dlc_guitar_{0}.json";
                        var jsonPathConsole = "manifests/songs_dlc/dlc_guitar_{0}.json";
                        packPsarc.AddEntry(String.Format((platform.IsConsole ? jsonPathConsole : jsonPathPC), dlcName), manifestStream);

                        // MANIFEST HEADER
                        var attributeHeaderDictionary = new Dictionary<string, InlayAttributes2014> { { "Attributes", attribute } };
                        var manifestHeader = new ManifestHeader2014<InlayAttributes2014>(platform, DLCPackageType.Inlay);
                        manifestHeader.Entries.Add(attribute.PersistentID, attributeHeaderDictionary);
                        manifestHeader.Serialize(manifestHeaderStream);
                        manifestHeaderStream.Seek(0, SeekOrigin.Begin);
                        var hsanPathPC = "manifests/songs_dlc_{0}/dlc_{0}.hsan";
                        var hsonPathConsole = "manifests/songs_dlc/dlc_{0}.hson";
                        packPsarc.AddEntry(String.Format((platform.IsConsole ? hsonPathConsole : hsanPathPC), dlcName), manifestHeaderStream);

                        // XBLOCK
                        GameXblock<Entity2014> game = GameXblock<Entity2014>.Generate2014(info, platform, DLCPackageType.Inlay);
                        game.SerializeXml(xblockStream);
                        xblockStream.Flush();
                        xblockStream.Seek(0, SeekOrigin.Begin);
                        packPsarc.AddEntry(String.Format("gamexblocks/nguitars/guitar_{0}.xblock", dlcName), xblockStream);

                        // INLAY NIF
                        InlayNif nif = new InlayNif(info);
                        nif.Serialize(nifStream);
                        nifStream.Flush();
                        nifStream.Seek(0, SeekOrigin.Begin);
                        packPsarc.AddEntry(String.Format("assets/gameplay/inlay/{0}.nif", dlcName), nifStream);

                        // WRITE PACKAGE
                        packPsarc.Write(output, !platform.IsConsole);
                        output.Flush();
                        output.Seek(0, SeekOrigin.Begin);
                        output.WriteTmpFile(String.Format("{0}.psarc", dlcName), platform);
                    }
                } catch (Exception ex) {
                    throw ex;
                } finally {
                    // Dispose all objects
                    if (rsenumerableRootStream != null)
                        rsenumerableRootStream.Dispose();
                    if (rsenumerableGuitarStream != null)
                        rsenumerableGuitarStream.Dispose();
                    DeleteTmpFiles(TMPFILES_ART);
                }
            }
        }
Ejemplo n.º 57
0
        private static void PackPC(string sourcePath, string saveFileName, bool useCryptography, bool updateSng)
        {
            var bins = Directory.EnumerateFiles(sourcePath, "NamesBlock.bin", SearchOption.AllDirectories).Where(File.Exists);
            foreach (var namesBlock in bins)
            {
                File.Delete(namesBlock);
            }

            if (Path.GetExtension(saveFileName) != ".dat")
                saveFileName += ".dat";

            using (var streamCollection = new DisposableCollection<Stream>())
            using (var outputFileStream = File.Create(saveFileName))
            {
                var psarc = new PSARC.PSARC();
                foreach (var x in Directory.EnumerateFiles(sourcePath))
                {
                    var fileStream = File.OpenRead(x);
                    streamCollection.Add(fileStream);
                    psarc.AddEntry(Path.GetFileName(x), fileStream);
                }

                foreach (var directory in Directory.EnumerateDirectories(sourcePath))
                {
                    var innerPsarcStream = new MemoryStream();
                    streamCollection.Add(innerPsarcStream);
                    var directoryName = Path.GetFileName(directory);

                    // Recreate SNG
                    if (updateSng)
                        if (directory.ToLower().IndexOf("dlc_tone_") < 0)
                            UpdateSng(directory, new Platform(GamePlatform.Pc, GameVersion.RS2012));

                    PackInnerPC(innerPsarcStream, directory);
                    psarc.AddEntry(directoryName + ".psarc", innerPsarcStream);
                }
                if (useCryptography)
                {
                    using (var psarcStream = new MemoryStream())
                    {
                        psarc.Write(psarcStream, false);
                        RijndaelEncryptor.EncryptFile(psarcStream, outputFileStream, RijndaelEncryptor.DLCKey);
                        return;
                    }
                }
                psarc.Write(outputFileStream, false);
            }
        }
Ejemplo n.º 58
0
        private static void AddFilter(DisposableCollection<List<FilterBase>> filters, Func<FilterBase> filterFactory)
        {
            if (filters.Elements.Capacity < filters.Elements.Count + 1)
            {
                filters.Elements.Capacity = filters.Elements.Count + 1;
            }

            FilterBase filter = null;
            try
            {
                filter = filterFactory ();
            }
            finally
            {
                filters.Elements.Add (filter);
            }
        }