/// <summary> /// Generates an AssemblyInfo file. /// </summary> protected override void ExecuteTask() { try { StringCollection imports = new StringCollection(); foreach (NamespaceImport import in Imports) { if (import.IfDefined && !import.UnlessDefined) { imports.Add(import.Namespace); } } // ensure base directory is set, even if fileset was not initialized // from XML if (References.BaseDirectory == null) { References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // write out code to memory stream, so we can compare it later // to what is already present (if necessary) MemoryStream generatedAsmInfoStream = new MemoryStream(); using (StreamWriter writer = new StreamWriter(generatedAsmInfoStream, Encoding.Default)) { // create new instance of CodeProviderInfo for specified CodeLanguage CodeProvider codeProvider = new CodeProvider(this, Language); // only generate imports here for C#, for VB we create the // imports as part of the assembly attributes compile unit if (Language == CodeLanguage.CSharp) { // generate imports code codeProvider.GenerateImportCode(imports, writer); } // generate code for assembly attributes codeProvider.GenerateAssemblyAttributesCode(AssemblyAttributes, imports, References.FileNames, writer); // flush writer.Flush(); // check whether generated source should be persisted if (NeedsPersisting(generatedAsmInfoStream)) { using (FileStream fs = new FileStream(Output.FullName, FileMode.Create, FileAccess.Write)) { byte[] buffer = generatedAsmInfoStream.ToArray(); fs.Write(buffer, 0, buffer.Length); fs.Flush(); fs.Close(); generatedAsmInfoStream.Close(); } Log(Level.Info, ResourceUtils.GetString("String_GeneratedFile"), Output.FullName); } else { Log(Level.Verbose, ResourceUtils.GetString("String_FileUpToDate"), Output.FullName); } } } catch (Exception ex) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2004"), Output.FullName), Location, ex); } }
private async Task AddGenresToPlaylistAsync(IList <string> genres, string playlistName) { CreateNewPlaylistResult createPlaylistResult = CreateNewPlaylistResult.Success; // Default Success // If no playlist is provided, first create one. if (playlistName == null) { var responseText = ResourceUtils.GetString("Language_New_Playlist"); if (this.dialogService.ShowInputDialog( 0xea37, 16, ResourceUtils.GetString("Language_New_Playlist"), ResourceUtils.GetString("Language_Enter_Name_For_Playlist"), ResourceUtils.GetString("Language_Ok"), ResourceUtils.GetString("Language_Cancel"), ref responseText)) { playlistName = responseText; createPlaylistResult = await this.playlistService.CreateNewPlaylistAsync(new EditablePlaylistViewModel(playlistName, PlaylistType.Static)); } } // If playlist name is still null, the user clicked cancel on the previous dialog. Stop here. if (playlistName == null) { return; } // Verify if the playlist was created switch (createPlaylistResult) { case CreateNewPlaylistResult.Success: case CreateNewPlaylistResult.Duplicate: // Add items to playlist AddTracksToPlaylistResult addTracksResult = await this.playlistService.AddGenresToStaticPlaylistAsync(genres, playlistName); if (addTracksResult == AddTracksToPlaylistResult.Error) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Adding_Songs_To_Playlist").Replace("{playlistname}", "\"" + playlistName + "\""), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } break; case CreateNewPlaylistResult.Error: this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Adding_Playlist"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); break; case CreateNewPlaylistResult.Blank: this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Provide_Playlist_Name"), ResourceUtils.GetString("Language_Ok"), false, string.Empty); break; default: // Never happens break; } }
/// <summary> /// Starts the external process and captures its output. /// </summary> /// <exception cref="BuildException"> /// <para>The external process did not finish within the configured timeout.</para> /// <para>-or-</para> /// <para>The exit code of the external process indicates a failure.</para> /// </exception> protected override void ExecuteTask() { Thread outputThread = null; Thread errorThread = null; try { // Start the external process Process process = StartProcess(); if (Spawn) { _processId = process.Id; return; } outputThread = new Thread(new ThreadStart(StreamReaderThread_Output)); errorThread = new Thread(new ThreadStart(StreamReaderThread_Error)); _stdOut = process.StandardOutput; _stdError = process.StandardError; outputThread.Start(); errorThread.Start(); // Wait for the process to terminate process.WaitForExit(TimeOut); // Wait for the threads to terminate outputThread.Join(2000); errorThread.Join(2000); if (!process.HasExited) { try { process.Kill(); } catch { // ignore possible exceptions that are thrown when the // process is terminated } throw new BuildException( String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1118"), ProgramFileName, TimeOut), Location); } _exitCode = process.ExitCode; if (process.ExitCode != 0) { throw new BuildException( String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1119"), ProgramFileName, process.ExitCode), Location); } } catch (BuildException e) { if (FailOnError) { throw; } else { logger.Error("Execution Error", e); Log(Level.Error, e.Message); } } catch (Exception e) { logger.Error("Execution Error", e); throw new BuildException( string.Format(CultureInfo.InvariantCulture, "{0}: {1} had errors. Please see log4net log.", GetType().ToString(), ProgramFileName), Location, e); } finally { // ensure outputThread is always aborted if (outputThread != null && outputThread.IsAlive) { outputThread.Abort(); } // ensure errorThread is always aborted if (errorThread != null && errorThread.IsAlive) { errorThread.Abort(); } } }
private async Task ChangeStorageLocationAsync(bool performReset, bool moveCurrentNotes) { string selectedFolder = ApplicationPaths.CurrentNoteStorageLocation; if (performReset) { bool confirmPerformReset = this.dialogService.ShowConfirmationDialog( null, title: ResourceUtils.GetString("Language_Reset"), content: ResourceUtils.GetString("Language_Reset_Confirm"), okText: ResourceUtils.GetString("Language_Yes"), cancelText: ResourceUtils.GetString("Language_No")); if (confirmPerformReset) { selectedFolder = ApplicationPaths.DefaultNoteStorageLocation; } } else { var dlg = new WPFFolderBrowserDialog(); dlg.InitialDirectory = ApplicationPaths.CurrentNoteStorageLocation; if ((bool)dlg.ShowDialog()) { selectedFolder = dlg.FileName; } } // If the new folder is the same as the old folder, do nothing. if (ApplicationPaths.CurrentNoteStorageLocation.Equals(selectedFolder, StringComparison.InvariantCultureIgnoreCase)) { return; } // Close all note windows await this.noteService.CloseAllNoteWindowsAsync(500); bool isChangeStorageLocationSuccess = await this.noteService.ChangeStorageLocationAsync(selectedFolder, moveCurrentNotes); // Show error if changing storage location failed if (isChangeStorageLocationSuccess) { // Show notification if change storage location succeeded this.dialogService.ShowNotificationDialog( null, title: ResourceUtils.GetString("Language_Success"), content: ResourceUtils.GetString("Language_Change_Storage_Location_Was_Successful"), okText: ResourceUtils.GetString("Language_Ok"), showViewLogs: false); } else { // Show error if change storage location failed this.dialogService.ShowNotificationDialog( null, title: ResourceUtils.GetString("Language_Error"), content: ResourceUtils.GetString("Language_Error_Change_Storage_Location_Error"), okText: ResourceUtils.GetString("Language_Ok"), showViewLogs: true); } }
private void WriteItems() { var freeItems = new List <Item>(); if (_settings.LogicMode == LogicMode.Vanilla) { freeItems.Add(Item.FairyMagic); freeItems.Add(Item.MaskDeku); freeItems.Add(Item.SongHealing); freeItems.Add(Item.StartingSword); freeItems.Add(Item.StartingShield); freeItems.Add(Item.StartingHeartContainer1); freeItems.Add(Item.StartingHeartContainer2); if (_settings.ShortenCutscenes) { //giants cs were removed freeItems.Add(Item.SongOath); } WriteFreeItems(freeItems.ToArray()); return; } //write free item (start item default = Deku Mask) freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.MaskDeku).Item); freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.SongHealing).Item); freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingSword).Item); freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingShield).Item); freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingHeartContainer1).Item); freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingHeartContainer2).Item); WriteFreeItems(freeItems.ToArray()); //write everything else ItemSwapUtils.ReplaceGetItemTable(Values.ModsDirectory); ItemSwapUtils.InitItems(); if (_settings.FixEponaSword) { ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-epona"); } if (_settings.PreventDowngrades) { ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-downgrades"); } if (_settings.AddCowMilk) { ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-cow-bottle-check"); } var newMessages = new List <MessageEntry>(); foreach (var item in _randomized.ItemList) { // Unused item if (item.NewLocation == null) { continue; } if (ItemUtils.IsBottleCatchContent(item.Item)) { ItemSwapUtils.WriteNewBottle(item.NewLocation.Value, item.Item); } else { ChestTypeAttribute.ChestType?overrideChestType = null; if ((item.Item.Name().Contains("Bombchu") || item.Item.Name().Contains("Shield")) && _randomized.Logic.Any(il => il.RequiredItemIds?.Contains(item.ID) == true || il.ConditionalItemIds?.Any(c => c.Contains(item.ID)) == true)) { overrideChestType = ChestTypeAttribute.ChestType.LargeGold; } ItemSwapUtils.WriteNewItem(item.NewLocation.Value, item.Item, newMessages, _settings.UpdateShopAppearance, _settings.PreventDowngrades, _settings.UpdateChests && item.IsRandomized, overrideChestType, _settings.CustomStartingItemList.Contains(item.Item)); } } var copyRupeesRegex = new Regex(": [0-9]+ Rupees"); foreach (var newMessage in newMessages) { var oldMessage = _messageTable.GetMessage(newMessage.Id); if (oldMessage != null) { var cost = copyRupeesRegex.Match(oldMessage.Message).Value; newMessage.Message = copyRupeesRegex.Replace(newMessage.Message, cost); } } if (_settings.UpdateShopAppearance) { // update tingle shops foreach (var messageShopText in Enum.GetValues(typeof(MessageShopText)).Cast <MessageShopText>()) { var messageShop = messageShopText.GetAttribute <MessageShopAttribute>(); var item1 = _randomized.ItemList.First(io => io.NewLocation == messageShop.Items[0]).Item; var item2 = _randomized.ItemList.First(io => io.NewLocation == messageShop.Items[1]).Item; newMessages.Add(new MessageEntry { Id = (ushort)messageShopText, Header = null, Message = string.Format(messageShop.MessageFormat, item1.Name() + " ", messageShop.Prices[0], item2.Name() + " ", messageShop.Prices[1]) }); } // update business scrub var businessScrubItem = _randomized.ItemList.First(io => io.NewLocation == Item.HeartPieceTerminaBusinessScrub).Item; newMessages.Add(new MessageEntry { Id = 0x1631, Header = null, Message = $"\x1E\x3A\xD2Please! I'll sell you {MessageUtils.GetArticle(businessScrubItem)}\u0001{businessScrubItem.Name()}\u0000 if you just keep this place a secret...\x19\xBF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x1632, Header = null, Message = $"\u0006150 Rupees\u0000 for{MessageUtils.GetPronounOrAmount(businessScrubItem).ToLower()}!\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(businessScrubItem)}\u0011No thanks\u00BF" }); newMessages.Add(new MessageEntry { Id = 0x1634, Header = null, Message = $"What about{MessageUtils.GetPronounOrAmount(businessScrubItem, "").ToLower()} for \u0006100 Rupees\u0000?\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(businessScrubItem)}\u0011No thanks\u00BF" }); // update biggest bomb bag purchase var biggestBombBagItem = _randomized.ItemList.First(io => io.NewLocation == Item.UpgradeBiggestBombBag).Item; newMessages.Add(new MessageEntry { Id = 0x15F5, Header = null, Message = $"I sell {MessageUtils.GetArticle(biggestBombBagItem)}\u0001{MessageUtils.GetAlternateName(biggestBombBagItem)}\u0000, but I'm focusing my marketing efforts on \u0001Gorons\u0000.".Wrap(35, "\u0011").EndTextbox() + "What I'd really like to do is go back home and do business where I'm surrounded by trees and grass.\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x15FF, Header = null, Message = $"\x1E\x39\x8CRight now, I've got a \u0001special\u0011\u0000offer just for you.\u0019\u00BF" }); newMessages.Add(new MessageEntry { Id = 0x1600, Header = null, Message = $"\x1E\x38\x81I'll give you {MessageUtils.GetArticle(biggestBombBagItem, "my ")}\u0001{biggestBombBagItem.Name()}\u0000, regularly priced at \u00061000 Rupees\u0000...".Wrap(35, "\u0011").EndTextbox() + "In return, you'll give me just\u0011\u0006200 Rupees\u0000!\u0019\u00BF" }); newMessages.Add(new MessageEntry { Id = 0x1606, Header = null, Message = $"\x1E\x38\x81I'll give you {MessageUtils.GetArticle(biggestBombBagItem, "my ")}\u0001{biggestBombBagItem.Name()}\u0000, regularly priced at \u00061000 Rupees\u0000, for just \u0006200 Rupees\u0000!\u0019\u00BF".Wrap(35, "\u0011") }); // update swamp scrub purchase var magicBeanItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemBusinessScrubMagicBean).Item; newMessages.Add(new MessageEntry { Id = 0x15E1, Header = null, Message = $"\x1E\x39\xA7I'm selling {MessageUtils.GetArticle(magicBeanItem)}\u0001{MessageUtils.GetAlternateName(magicBeanItem)}\u0000 to Deku Scrubs, but I'd really like to leave my hometown.".Wrap(35, "\u0011").EndTextbox() + "I'm hoping to find some success in a livelier place!\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x15E9, Header = null, Message = $"\x1E\x3A\u00D2Do you know what {MessageUtils.GetArticle(magicBeanItem)}\u0001{MessageUtils.GetAlternateName(magicBeanItem)}\u0000 {MessageUtils.GetVerb(magicBeanItem)}, sir?".Wrap(35, "\u0011") + $"\u0011I'll sell you{MessageUtils.GetPronounOrAmount(magicBeanItem).ToLower()} for \u000610 Rupees\u0000.\u0019\u00BF" }); // update ocean scrub purchase var greenPotionItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemBusinessScrubGreenPotion).Item; newMessages.Add(new MessageEntry { Id = 0x1608, Header = null, Message = $"\x1E\x39\xA7I'm selling {MessageUtils.GetArticle(greenPotionItem)}\u0001{MessageUtils.GetAlternateName(greenPotionItem)}\u0000, but I'm focusing my marketing efforts on Zoras.".Wrap(35, "\u0011").EndTextbox() + "Actually, I'd like to do business someplace where it's cooler and the air is clean.\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x1612, Header = null, Message = $"\x1E\x39\x8CI'll sell you {MessageUtils.GetArticle(greenPotionItem)}\u0001{greenPotionItem.Name()}\u0000 for \u000640 Rupees\u0000!\u00E0\u00BF".Wrap(35, "\u0011") }); // update canyon scrub purchase var bluePotionItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemBusinessScrubBluePotion).Item; newMessages.Add(new MessageEntry { Id = 0x161C, Header = null, Message = $"\x1E\x39\xA7I'm here to sell {MessageUtils.GetArticle(bluePotionItem)}\u0001{MessageUtils.GetAlternateName(bluePotionItem)}\u0000.".Wrap(35, "\u0011").EndTextbox() + "Actually, I want to do business in the sea breeze while listening to the sound of the waves.\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x1626, Header = null, Message = $"\x1E\x3A\u00D2Don't you need {MessageUtils.GetArticle(bluePotionItem)}\u0001{MessageUtils.GetAlternateName(bluePotionItem)}\u0000? I'll sell you{MessageUtils.GetPronounOrAmount(bluePotionItem).ToLower()} for \u0006100 Rupees\u0000.\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x15EA, Header = null, Message = $"Do we have a deal?\u0011 \u0011\u0002\u00C2Yes\u0011No\u00BF" }); // update gorman bros milk purchase var gormanBrosMilkItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemGormanBrosMilk).Item; newMessages.Add(new MessageEntry { Id = 0x3463, Header = null, Message = $"Won'tcha buy {MessageUtils.GetArticle(gormanBrosMilkItem)}\u0001{MessageUtils.GetAlternateName(gormanBrosMilkItem)}\u0000?\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x3466, Header = null, Message = $"\u000650 Rupees\u0000 will do ya for{MessageUtils.GetPronounOrAmount(gormanBrosMilkItem).ToLower()}.\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(gormanBrosMilkItem)}\u0011No thanks\u00BF" }); newMessages.Add(new MessageEntry { Id = 0x346B, Header = null, Message = $"Buyin' {MessageUtils.GetArticle(gormanBrosMilkItem)}\u0001{MessageUtils.GetAlternateName(gormanBrosMilkItem)}\u0000?\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x348F, Header = null, Message = $"Seems like we're the only ones who have {MessageUtils.GetArticle(gormanBrosMilkItem)}\u0001{MessageUtils.GetAlternateName(gormanBrosMilkItem)}\u0000. Hyuh, hyuh. If you like, I'll sell you{MessageUtils.GetPronounOrAmount(gormanBrosMilkItem).ToLower()}.\u0019\u00BF".Wrap(35, "\u0011") }); newMessages.Add(new MessageEntry { Id = 0x3490, Header = null, Message = $"\u000650 Rupees\u0000 will do you for{MessageUtils.GetPronounOrAmount(gormanBrosMilkItem).ToLower()}!\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(gormanBrosMilkItem)}\u0011No thanks\u00BF" }); // update lottery message var lotteryItem = _randomized.ItemList.First(io => io.NewLocation == Item.MundaneItemLotteryPurpleRupee).Item; newMessages.Add(new MessageEntry { Id = 0x2B5C, Header = null, Message = $"Would you like the chance to buy your dreams for \u000610 Rupees\u0000?".Wrap(35, "\u0011").EndTextbox() + $"Pick any three numbers, and if those are picked, you'll win {MessageUtils.GetArticle(lotteryItem)}\u0001{lotteryItem.Name()}\u0000. It's only for the \u0001first\u0000 person!\u0019\u00BF".Wrap(35, "\u0011") }); } // replace "Razor Sword is now blunt" message with get-item message for Kokiri Sword. newMessages.Add(new MessageEntry { Id = 0xF9, Header = new byte[11] { 0x06, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, Message = $"You got the \x01Kokiri Sword\x00!\u0011This is a hidden treasure of\u0011the Kokiri, but you can borrow it\u0011for a while.\u00BF", }); // replace Magic Power message newMessages.Add(new MessageEntry { Id = 0xC8, Header = null, Message = $"\u0017You've been granted \u0002Magic Power\u0000!\u0018\u0011Replenish it with \u0001Magic Jars\u0000\u0011and \u0001Potions\u0000.\u00BF", }); // update Bank Reward messages newMessages.Add(new MessageEntry { Id = 0x45C, Header = null, Message = "\u0017What's this? You've already saved\u0011up \u0001500 Rupees\u0000!?!\u0018\u0011\u0013\u0012Well, little guy, here's your special\u0011gift. Take it!\u00E0\u00BF", }); newMessages.Add(new MessageEntry { Id = 0x45D, Header = null, Message = "\u0017What's this? You've already saved\u0011up \u00011000 Rupees\u0000?!\u0018\u0011\u0013\u0012Well, little guy, I can't take any\u0011more deposits. Sorry, but this is\u0011all I can give you.\u00E0\u00BF", }); if (_settings.AddSkulltulaTokens) { ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-skulltula-tokens"); newMessages.Add(new MessageEntry { Id = 0x51, Header = new byte[11] { 0x02, 0x00, 0x52, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, Message = $"\u0017You got an \u0005Ocean Gold Skulltula\u0011Spirit\0!\u0018\u001F\u0000\u0010 This is your \u0001\u000D\u0000 one!\u00BF", }); newMessages.Add(new MessageEntry { Id = 0x52, Header = new byte[11] { 0x02, 0x00, 0x52, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, Message = $"\u0017You got a \u0006Swamp Gold Skulltula\u0011Spirit\0!\u0018\u001F\u0000\u0010 This is your \u0001\u000D\u0000 one!\u00BF", }); } if (_settings.AddStrayFairies) { ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-fairies"); } var dungeonItemMessageIds = new byte[] { 0x3C, 0x3D, 0x3E, 0x3F, 0x74, 0x40, 0x4D, 0x4E, 0x53, 0x75, 0x54, 0x61, 0x64, 0x6E, 0x76, 0x70, 0x71, 0x72, 0x73, 0x77, }; var dungeonNames = new string[] { "\u0006Woodfall Temple\u0000", "\u0002Snowhead Temple\u0000", "\u0005Great Bay Temple\u0000", "\u0004Stone Tower Temple\u0000" }; var dungeonItemMessages = new string[] { "\u0017You found a \u0001Small Key\u0000 for\u0011{0}!\u0018\u00BF", "\u0017You found the \u0001Boss Key\u0000 for\u0011{0}!\u0018\u00BF", "\u0017You found the \u0001Dungeon Map\u0000 for\u0011{0}!\u0018\u00BF", "\u0017You found the \u0001Compass\u0000 for\u0011{0}!\u0018\u00BF", "\u0017You found a \u0001Stray Fairy\u0000 from\u0011{0}!\u0018\u001F\u0000\u0010\u0011This is your \u0001\u000C\u0000 one!\u00BF", }; var dungeonItemIcons = new byte[] { 0x3C, 0x3D, 0x3E, 0x3F, 0xFE }; for (var i = 0; i < dungeonItemMessageIds.Length; i++) { var messageId = dungeonItemMessageIds[i]; var icon = dungeonItemIcons[i % 5]; var dungeonName = dungeonNames[i / 5]; var message = string.Format(dungeonItemMessages[i % 5], dungeonName); newMessages.Add(new MessageEntry { Id = messageId, Header = new byte[11] { 0x02, 0x00, icon, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, Message = message }); } _messageTable.UpdateMessages(newMessages); if (_settings.AddShopItems) { ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-shop-checks"); } }
protected async Task PlaySelectedAsync() { var result = await this.playbackService.PlaySelectedAsync(this.selectedTracks); if (!result) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Playing_Selected_Songs"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } }
private async Task SavePresetToFileAsync() { var showSaveDialog = true; var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = string.Empty; dlg.DefaultExt = FileFormats.DEQ; dlg.Filter = string.Concat(ResourceUtils.GetString("Language_Equalizer_Presets"), " (", FileFormats.DEQ, ")|*", FileFormats.DEQ); dlg.InitialDirectory = System.IO.Path.Combine(WindowsPaths.AppData(), ProductInformation.ApplicationName, ApplicationPaths.EqualizerFolder); while (showSaveDialog) { if ((bool)dlg.ShowDialog()) { int existingCount = this.presets.Select((p) => p).Where((p) => p.Name.ToLower() == System.IO.Path.GetFileNameWithoutExtension(dlg.FileName).ToLower() & !p.IsRemovable).Count(); if (existingCount > 0) { dlg.FileName = string.Empty; this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Preset_Already_Taken"), ResourceUtils.GetString("Language_Ok"), false, string.Empty); } else { showSaveDialog = false; try { await Task.Run(() => { System.IO.File.WriteAllLines(dlg.FileName, this.SelectedPreset.ToValueString().Split(';')); }); } catch (Exception ex) { LogClient.Error("An error occurred while saving preset to file '{0}'. Exception: {1}", dlg.FileName, ex.Message); this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_While_Saving_Preset"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } SettingsClient.Set <string>("Equalizer", "SelectedPreset", System.IO.Path.GetFileNameWithoutExtension(dlg.FileName)); this.InitializeAsync(); } } else { showSaveDialog = false; // Makes sure the dialog doesn't re-appear when pressing cancel } } }
public EditAlbumViewModel(Album album, IMetadataService metadataService, IDialogService dialogService) { this.Album = album; this.metadataService = metadataService; this.dialogService = dialogService; this.artwork = new MetadataArtworkValue(); this.LoadedCommand = new DelegateCommand(async() => await this.GetAlbumArtworkAsync()); this.ChangeArtworkCommand = new DelegateCommand(async() => { if (!await OpenFileUtils.OpenImageFileAsync(new Action <string, byte[]>(this.UpdateArtwork))) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetStringResource("Language_Error"), ResourceUtils.GetStringResource("Language_Error_Changing_Image"), ResourceUtils.GetStringResource("Language_Ok"), true, ResourceUtils.GetStringResource("Language_Log_File")); } }); this.RemoveArtworkCommand = new DelegateCommand(() => this.UpdateArtwork(string.Empty, null)); }
/// <summary> /// Writes the compiler options to the specified <see cref="TextWriter" />. /// </summary> /// <param name="writer"><see cref="TextWriter" /> to which the compiler options should be written.</param> protected override void WriteOptions(TextWriter writer) { // causes the compiler to specify the full path of the file in which // an error was found WriteOption(writer, "fullpaths"); // the base address for the DLL if (BaseAddress != null) { WriteOption(writer, "baseaddress", BaseAddress); } // If mcs is the compiler and the specified McsSdk version is specified, append the new // -sdk: option to the argument list. if (PlatformHelper.IsMono) { if (ExeName.Equals("mcs", StringComparison.InvariantCultureIgnoreCase) && _mcsSdk > 0) { WriteOption(writer, "sdk", _mcsSdk.ToString()); } } // XML documentation if (DocFile != null) { if (SupportsDocGeneration) { WriteOption(writer, "doc", DocFile.FullName); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportXmlDoc"), Project.TargetFramework.Description); } } // langversion if (LangVersion != null) { if (SupportsLangVersion) { WriteOption(writer, "langversion", LangVersion); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportLangVersion"), Project.TargetFramework.Description); } } // platform if (Platform != null) { if (SupportsPlatform) { WriteOption(writer, "platform", Platform); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportPlatform"), Project.TargetFramework.Description); } } // win32res if (Win32Res != null) { WriteOption(writer, "win32res", Win32Res.FullName); } // handle debug builds. switch (DebugOutput) { case DebugOutput.None: break; case DebugOutput.Enable: WriteOption(writer, "debug"); WriteOption(writer, "define", "DEBUG"); WriteOption(writer, "define", "TRACE"); break; case DebugOutput.Full: WriteOption(writer, "debug"); break; case DebugOutput.PdbOnly: WriteOption(writer, "debug", "pdbonly"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2011"), DebugOutput), Location); } if (FileAlign > 0) { WriteOption(writer, "filealign", FileAlign.ToString(CultureInfo.InvariantCulture)); } if (NoStdLib) { WriteOption(writer, "nostdlib"); } if (Checked) { WriteOption(writer, "checked"); } if (Unsafe) { WriteOption(writer, "unsafe"); } if (Optimize) { WriteOption(writer, "optimize"); } if (WarningLevel != null) { WriteOption(writer, "warn", WarningLevel); } if (Codepage != null) { WriteOption(writer, "codepage", Codepage); } if (NoConfig && !Arguments.Contains("/noconfig")) { Arguments.Add(new Argument("/noconfig")); } }
protected bool CheckAllSelectedFilesExist(List <string> paths) { bool allSelectedTracksExist = true; foreach (string path in paths) { if (!System.IO.File.Exists(path)) { allSelectedTracksExist = false; break; } } if (!allSelectedTracksExist) { string message = ResourceUtils.GetString("Language_Song_Cannot_Be_Found_Refresh_Collection"); if (paths.Count > 1) { message = ResourceUtils.GetString("Language_Songs_Cannot_Be_Found_Refresh_Collection"); } if (this.dialogService.ShowConfirmation(0xe11b, 16, ResourceUtils.GetString("Language_Refresh"), message, ResourceUtils.GetString("Language_Yes"), ResourceUtils.GetString("Language_No"))) { this.indexingService.RefreshCollectionImmediatelyAsync(); } } return(allSelectedTracksExist); }
public async Task CanCreateBatchAccountWithApplication() { using (var context = FluentMockContext.Start(this.GetType().FullName)) { try { var applicationId = "myApplication"; var applicationDisplayName = "displayName"; var allowUpdates = true; var batchManager = TestHelper.CreateBatchManager(); // Create var batchAccount = await batchManager.BatchAccounts .Define(batchAccountName) .WithRegion(Region.AsiaSouthEast) .WithNewResourceGroup(rgName) .DefineNewApplication(applicationId) .WithDisplayName(applicationDisplayName) .WithAllowUpdates(allowUpdates) .Attach() .WithNewStorageAccount(storageAccountName) .CreateAsync(); Assert.Equal(rgName, batchAccount.ResourceGroupName); Assert.NotNull(batchAccount.AutoStorage); Assert.Equal(ResourceUtils.NameFromResourceId(batchAccount.AutoStorage.StorageAccountId), storageAccountName); // List var accounts = batchManager.BatchAccounts.ListByResourceGroup(rgName); Assert.Contains(accounts, account => StringComparer.OrdinalIgnoreCase.Equals(account.Name, batchAccountName)); // Get batchAccount = batchManager.BatchAccounts.GetByResourceGroup(rgName, batchAccountName); Assert.NotNull(batchAccount); Assert.True(batchAccount.Applications.ContainsKey(applicationId)); var application = batchAccount.Applications[applicationId]; Assert.NotNull(application); Assert.Equal(application.DisplayName, applicationDisplayName); Assert.Equal(application.UpdatesAllowed, allowUpdates); try { await batchManager.BatchAccounts.DeleteByResourceGroupAsync(batchAccount.ResourceGroupName, batchAccountName); } catch { } var batchAccounts = batchManager.BatchAccounts.ListByResourceGroup(rgName); Assert.Empty(batchAccounts); } finally { try { var resourceManager = TestHelper.CreateResourceManager(); resourceManager.ResourceGroups.DeleteByName(rgName); } catch { } } } }
protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (InFiles.BaseDirectory == null) { InFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } StringCollection srcFiles = null; if (SrcFile != null) { srcFiles = new StringCollection(); srcFiles.Add(SrcFile.FullName); } else if (InFiles.FileNames.Count > 0) { if (OutputFile != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1148")), Location); } srcFiles = InFiles.FileNames; } if (srcFiles == null || srcFiles.Count == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1147")), Location); } if (XsltFile.IsFile) { FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); if (!fileInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), fileInfo.FullName), Location); } } else { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(XsltFile); if (Proxy != null) { request.Proxy = Proxy.GetWebProxy(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), XsltFile), Location); } } foreach (string srcFile in srcFiles) { string destFile = null; if (OutputFile != null) { destFile = OutputFile.FullName; } if (StringUtils.IsNullOrEmpty(destFile)) { // TODO: use System.IO.Path (gs) // append extension if necessary string ext = Extension.IndexOf(".") > -1 ? Extension : "." + Extension; int extPos = srcFile.LastIndexOf('.'); if (extPos == -1) { destFile = srcFile + ext; } else { destFile = srcFile.Substring(0, extPos) + ext; } destFile = Path.GetFileName(destFile); } FileInfo srcInfo = new FileInfo(srcFile); FileInfo destInfo = new FileInfo(Path.GetFullPath(Path.Combine( DestDir.FullName, destFile))); if (!srcInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1150"), srcInfo.FullName), Location); } bool destOutdated = !destInfo.Exists || srcInfo.LastWriteTime > destInfo.LastWriteTime; if (!destOutdated && XsltFile.IsFile) { FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); destOutdated |= fileInfo.LastWriteTime > destInfo.LastWriteTime; } if (destOutdated) { XmlReader xmlReader = null; XmlReader xslReader = null; TextWriter writer = null; try { // store current directory string originalCurrentDirectory = Directory.GetCurrentDirectory(); // initialize XPath document holding input XML XPathDocument xml = null; try { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly Directory.SetCurrentDirectory(srcInfo.DirectoryName); // load the xml that needs to be transformed Log(Level.Verbose, "Loading XML file '{0}'.", srcInfo.FullName); xmlReader = CreateXmlReader(new Uri(srcInfo.FullName)); xml = new XPathDocument(xmlReader); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } // initialize xslt parameters XsltArgumentList xsltArgs = new XsltArgumentList(); // set the xslt parameters foreach (XsltParameter parameter in Parameters) { if (IfDefined && !UnlessDefined) { xsltArgs.AddParam(parameter.ParameterName, parameter.NamespaceUri, parameter.Value); } } // create extension objects foreach (XsltExtensionObject extensionObject in ExtensionObjects) { if (extensionObject.IfDefined && !extensionObject.UnlessDefined) { object extensionInstance = extensionObject.CreateInstance(); xsltArgs.AddExtensionObject(extensionObject.NamespaceUri, extensionInstance); } } // initialize XSLT transform XslTransform xslt = new XslTransform(); try { if (XsltFile.IsFile) { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); Directory.SetCurrentDirectory(fileInfo.DirectoryName); } // load the stylesheet Log(Level.Verbose, "Loading stylesheet '{0}'.", XsltFile); xslReader = CreateXmlReader(XsltFile); xslt.Load(xslReader); // create writer for the destination xml writer = CreateWriter(destInfo.FullName); // do the actual transformation Log(Level.Info, "Processing '{0}' to '{1}'.", srcInfo.FullName, destInfo.FullName); xslt.Transform(xml, xsltArgs, writer); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1151"), srcInfo.FullName, XsltFile), Location, ex); } finally { // ensure file handles are closed if (xmlReader != null) { xmlReader.Close(); } if (xslReader != null) { xslReader.Close(); } if (writer != null) { writer.Close(); } } } } }
/// <summary> /// Represents the method that will be called to update the current /// step's precent complete value. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="ProgressArgs" /> that contains the event data.</param> private void OnDocBuildingProgress(object sender, ProgressArgs e) { Log(Level.Verbose, e.Progress + ResourceUtils.GetString("String_PercentageComplete")); }
/// <summary> /// Generates an NDoc project and builds the documentation. /// </summary> protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Assemblies.BaseDirectory == null) { Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Summaries.BaseDirectory == null) { Summaries.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (ReferencePaths.BaseDirectory == null) { ReferencePaths.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // Make sure there is at least one included assembly. This can't // be done in the InitializeTask() method because the files might // not have been built at startup time. if (Assemblies.FileNames.Count == 0) { throw new BuildException(ResourceUtils.GetString("NA2020"), Location); } // create NDoc Project NDoc.Core.Project project = null; try { project = new NDoc.Core.Project(); } catch (Exception ex) { throw new BuildException(ResourceUtils.GetString("NA2021"), Location, ex); } // set-up probe path, meaning list of directories where NDoc searches // for documenters // by default, NDoc scans the startup path of the app, so we do not // need to add this explicitly string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (privateBinPath != null) { // have NDoc also probe for documenters in the privatebinpath foreach (string relativePath in privateBinPath.Split(Path.PathSeparator)) { project.AppendProbePath(Path.Combine( AppDomain.CurrentDomain.BaseDirectory, relativePath)); } } // check for valid documenters (any other validation can be done by NDoc itself at project load time) foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } string documenterName = node.Attributes["name"].Value; CheckAndGetDocumenter(project, documenterName); } // write documenter project settings to temp file string projectFileName = Path.GetTempFileName(); Log(Level.Verbose, ResourceUtils.GetString("String_WritingProjectSettings"), projectFileName); XmlTextWriter writer = new XmlTextWriter(projectFileName, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("project"); // write assemblies section writer.WriteStartElement("assemblies"); foreach (string assemblyPath in Assemblies.FileNames) { string docPath = Path.ChangeExtension(assemblyPath, ".xml"); writer.WriteStartElement("assembly"); writer.WriteAttributeString("location", assemblyPath); if (File.Exists(docPath)) { writer.WriteAttributeString("documentation", docPath); } writer.WriteEndElement(); } writer.WriteEndElement(); // write summaries section StringBuilder sb = new StringBuilder(); foreach (string summaryPath in Summaries.FileNames) { // write out the namespace summary nodes try { XmlTextReader tr = new XmlTextReader(summaryPath); tr.MoveToContent(); // skip XmlDeclaration and Processing Instructions sb.Append(tr.ReadOuterXml()); tr.Close(); } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2022"), summaryPath), Location, ex); } } writer.WriteRaw(sb.ToString()); // write out the documenters section writer.WriteStartElement("documenters"); foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } writer.WriteRaw(node.OuterXml); } writer.WriteEndElement(); // end project element writer.WriteEndElement(); writer.Close(); try { // read NDoc project file Log(Level.Verbose, ResourceUtils.GetString("String_NDocProjectFile"), Path.GetFullPath(projectFileName)); project.Read(projectFileName); // add additional directories to search for referenced assemblies if (ReferencePaths.DirectoryNames.Count > 0) { foreach (string directory in ReferencePaths.DirectoryNames) { project.ReferencePaths.Add(new ReferencePath(directory)); } } foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } string documenterName = node.Attributes["name"].Value; IDocumenter documenter = CheckAndGetDocumenter(project, documenterName); // hook up events for feedback during the build documenter.DocBuildingStep += new DocBuildingEventHandler(OnDocBuildingStep); documenter.DocBuildingProgress += new DocBuildingEventHandler(OnDocBuildingProgress); // build documentation documenter.Build(project); } } catch (Exception ex) { throw new BuildException(ResourceUtils.GetString("NA2023"), Location, ex); } }
void ResourceUtils_OnUITypeEditorEditValue(ResourceUtils.ResourceUITypeEditorEditValueEventHandler e) { ResourceType resourceType = ResourceTypeManager.Instance.GetByName(e.ResourceTypeName); if (resourceType == null) Log.Fatal("Resource type not defined \"{0}\"", e.ResourceTypeName); ChooseResourceForm dialog = new ChooseResourceForm(resourceType, true, e.ShouldAddDelegate, e.ResourceName,true); if (dialog.ShowDialog() == DialogResult.OK) { e.ResourceName = dialog.FilePath; e.Modified = true; } }
/// <summary> /// Writes the compiler options to the specified <see cref="TextWriter" />. /// </summary> /// <param name="writer"><see cref="TextWriter" /> to which the compiler options should be written.</param> protected override void WriteOptions(TextWriter writer) { // the base address for the DLL if (BaseAddress != null) { WriteOption(writer, "baseaddress", BaseAddress); } // XML documentation if (DocFile != null) { if (SupportsDocGeneration) { WriteOption(writer, "doc", DocFile.FullName); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportXmlDoc"), Project.TargetFramework.Description); } } if (NoStdLib) { if (SupportsNoStdLib) { WriteOption(writer, "nostdlib"); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportNoStdLib"), Project.TargetFramework.Description); } } // platform if (Platform != null) { if (SupportsPlatform) { WriteOption(writer, "platform", Platform); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportPlatform"), Project.TargetFramework.Description); } } // win32res if (Win32Res != null) { WriteOption(writer, "win32resource", Win32Res.FullName); } // handle debug builds. switch (DebugOutput) { case DebugOutput.None: break; case DebugOutput.Enable: WriteOption(writer, "debug"); WriteOption(writer, "define", "DEBUG=True"); WriteOption(writer, "define", "TRACE=True"); break; case DebugOutput.Full: WriteOption(writer, "debug"); break; case DebugOutput.PdbOnly: WriteOption(writer, "debug", "pdbonly"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2011"), DebugOutput), Location); } string imports = Imports.ToString(); if (!StringUtils.IsNullOrEmpty(imports)) { WriteOption(writer, "imports", imports); } if (OptionCompare != null && OptionCompare.ToUpper(CultureInfo.InvariantCulture) != "FALSE") { WriteOption(writer, "optioncompare", OptionCompare); } if (OptionExplicit) { WriteOption(writer, "optionexplicit"); } if (OptionStrict) { WriteOption(writer, "optionstrict"); } if (RemoveIntChecks) { WriteOption(writer, "removeintchecks"); } if (OptionOptimize) { WriteOption(writer, "optimize"); } if (RootNamespace != null) { WriteOption(writer, "rootnamespace", RootNamespace); } if (Project.TargetFramework.Family == "netcf") { WriteOption(writer, "netcf"); WriteOption(writer, "sdkpath", Project.TargetFramework. FrameworkAssemblyDirectory.FullName); } }
protected async Task RemoveTracksFromDiskAsync(IList <TrackViewModel> selectedTracks) { string title = ResourceUtils.GetString("Language_Remove_From_Disk"); string body = ResourceUtils.GetString("Language_Are_You_Sure_To_Remove_Song_From_Disk"); if (selectedTracks != null && selectedTracks.Count > 1) { body = ResourceUtils.GetString("Language_Are_You_Sure_To_Remove_Songs_From_Disk"); } if (this.dialogService.ShowConfirmation(0xe11b, 16, title, body, ResourceUtils.GetString("Language_Yes"), ResourceUtils.GetString("Language_No"))) { RemoveTracksResult result = await this.collectionService.RemoveTracksFromDiskAsync(selectedTracks); if (result == RemoveTracksResult.Error) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Removing_Songs_From_Disk"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } else { await this.playbackService.DequeueAsync(selectedTracks); } } }
/// <summary> /// Creates a new instance of the <see cref="NAntSchemaGenerator" /> /// class. /// </summary> /// <param name="tasks">Tasks for which a schema should be generated.</param> /// <param name="dataTypes">Data Types for which a schema should be generated.</param> /// <param name="targetNS">The namespace to use. /// <example> http://tempuri.org/nant.xsd </example> /// </param> public NAntSchemaGenerator(Type[] tasks, Type[] dataTypes, string targetNS) { //setup namespace stuff if (targetNS != null) { _nantSchema.TargetNamespace = targetNS; _nantSchema.Namespaces.Add("nant", _nantSchema.TargetNamespace); } // add XSD namespace so that all xsd elements are prefix'd _nantSchema.Namespaces.Add("xs", XmlSchema.Namespace); _nantSchema.ElementFormDefault = XmlSchemaForm.Qualified; // initialize stuff _nantComplexTypes = new HybridDictionary(tasks.Length + dataTypes.Length); XmlSchemaAnnotation schemaAnnotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation schemaDocumentation = new XmlSchemaDocumentation(); string doc = String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_SchemaGenerated"), DateTime.Now); schemaDocumentation.Markup = TextToNodeArray(doc); schemaAnnotation.Items.Add(schemaDocumentation); _nantSchema.Items.Add(schemaAnnotation); // create temp list of taskcontainer Complex Types ArrayList taskContainerComplexTypes = new ArrayList(4); XmlSchemaComplexType containerCT = FindOrCreateComplexType(typeof(TaskContainer)); if (containerCT.Particle == null) { // just create empty sequence to which elements will // be added later containerCT.Particle = CreateXsdSequence(0, Decimal.MaxValue); } taskContainerComplexTypes.Add(containerCT); // create temp list of task Complex Types ArrayList dataTypeComplexTypes = new ArrayList(dataTypes.Length); foreach (Type t in dataTypes) { dataTypeComplexTypes.Add(FindOrCreateComplexType(t)); } foreach (Type t in tasks) { XmlSchemaComplexType taskCT = FindOrCreateComplexType(t); // allow any tasks... if (t.IsSubclassOf(typeof(TaskContainer))) { taskContainerComplexTypes.Add(taskCT); } } Compile(); // update the taskcontainerCTs to allow any other task and the // list of tasks generated foreach (XmlSchemaComplexType ct in taskContainerComplexTypes) { XmlSchemaSequence seq = ct.Particle as XmlSchemaSequence; if (seq != null) { seq.Items.Add(CreateTaskListComplexType(tasks).Particle); } else { logger.Error("Unable to fixup complextype with children. Particle is not XmlSchemaSequence"); } } Compile(); // create target ComplexType _targetCT = CreateTaskListComplexType(tasks, dataTypes, false); _targetCT.Name = "Target"; // name attribute _targetCT.Attributes.Add(CreateXsdAttribute("name", true)); // depends attribute _targetCT.Attributes.Add(CreateXsdAttribute("depends", false)); // description attribute _targetCT.Attributes.Add(CreateXsdAttribute("description", false)); // if attribute _targetCT.Attributes.Add(CreateXsdAttribute("if", false)); // unless attribute _targetCT.Attributes.Add(CreateXsdAttribute("unless", false)); _nantSchema.Items.Add(_targetCT); Compile(); // Generate project Element and ComplexType XmlSchemaElement projectElement = new XmlSchemaElement(); projectElement.Name = "project"; XmlSchemaComplexType projectCT = CreateTaskListComplexType(tasks, dataTypes, true); projectElement.SchemaType = projectCT; //name attribute projectCT.Attributes.Add(CreateXsdAttribute("name", true)); //default attribute projectCT.Attributes.Add(CreateXsdAttribute("default", false)); //basedir attribute projectCT.Attributes.Add(CreateXsdAttribute("basedir", false)); _nantSchema.Items.Add(projectElement); Compile(); }
protected async Task AddTracksToNowPlayingAsync() { IList <TrackViewModel> selectedTracks = this.SelectedTracks; EnqueueResult result = await this.playbackService.AddToQueueAsync(selectedTracks); if (!result.IsSuccess) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Adding_Songs_To_Now_Playing"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } }
protected XmlSchemaComplexType FindOrCreateComplexType(Type t) { XmlSchemaComplexType ct; string typeId = GenerateIDFromType(t); ct = FindComplexTypeByID(typeId); if (ct != null) { return(ct); } ct = new XmlSchemaComplexType(); ct.Name = typeId; // add complex type to collection immediately to avoid stack // overflows, when we allow a type to be nested _nantComplexTypes.Add(typeId, ct); #if NOT_IMPLEMENTED // // TODO - add task/type documentation in the future // ct.Annotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); ct.Annotation.Items.Add(doc); doc.Markup = ...; #endif XmlSchemaSequence group1 = null; XmlSchemaObjectCollection attributesCollection = ct.Attributes; foreach (MemberInfo memInfo in t.GetMembers(BindingFlags.Instance | BindingFlags.Public)) { if (memInfo.DeclaringType.Equals(typeof(object))) { continue; } //Check for any return type that is derived from Element // add Attributes TaskAttributeAttribute taskAttrAttr = (TaskAttributeAttribute) Attribute.GetCustomAttribute(memInfo, typeof(TaskAttributeAttribute), false); BuildElementAttribute buildElemAttr = (BuildElementAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute), false); if (taskAttrAttr != null) { XmlSchemaAttribute newAttr = CreateXsdAttribute(taskAttrAttr.Name, taskAttrAttr.Required); attributesCollection.Add(newAttr); } else if (buildElemAttr != null) { // Create individial choice for any individual child Element Decimal min = 0; if (buildElemAttr.Required) { min = 1; } XmlSchemaElement childElement = new XmlSchemaElement(); childElement.MinOccurs = min; childElement.MaxOccurs = 1; childElement.Name = buildElemAttr.Name; //XmlSchemaGroupBase elementGroup = CreateXsdSequence(min, Decimal.MaxValue); Type childType; // We will only process child elements if they are defined for Properties or Fields, this should be enforced by the AttributeUsage on the Attribute class if (memInfo is PropertyInfo) { childType = ((PropertyInfo)memInfo).PropertyType; } else if (memInfo is FieldInfo) { childType = ((FieldInfo)memInfo).FieldType; } else if (memInfo is MethodInfo) { MethodInfo method = (MethodInfo)memInfo; if (method.GetParameters().Length == 1) { childType = method.GetParameters()[0].ParameterType; } else { throw new ApplicationException("Method should have one parameter."); } } else { throw new ApplicationException("Member Type != Field/Property/Method"); } BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementArrayAttribute), false); // determine type of child elements if (buildElementArrayAttribute != null) { if (buildElementArrayAttribute.ElementType == null) { if (childType.IsArray) { childType = childType.GetElementType(); } else { Type elementType = null; // locate Add method with 1 parameter, type of that parameter is parameter type foreach (MethodInfo method in childType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; elementType = parameter.ParameterType; break; } } childType = elementType; } } else { childType = buildElementArrayAttribute.ElementType; } if (childType == null || !typeof(Element).IsAssignableFrom(childType)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1140"), memInfo.DeclaringType.FullName, memInfo.Name)); } } BuildElementCollectionAttribute buildElementCollectionAttribute = (BuildElementCollectionAttribute)Attribute.GetCustomAttribute(memInfo, typeof(BuildElementCollectionAttribute), false); if (buildElementCollectionAttribute != null) { XmlSchemaComplexType collectionType = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); collectionType.Particle = sequence; sequence.MinOccurs = 0; sequence.MaxOccursString = "unbounded"; XmlSchemaElement itemType = new XmlSchemaElement(); itemType.Name = buildElementCollectionAttribute.ChildElementName; itemType.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; sequence.Items.Add(itemType); childElement.SchemaType = collectionType; } else { childElement.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; } // lazy init of sequence if (group1 == null) { group1 = CreateXsdSequence(0, Decimal.MaxValue); ct.Particle = group1; } group1.Items.Add(childElement); } } // allow attributes from other namespace ct.AnyAttribute = new XmlSchemaAnyAttribute(); ct.AnyAttribute.Namespace = "##other"; ct.AnyAttribute.ProcessContents = XmlSchemaContentProcessing.Skip; Schema.Items.Add(ct); Compile(); return(ct); }
/// <summary> /// Creates WindowsVolumeEncryptionMonitorImpl. /// </summary> /// <param name="virtualMachineId">Resource id of Windows virtual machine to retrieve encryption status from.</param> /// <param name="computeManager">Compute manager.</param> ///GENMHASH:F0AB482101B80764DF92472E6DF90604:0C2BFB2332C823A9307222D73EFBAF83 internal WindowsVolumeEncryptionMonitorImpl(string virtualMachineId, IComputeManager computeManager) { this.rgName = ResourceUtils.GroupFromResourceId(virtualMachineId); this.vmName = ResourceUtils.NameFromResourceId(virtualMachineId); this.computeManager = computeManager; }
private void ShowSelectedTrackInformation() { // Don't try to show the file information when nothing is selected if (this.SelectedTracks == null || this.SelectedTracks.Count == 0) { return; } Views.FileInformation view = this.container.Resolve <Views.FileInformation>(); view.DataContext = this.container.Resolve <FileInformationViewModel>(new DependencyOverride(typeof(TrackInfo), this.SelectedTracks.First())); this.dialogService.ShowCustomDialog(0xe8d6, 16, ResourceUtils.GetStringResource("Language_Information"), view, 400, 620, true, false, ResourceUtils.GetStringResource("Language_Ok"), string.Empty, null); }
public void MakeROM(string InFile, string FileName, BackgroundWorker worker) { using (BinaryReader OldROM = new BinaryReader(File.Open(InFile, FileMode.Open, FileAccess.Read))) { RomUtils.ReadFileTable(OldROM); _messageTable.InitializeTable(); } var originalMMFileList = RomData.MMFileList.Select(file => file.Clone()).ToList(); byte[] hash; if (!string.IsNullOrWhiteSpace(_settings.InputPatchFilename)) { worker.ReportProgress(50, "Applying patch..."); hash = RomUtils.ApplyPatch(_settings.InputPatchFilename); // Apply Asm configuration post-patch WriteAsmConfigPostPatch(); } else { worker.ReportProgress(55, "Writing player model..."); WritePlayerModel(); if (_settings.LogicMode != LogicMode.Vanilla) { worker.ReportProgress(60, "Applying hacks..."); ResourceUtils.ApplyHack(Values.ModsDirectory + "title-screen"); ResourceUtils.ApplyHack(Values.ModsDirectory + "misc-changes"); ResourceUtils.ApplyHack(Values.ModsDirectory + "cm-cs"); ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-song-of-healing"); WriteFileSelect(); } ResourceUtils.ApplyHack(Values.ModsDirectory + "init-file"); ResourceUtils.ApplyHack(Values.ModsDirectory + "fierce-deity-anywhere"); worker.ReportProgress(61, "Writing quick text..."); WriteQuickText(); worker.ReportProgress(62, "Writing cutscenes..."); WriteCutscenes(); worker.ReportProgress(63, "Writing dungeons..."); WriteDungeons(); worker.ReportProgress(64, "Writing gimmicks..."); WriteGimmicks(); worker.ReportProgress(65, "Writing speedups..."); WriteSpeedUps(); worker.ReportProgress(66, "Writing enemies..."); WriteEnemies(); // if shop should match given items { WriteShopObjects(); } worker.ReportProgress(67, "Writing items..."); WriteItems(); worker.ReportProgress(68, "Writing messages..."); WriteGossipQuotes(); MessageTable.WriteMessageTable(_messageTable, _settings.QuickTextEnabled); worker.ReportProgress(69, "Writing startup..."); WriteStartupStrings(); worker.ReportProgress(70, "Writing ASM patch..."); WriteAsmPatch(); worker.ReportProgress(71, _settings.GeneratePatch ? "Generating patch..." : "Computing hash..."); hash = RomUtils.CreatePatch(_settings.GeneratePatch ? FileName : null, originalMMFileList); } worker.ReportProgress(72, "Writing cosmetics..."); WriteTatlColour(); WriteTunicColor(); worker.ReportProgress(73, "Writing music..."); WriteAudioSeq(new Random(BitConverter.ToInt32(hash, 0))); WriteMuteMusic(); worker.ReportProgress(74, "Writing sound effects..."); WriteSoundEffects(new Random(BitConverter.ToInt32(hash, 0))); if (_settings.GenerateROM) { worker.ReportProgress(75, "Building ROM..."); byte[] ROM = RomUtils.BuildROM(FileName); if (_settings.OutputVC) { worker.ReportProgress(90, "Building VC..."); VCInjectionUtils.BuildVC(ROM, _settings.PatcherOptions, Values.VCDirectory, Path.ChangeExtension(FileName, "wad")); } } worker.ReportProgress(100, "Done!"); }
protected async Task AddTracksToPlaylistAsync(IList <TrackInfo> tracks, string playlistName) { AddToPlaylistResult result = await this.collectionService.AddTracksToPlaylistAsync(tracks, playlistName); if (!result.IsSuccess) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetStringResource("Language_Error"), ResourceUtils.GetStringResource("Language_Error_Adding_Songs_To_Playlist").Replace("%playlistname%", "\"" + playlistName + "\""), ResourceUtils.GetStringResource("Language_Ok"), true, ResourceUtils.GetStringResource("Language_Log_File")); } }
protected override void ExecuteTask() { string includedFileName = Path.GetFullPath(Path.Combine(_currentBasedir, BuildFileName)); // check if build file exists if (!File.Exists(includedFileName)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1127"), includedFileName), Location); } // check if file has already been mapped, if it has not yet been mapped, // add the include file to the map. This addresses Bug#: 3016497 if (Project.LocationMap.FileIsMapped(includedFileName)) { Log(Level.Verbose, ResourceUtils.GetString("String_DuplicateInclude"), includedFileName); return; } else { XmlDocument mapDoc = new XmlDocument(); mapDoc.Load(includedFileName); Project.LocationMap.Add(mapDoc); mapDoc = null; } // push ourselves onto the stack (prevents recursive includes) _includedFileNames.Push(includedFileName); // increment the nesting level _nestinglevel++; Log(Level.Verbose, "Including file {0}.", includedFileName); // store original base directory string oldBaseDir = _currentBasedir; // set basedir to be used by the nested calls (if any) _currentBasedir = Path.GetDirectoryName(includedFileName); try { // This section addresses SF Bug#:2824210.. // // Description of issue: // The root cause to this bug is mismatching NamespaceURIs between the main // build file and the include file. There is no place where the include // build file's Namespace is added to the main build files namespace collection. // So if the NamespaceURI of the include file doesn't match the main build file, // then the Project class would not import any of the include file contents. // // Resolution: // The key is to have the Namespaces match between project and include files. // Rather than remove the Namespace checks in the Project class, I decided to // copy the project's namespace into the include file prior to importing into the // main file. Unfortunately, it is not an easy task. // Create two XmlDocument variables. One to sanitize the include file (doc) // and one to pass to the project class (loadDoc). XmlDocument doc = new XmlDocument(); XmlDocument loadDoc = new XmlDocument(); // Gets the namespace from the main project. string projectNamespaceURI = Project.Document.DocumentElement.NamespaceURI; // String variable to hold the main build file's namespace. string projectURI = ""; // Rather than loading the xml file directly into the XmlDocument, it is loaded // into an XmlTextReader so any NamespaceURI may be stripped out before proceeding // further. XmlTextReader includeXmlReader = new XmlTextReader(includedFileName); // Turn the namespaces off includeXmlReader.Namespaces = false; // Load the contents of the XmlTextReader into the doc XmlDocument doc.Load(includeXmlReader); // Strip the namespace attribute. doc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); // Kill the XmlTextReader ((IDisposable)includeXmlReader).Dispose(); includeXmlReader = null; // Assigns the main build file's namespace to the // local string variable if it is not blank. if (!String.IsNullOrEmpty(projectNamespaceURI)) { projectURI = projectNamespaceURI; } // If the projectURI is not empty at this point, add // the Namespace attribute to the doc XmlDocument. if (!String.IsNullOrEmpty(projectURI)) { XmlAttribute projAttr = doc.CreateAttribute("xmlns"); projAttr.Value = projectURI; doc.DocumentElement.Attributes.Append(projAttr); } // Set up a stringwriter and XmlTextWriter variable to pass the // contents of the doc XmlDocument variable to. using (StringWriter includeFileSW = new StringWriter()) { XmlTextWriter includeFileXW = new XmlTextWriter(includeFileSW); // Loads the contents from doc to the XmlTextWriter. doc.WriteTo(includeFileXW); // Then the contents of the XmlTextWriter to the loadDoc XmlDocument // var. This will ensure that the main build file's Namespace // is loaded into the include file before it's passed to the Project // class. loadDoc.LoadXml(includeFileSW.ToString()); // Kill the XmlTextWriter ((IDisposable)includeFileXW).Dispose(); includeFileXW = null; } // Pass the loadDoc XmlDocument to the project. Project.InitializeProjectDocument(loadDoc); } catch (BuildException) { // rethrow exception throw; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1128"), includedFileName), Location, ex); } finally { // pop off the stack _includedFileNames.Pop(); // decrease the nesting level _nestinglevel--; // restore original base directory _currentBasedir = oldBaseDir; } }
protected void EditSelectedTracks() { if (this.SelectedTracks == null || this.SelectedTracks.Count == 0) { return; } EditTrack view = this.container.Resolve <EditTrack>(); view.DataContext = this.container.Resolve <EditTrackViewModel>(new DependencyOverride(typeof(IList <TrackInfo>), this.SelectedTracks)); string dialogTitle = this.SelectedTracks.Count > 1 ? ResourceUtils.GetStringResource("Language_Edit_Multiple_Songs") : ResourceUtils.GetStringResource("Language_Edit_Song"); this.dialogService.ShowCustomDialog(0xe104, 14, dialogTitle, view, 620, 450, false, true, ResourceUtils.GetStringResource("Language_Ok"), ResourceUtils.GetStringResource("Language_Cancel"), ((EditTrackViewModel)view.DataContext).SaveTracksAsync); }
private async Task AddGenresToNowPlayingAsync(IList <string> genres) { EnqueueResult result = await this.playbackService.AddGenresToQueueAsync(genres); if (!result.IsSuccess) { this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Adding_Genres_To_Now_Playing"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } }
/// <summary> /// This is where the work is done. /// </summary> protected override void ExecuteTask() { MailMessage mailMessage = new MailMessage(); // Gather any email addresses provided by the task. MailAddressCollection toAddrs = ParseAddresses(ToList); MailAddressCollection ccAddrs = ParseAddresses(CcList); MailAddressCollection bccAddrs = ParseAddresses(BccList); // If any addresses were specified in the to, cc, and/or bcc // list, add them to the mailMessage object. foreach (MailAddress toAddr in toAddrs) { mailMessage.To.Add(toAddr); } foreach (MailAddress ccAddr in ccAddrs) { mailMessage.CC.Add(ccAddr); } foreach (MailAddress bccAddr in bccAddrs) { mailMessage.Bcc.Add(bccAddr); } // If a reply to address was specified, add it to the // mailMessage object. Starting with .NET 4.0, the // ReplyTo property was deprecated in favor of // ReplyToList. if (!String.IsNullOrEmpty(ReplyTo)) { #if NET_4_0 MailAddressCollection replyAddrs = ParseAddresses(ReplyTo); if (replyAddrs.Count > 0) { foreach (MailAddress replyAddr in replyAddrs) { mailMessage.ReplyToList.Add(replyAddr); } } #else mailMessage.ReplyTo = ConvertStringToMailAddress(ReplyTo); #endif } // Add the From and Subject lines to the mailMessage object. mailMessage.From = ConvertStringToMailAddress(this.From); mailMessage.Subject = this.Subject; // Indicate whether or not the body of the email is in html format. mailMessage.IsBodyHtml = this.IsBodyHtml; // ensure base directory is set, even if fileset was not initialized // from XML if (Files.BaseDirectory == null) { Files.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Attachments.BaseDirectory == null) { Attachments.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // begin build message body StringWriter bodyWriter = new StringWriter(CultureInfo.InvariantCulture); if (!String.IsNullOrEmpty(Message)) { bodyWriter.WriteLine(Message); bodyWriter.WriteLine(); } // append file(s) to message body foreach (string fileName in Files.FileNames) { try { string content = ReadFile(fileName); if (!String.IsNullOrEmpty(content)) { bodyWriter.Write(content); bodyWriter.WriteLine(string.Empty); } } catch (Exception ex) { Log(Level.Warning, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1135"), fileName, ex.Message)); } } // add message body to mailMessage string bodyText = bodyWriter.ToString(); if (bodyText.Length != 0) { mailMessage.Body = bodyText; } // add attachments to message foreach (string fileName in Attachments.FileNames) { try { Attachment attachment = new Attachment(fileName); mailMessage.Attachments.Add(attachment); } catch (Exception ex) { Log(Level.Warning, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1136"), fileName, ex.Message)); } } Log(Level.Info, "Sending mail..."); Log(Level.Verbose, "To: {0}", mailMessage.To); Log(Level.Verbose, "Cc: {0}", mailMessage.CC); Log(Level.Verbose, "Bcc: {0}", mailMessage.Bcc); Log(Level.Verbose, "Subject: {0}", mailMessage.Subject); // Initialize a new SmtpClient object to sent email through. #if NET_4_0 // Starting with .NET 4.0, SmtpClient implements IDisposable. using (SmtpClient smtp = new SmtpClient(this.Mailhost)) { #else SmtpClient smtp = new SmtpClient(this.Mailhost); #endif // send message try { // If username and password attributes are provided, // use the information as the network credentials. // Otherwise, use the default credentials (the information // used by the user to login to the machine. if (!String.IsNullOrEmpty(this.UserName) && !String.IsNullOrEmpty(this.Password)) { smtp.Credentials = new NetworkCredential(this.UserName, this.Password); } else { // Mono does not implement the UseDefaultCredentials // property in the SmtpClient class. So only set the // property when NAnt is run on .NET. Otherwise, // use an emtpy NetworkCredential object as the // SmtpClient credentials. if (PlatformHelper.IsMono) { smtp.Credentials = new NetworkCredential(); } else { smtp.UseDefaultCredentials = true; } } // Set the ssl and the port information. smtp.EnableSsl = this.EnableSsl; smtp.Port = this.Port; // Send the email. smtp.Send(mailMessage); } catch (Exception ex) { StringBuilder msg = new StringBuilder(); msg.AppendLine("Error enountered while sending mail message."); msg.AppendLine("Make sure that the following information is valid:"); msg.AppendFormat(CultureInfo.InvariantCulture, "Mailhost: {0}", this.Mailhost).AppendLine(); msg.AppendFormat(CultureInfo.InvariantCulture, "Mailport: {0}", this.Port.ToString()).AppendLine(); msg.AppendFormat(CultureInfo.InvariantCulture, "Use SSL: {0}", this.EnableSsl.ToString()).AppendLine(); if (!String.IsNullOrEmpty(this.UserName) && !String.IsNullOrEmpty(this.Password)) { msg.AppendFormat(CultureInfo.InvariantCulture, "Username: {0}", this.UserName).AppendLine(); } else { msg.AppendLine("Using default credentials"); } throw new BuildException("Error sending mail:" + Environment.NewLine + msg.ToString(), Location, ex); } #if NET_4_0 } #endif }
/// <summary> /// Determines the path of the external program that should be executed. /// </summary> /// <returns> /// A fully qualifies pathname including the program name. /// </returns> /// <exception cref="BuildException">The task is not available or not configured for the current framework.</exception> private string DetermineFilePath() { string fullPath = ""; // if the Exename is already specified as a full path then just use that. if (ExeName != null && Path.IsPathRooted(ExeName)) { return(ExeName); } // get the ProgramLocation attribute ProgramLocationAttribute programLocationAttribute = (ProgramLocationAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(ProgramLocationAttribute)); if (programLocationAttribute != null) { // ensure we have a valid framework set. if ((programLocationAttribute.LocationType == LocationType.FrameworkDir || programLocationAttribute.LocationType == LocationType.FrameworkSdkDir) && (Project.TargetFramework == null)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1120") + Environment.NewLine, Name)); } switch (programLocationAttribute.LocationType) { case LocationType.FrameworkDir: if (Project.TargetFramework.FrameworkDirectory != null) { string frameworkDir = Project.TargetFramework.FrameworkDirectory.FullName; fullPath = Path.Combine(frameworkDir, ExeName + ".exe"); } else { throw new BuildException( string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1124"), Project.TargetFramework.Name)); } break; case LocationType.FrameworkSdkDir: if (Project.TargetFramework.SdkDirectory != null) { string sdkDirectory = Project.TargetFramework.SdkDirectory.FullName; fullPath = Path.Combine(sdkDirectory, ExeName + ".exe"); } else { throw new BuildException( string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1122"), Project.TargetFramework.Name)); } break; } if (!File.Exists(fullPath)) { string toolPath = Project.TargetFramework.GetToolPath( ExeName + ".exe"); if (toolPath != null) { fullPath = toolPath; } } } else { // rely on it being on the path. fullPath = ExeName; } return(fullPath); }
protected async Task GetTracksAsync(IList <string> artists, IList <string> genres, IList <AlbumViewModel> albumViewModels, TrackOrder trackOrder) { IList <Track> tracks = null; if (albumViewModels != null && albumViewModels.Count > 0) { // First, check Albums. They topmost have priority. tracks = await this.trackRepository.GetAlbumTracksAsync(albumViewModels.Select(x => x.AlbumKey).ToList()); } else if (!artists.IsNullOrEmpty()) { // Artists and Genres have the same priority tracks = await this.trackRepository.GetArtistTracksAsync(artists.Select(x => x.Replace(ResourceUtils.GetString("Language_Unknown_Artist"), string.Empty)).ToList()); } else if (!genres.IsNullOrEmpty()) { // Artists and Genres have the same priority tracks = await this.trackRepository.GetGenreTracksAsync(genres.Select(x => x.Replace(ResourceUtils.GetString("Language_Unknown_Genre"), string.Empty)).ToList()); } else { // Tracks have lowest priority tracks = await this.trackRepository.GetTracksAsync(); } await this.GetTracksCommonAsync(await this.container.ResolveTrackViewModelsAsync(tracks), trackOrder); }
/// <summary> /// Retrieves the specified <see cref="Type" /> corresponding with the specified /// type name from a list of assemblies. /// </summary> /// <param name="assemblies">The collection of assemblies that the type should tried to be instantiated from.</param> /// <param name="imports">The list of imports that can be used to resolve the typename to a full typename.</param> /// <param name="typename">The typename that should be used to determine the type to which the specified value should be converted.</param> /// <param name="value">The <see cref="string" /> value that should be converted to a typed value.</param> /// <returns></returns> /// <exception cref="BuildException"> /// <para><paramref name="value" /> is <see langword="null" /> and the <see cref="Type" /> identified by <paramref name="typename" /> has no default public constructor.</para> /// <para>-or-</para> /// <para><paramref name="value" /> cannot be converted to a value that's suitable for one of the constructors of the <see cref="Type" /> identified by <paramref name="typename" />.</para> /// <para>-or-</para> /// <para>The <see cref="Type" /> identified by <paramref name="typename" /> has no suitable constructor.</para> /// <para>-or-</para> /// <para>A <see cref="Type" /> identified by <paramref name="typename" /> could not be located or loaded.</para> /// </exception> public object GetTypedValue(StringCollection assemblies, StringCollection imports, string typename, string value) { // create assembly resolver AssemblyResolver assemblyResolver = new AssemblyResolver(); // attach assembly resolver to the current domain assemblyResolver.Attach(); try { Type type = null; // load each assembly and try to get type from it foreach (string assemblyFileName in assemblies) { // load assembly from filesystem Assembly assembly = Assembly.LoadFrom(assemblyFileName); // try to load type from assembly type = assembly.GetType(typename, false, false); if (type == null) { foreach (string import in imports) { type = assembly.GetType(import + "." + typename, false, false); if (type != null) { break; } } } if (type != null) { break; } } // try to load type from all assemblies loaded from disk, if // it was not loaded from the references assemblies if (type == null) { type = Type.GetType(typename, false, false); if (type == null) { foreach (string import in imports) { type = Type.GetType(import + "." + typename, false, false); if (type != null) { break; } } } } if (type != null) { object typedValue = null; if (value == null) { ConstructorInfo defaultConstructor = type.GetConstructor( BindingFlags.Public | BindingFlags.Instance, null, new Type[0], new ParameterModifier[0]); if (defaultConstructor != null) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2005"), type.FullName), Location.UnknownLocation); } typedValue = null; } else { ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); for (int counter = 0; counter < constructors.Length; counter++) { ParameterInfo[] parameters = constructors[counter].GetParameters(); if (parameters.Length == 1) { if (parameters[0].ParameterType.IsPrimitive || parameters[0].ParameterType == typeof(string)) { try { // convert value to type of constructor parameter typedValue = Convert.ChangeType(value, parameters[0].ParameterType, CultureInfo.InvariantCulture); break; } catch (Exception ex) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2006"), value, parameters[0].ParameterType.FullName, type.FullName), Location.UnknownLocation, ex); } } } } if (typedValue == null) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2003"), typename), Location.UnknownLocation); } } return(typedValue); } else { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2001"), typename), Location.UnknownLocation); } } finally { // detach assembly resolver from the current domain assemblyResolver.Detach(); } }
private void resourceBulkConvertBtn_Click(object sender, EventArgs e) { ResourceFormat inputFormat = ResourceFormat.LSX; switch (resourceInputFormatCb.SelectedIndex) { case 0: inputFormat = ResourceFormat.LSX; break; case 1: inputFormat = ResourceFormat.LSB; break; case 2: inputFormat = ResourceFormat.LSF; break; } ResourceFormat outputFormat = ResourceFormat.LSF; int outputVersion = -1; switch (resourceOutputFormatCb.SelectedIndex) { case 0: outputFormat = ResourceFormat.LSX; break; case 1: outputFormat = ResourceFormat.LSB; break; case 2: outputFormat = ResourceFormat.LSF; if (GetGame() == DivGame.DOS2) { outputVersion = (int)FileVersion.VerExtendedNodes; } else { outputVersion = (int)FileVersion.VerChunkedCompress; } break; } try { resourceConvertBtn.Enabled = false; var utils = new ResourceUtils(); utils.progressUpdate += this.ResourceProgressUpdate; utils.ConvertResources(resourceInputDir.Text, resourceOutputDir.Text, inputFormat, outputFormat, outputVersion); MessageBox.Show("Resources converted successfully."); } catch (Exception exc) { MessageBox.Show("Internal error!\r\n\r\n" + exc.ToString(), "Conversion Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { resourceProgressLabel.Text = ""; resourceConversionProgress.Value = 0; resourceConvertBtn.Enabled = true; } }