public static void AddFeatBenefits(Character character, string feat) { string stat = ""; string lang = ""; string expertise = ""; var prof = new List <string>(); if (OneStatFeats.Contains(feat)) { stat = Options.FeatDefinitions[feat].Substring(9, 3); Stats.IncreaseStat(character, stat, 1); } var choices = new List <string>(); switch (feat) { case "Chef": choices = new List <string> { "Con", "Wis" }; character.Proficiencies.Add("Cook's Utensils"); break; case "Crusher": choices = new List <string> { "Str", "Con" }; break; case "Dragon Fear": choices = new List <string> { "Str", "Con", "Cha" }; break; case "Dragon Hide": choices = new List <string> { "Str", "Con", "Cha" }; break; case "Elven Accuracy": choices = new List <string> { "Dex", "Int", "Wis", "Cha" }; break; case "Fey Teleportation": choices = new List <string> { "Int", "Cha" }; character.Languages.Add("Sylvan"); break; case "Flames of Phlegethos": choices = new List <string> { "Int", "Cha" }; break; case "Observant": choices = new List <string> { "Int", "Wis" }; break; case "Orcish Fury": choices = new List <string> { "Str", "Con" }; break; case "Second Chance": choices = new List <string> { "Dex", "Con", "Cha" }; break; } if (StrDexFeats.Contains(feat)) { choices = new List <string> { "Str", "Dex" }; StatFeats.AddRange(StrDexFeats); } if (IntWisChaFeats.Contains(feat)) { choices = new List <string> { "Int", "Wis", "Cha" }; StatFeats.AddRange(IntWisChaFeats); } if (StatFeats.Contains(feat)) { Console.WriteLine("Pick a stat to increase by 1"); stat = CLIHelper.PrintChoices(choices); Stats.IncreaseStat(character, stat, 1); } if (SpellFeats.Contains(feat)) { string cantrip = ""; string spell = ""; switch (feat) { case "Arcane Initiate": Console.WriteLine("Pick an Artificer cantrip"); cantrip = CLIHelper.PrintChoices(ArtificerSpells.Cantrips); character.Cantrips.Add(cantrip); Console.WriteLine("Pick a 1st lvl Artificer spell"); spell = CLIHelper.PrintChoices(ArtificerSpells.FirstLvls); character.Spells[1].Add(spell); Console.WriteLine("Pick a set of Artisan's Tools to gain proficiency with"); string tool = CLIHelper.PrintChoices(Options.ArtisanTools); character.ToolProficiencies.Add(tool); break; case "Drow High Magic": character.Spells[1].Add("Detect Magic(at-will)"); character.Spells[2].Add("Levitate(1/LR, Cha to cast)"); character.Spells[3].Add("Dispel Magic(1/LR, Cha to cast)"); break; case "Fey Touched": choices.Clear(); choices.AddRange(AllSpells.FirstLvlDivination); choices.AddRange(AllSpells.FirstLvlEnchantment); choices.Sort(); Console.WriteLine("Pick a 1st lvl divination or enchantment spell"); spell = CLIHelper.PrintChoices(choices); character.Spells[1].Add(spell + "(Fey Touched)"); break; case "Magic Initiate": Tuple <Dictionary <int, List <string> >, string> spellClass = PickClassForSpells(); Dictionary <int, List <string> > spellList = spellClass.Item1; stat = spellClass.Item2; Console.WriteLine("Pick 2 cantrips"); cantrip = CLIHelper.PrintChoices(spellList[0]); character.Cantrips.Add(cantrip); spellList[0].Remove(cantrip); cantrip = CLIHelper.PrintChoices(spellList[0]); character.Cantrips.Add(cantrip); int index = CLIHelper.PrintChoices("Pick a 1st lvl spell", spellList[1]); spell = spellList[1][index]; character.Spells[1].Add(spell + $"(1/LR, {stat} to cast)"); break; case "Ritual Caster": var classes = new List <string> { "Bard", "Cleric", "Druid", "Sorcerer", "Warlock", "Wizard" }; index = CLIHelper.PrintChoices("Pick a class that will determine the spells you can gain", classes); string spellcastingClass = classes[index]; Tuple <List <string>, string> ritualClass = PickClassForSpells(spellcastingClass); List <string> ritualSpellList = ritualClass.Item1; stat = ritualClass.Item2; Console.WriteLine("Pick 2 ritual spells"); spell = CLIHelper.PrintChoices(ritualSpellList); character.Spells[1].Add(spell + $"({stat} to cast)"); ritualSpellList.Remove(spell); spell = CLIHelper.PrintChoices(ritualSpellList); character.Spells[1].Add(spell + $"ritual, ({stat} to cast)"); break; case "Shadow Touched": choices.Clear(); choices.AddRange(AllSpells.FirstLvlIllusion); choices.AddRange(AllSpells.FirstLvlNecromancy); choices.Sort(); Console.WriteLine("Pick a 1st lvl divination or enchantment spell"); spell = CLIHelper.PrintChoices(choices); character.Spells[1].Add(spell + "(Fey Touched)"); break; case "Telekinetic": character.Cantrips.Add("Mage Hand(feat)"); break; case "Wood Elf Magic": Console.WriteLine("Pick a Druid cantrip"); cantrip = CLIHelper.PrintChoices(DruidSpells.Cantrips); character.Cantrips.Add(cantrip); character.Spells[1].Add("Longstrider(1/LR, Wis to cast)"); character.Spells[2].Add("Pass without Trace(1/LR, Wis to cast)"); break; } } //all other feats switch (feat) { case "Alert": character.Init += 5; break; case "Athlete": character.Speedstring += $", Climb {character.Speed}ft"; break; case "Dual Wielder": character.AC += 1; break; case "Eldritch Adept": var invoc = new List <string> { "Armor of Shadows", "Beast Speech", "Beguiling Influence", "Devil's Sight", "Eldritch Mind", "Eldritch Sight", "Eyes of the Rune Keeper", "Fiendish Vigor", "Gaze of Two Minds", "Grasp of Hadar", "Lance of Lethargy", "Mask of Many Faces", "Misty Visions", "Thief of Five Fates" }; string newInvoc = CLIHelper.PrintChoices(Options.AllInvocations, invoc, "Pick an Invocation"); character.ClassFeatures.Add("Invocations", "\n ------------------------------------"); character.ClassFeatures.Add(newInvoc, Options.AllInvocations[newInvoc]); invoc.Remove(newInvoc); newInvoc = CLIHelper.PrintChoices(Options.AllInvocations, invoc, "Pick an Invocation"); character.ClassFeatures.Add(newInvoc, Options.AllInvocations[newInvoc]); break; case "Fighting Initiate": string fightStyleMsg = "Pick a fighting style."; List <string> styleList = new List <string>(); foreach (var style in Options.FightingStyles.Keys) { if (style != "Blessed Warrior" || style != "Druidic Warrior" || style != "Superior Technique") { styleList.Add(style); } } string fightStyle = CLIHelper.PrintChoices(Options.FightingStyles, styleList, fightStyleMsg); string fightStyleKey = $"Fighting Style({fightStyle})"; string fightStyleValue = Options.FightingStyles[fightStyle]; character.ClassFeatures.Add(fightStyleKey, fightStyleValue); break; case "Gunner": character.Proficiencies.Add("Firearms"); break; case "Heavily Armored": character.Proficiencies.Add("Heavy Armor"); break; case "Lightly Armored": character.Proficiencies.Add("Light Armor"); break; case "Lingusit": Console.WriteLine("You gain 3 languages of your choice. Pick the first language now"); string pickMsg = "Pick another language"; for (int i = 0; i < 3; i++) { lang = CLIHelper.GetNew(Options.Languages, character.Languages, pickMsg); character.Languages.Add(lang); } break; case "Martial Adept": List <string> maneuvers = CLIHelper.GetDictionaryOptions(Options.Maneuvers, 2, "Pick a new maneuver"); character.ClassFeatures.Add("Maneuvers(D6)", "\n ------------------------------------"); foreach (var item in maneuvers) { character.ClassFeatures.Add(item, Options.Maneuvers[item]); } break; case "Medium Armor Master": character.AC += 1; break; case "Metamagic Adept": var metamagicList = new List <string>(); foreach (var item in Options.Metamagic.Keys) { metamagicList.Add(item); } character.ClassFeatures.Add("Metamagic", "Gain 2 Metamgagic options, can only use 1 option at a time"); Console.WriteLine("You get 2 metamagic options of your choice"); for (int i = 0; i < 2; i++) { string metamagic = CLIHelper.PrintChoices(Options.Metamagic, metamagicList, "Pick an option"); character.Metamagic.Add(metamagic); character.ClassFeatures["Metamagic"] += $"\n{metamagic}: {Options.Metamagic[metamagic]}"; metamagicList.Remove(metamagic); } break; case "Mobile": character.Speed += 10; break; case "Moderately Armored": character.Proficiencies.Add("Heavy Armor"); break; case "Prodigy": string skill = CLIHelper.GetNew(Options.Skills, character.SkillProficiencies, "Pick a skill to gain proficiency"); character.SkillProficiencies.Add(skill); prof.AddRange(character.SkillProficiencies); expertise = CLIHelper.PrintChoices(prof); BEHelper.AddSkillExpertise(expertise, character); BEHelper.GetTool(character); lang = CLIHelper.GetNew(Options.Languages, character.Languages, "Pick a language"); character.Languages.Add(lang); break; case "Resilient": string resStat = Stats.IncreaseStat(character, 1, true); character.Saves.Add(resStat); break; case "Skill Expert": Stats.IncreaseStat(character, 1); Console.WriteLine("Pick a skill to gain Expertise in"); prof.AddRange(character.SkillProficiencies); expertise = CLIHelper.PrintChoices(prof); BEHelper.AddSkillExpertise(expertise, character); int index = CLIHelper.PrintChoices("Pick a skill to gain proficiency", Options.Skills); character.SkillProficiencies.Add(Options.Skills[index]); break; case "Skilled": GetSkillsOrTools(character); break; case "Squat Nimbleness": var skills = new List <string> { "Acrobatics", "Athletics" }; index = CLIHelper.PrintChoices("Pick a skill", skills); character.SkillProficiencies.Add(skills[index]); break; case "Tavern Brawler": character.Proficiencies.Add("Improvised Weapons"); character.Proficiencies.Add("Unarmed Strike"); break; case "Tough": character.HP += character.Lvl * 2; break; } }
public static void Mutant(Character character) { int lvl = character.Lvl; int formulas = 3; for (int i = 7; i < lvl; i += 3) { formulas++; if (i == 10) { i += 2; } } var mutagens = new List <string>(); var dict = new Dictionary <string, string>(); foreach (var item in Options.Mutagens.Keys) { dict.Add(item, Options.Mutagens[item]); } if (lvl < 7) { dict.Remove("Precision"); } if (lvl < 10) { dict.Remove("Aether"); } else { dict["Mobility"] += ", paralyze"; } if (lvl >= 15) { dict["Precision"] = "crit on 18-20, half all healing received"; dict["Rapidity"] = "gain speed +15ft, enemies crit on 19-20"; } foreach (var item in dict.Keys) { mutagens.Add(item); } character.ClassFeatures.Add("Mutagen Craft", "on SR, create a mutagen, consume as bonus, duration until SR, mutation score = lvl / 4, rounded up"); for (int i = 0; i < formulas; i++) { string newMutagen = CLIHelper.PrintChoices(dict, mutagens, "Pick a new mutagen formula"); mutagens.Remove(newMutagen); character.ClassFeatures["Mutagen Craft"] += $"\n{newMutagen}({dict[newMutagen]})"; } if (character.ClassFeatures["Mutagen Craft"].Contains("Nighteye")) { if (character.Vision.Contains("Lowlight")) { character.Vision = "Darkvision 60ft"; } else { string vision = character.Vision; if (vision.Contains("Superior")) { character.Vision = "Superior Darkvision 180ft"; } else { character.Vision = "Darkvision 120ft"; } } } if (lvl >= 7) { character.ClassFeatures.Add("Advanced Mutagen Craft", "on SR, create 2 mutagens, must be different formulas"); } if (lvl >= 10) { character.ClassFeatures.Add("Robust Physiology", "gain Immunity to Poison dmg and poison(condition)"); } if (lvl >= 15) { character.ClassFeatures["Advanced Mutagen Craft"] = "on SR, create 3 mutagens, must be different formulas"; character.ClassFeatures.Add("Strange Metabolism", "SR, ignore the side effect from 1 mutagen after taking it"); } if (lvl >= 18) { character.ClassFeatures.Add("Exalted Mutation", "choose 1 mutagen formula to gain permanently, can't be changed or effected by Strange Metabolism"); } }
public static void Features(Character character) { int lvl = character.Lvl; int index = -1; int dmg = 4; for (int i = 5; i <= lvl; i += 4) { dmg += 2; } int rites = 1; for (int i = 6; i <= lvl; i += 3) { rites++; if (i == 9) { i++; } } var primalRites = new List <string> { "Rite of the Flame", "Rite of the Frozen", "Rite of the Ruined", "Rite of the Storm" }; var esotericRites = new List <string> { "Rite of the Dead", "Rite of the Oracle", "Rite of the Roar" }; string msg = "Pick a Primal Rite"; var dmgTypes = new List <string>(); for (int i = 0; i < rites; i++) { if (i != 3) { index = CLIHelper.PrintChoices(msg, primalRites); string newRite = primalRites[index]; string riteType = newRite.Substring(12); switch (riteType) { case "Flame": dmgTypes.Add("Fire"); break; case "Frozen": dmgTypes.Add("Cold"); break; case "Ruined": dmgTypes.Add("Acid"); break; case "Storm": dmgTypes.Add("Lightning"); break; } primalRites.Remove(newRite); } else { index = CLIHelper.PrintChoices(msg, esotericRites); string newRite = esotericRites[index].Substring(12); switch (newRite) { case "Dead": dmgTypes.Add("Necrotic"); break; case "Oracle": dmgTypes.Add("Psychic"); break; case "Roar": dmgTypes.Add("Thunder"); break; } } } string riteDmg = String.Join(", ", dmgTypes); character.ClassFeatures.Add("Hunter's Bane", "adv on Survival to track and Int to recall info about Fey, Fiends, and Undead" + "\ncan't be surprised by creature type while tracking that type, can only track 1 type at a time"); character.ClassFeatures.Add("Crimson Rite", $"bonus, reduce max HP by lvl, dmg + 1D{dmg} of 1 type, dmg type(s) = {riteDmg}"); if (lvl >= 2) { string fightStyleMsg = "Pick a fighting style."; List <string> styleList = new List <string> { "Archery", "Blind Fighting", "Dueling", "Great Weapon Fighting", "Two-Weapon Fighting" }; string fightStyle = CLIHelper.PrintChoices(Options.FightingStyles, styleList, fightStyleMsg); string fightStyleKey = $"Fighting Style({fightStyle})"; string fightStyleValue = Options.FightingStyles[fightStyle]; character.ClassFeatures.Add(fightStyleKey, fightStyleValue); } if (lvl >= 3) { msg = "Pick a Bloodhunter Order that will give you features at levels 3, 7, 10, 15, and 18."; var archetypes = new List <string> { "Order of the Ghostslayer", "Order of the Mutant", "Order of the Profane Soul" }; int answer = CLIHelper.PrintChoices(msg, archetypes); BloodhunterOrder = archetypes[answer].Substring(13); switch (BloodhunterOrder) { case "Ghostslayer": Ghostslayer(character); break; case "Mutant": Mutant(character); break; case "Profane Soul": ProfaneSoul(character); break; } } if (lvl >= 4) { character.ClassFeatures.Add("Hunter's Versatility", "When you gain an Ability Score Improvement, replace a Fighting Style or a Crimson Rite option"); } if (lvl >= 5) { character.ClassFeatures.Add("Extra Attack", "When using an atk action, atk twice"); } if (lvl >= 6) { int cursesKnown = 2; int curseUses = 2; for (int i = 10; i <= lvl; i += 4) { cursesKnown++; } for (int i = 11; i <= lvl; i += 6) { curseUses++; } Options.BloodCurses.Add("Blood Curse of the Transfusion", $"bonus, 30ft, 1 ally, take {curseUses}D6 dmg to heal ally HP = dmg" + $"\n Amplified - 1 Hitdie, healing + (Wis x 2)"); var bloodCurses = new List <string>(); foreach (var item in Options.BloodCurses.Keys) { bloodCurses.Add(item); } character.ClassFeatures.Add("Blood Maledict", $"{curseUses}/SR, target must have blood, creatures can only have 1 curse at a time, you know {cursesKnown} Blood Curse options"); for (int i = 0; i < cursesKnown; i++) { string newCurse = CLIHelper.PrintChoices(Options.BloodCurses, bloodCurses, "Pick a Blood Curse option"); character.ClassFeatures["Blood Maledict"] += $"\n{newCurse}({Options.BloodCurses[newCurse]})"; bloodCurses.Remove(newCurse); } } if (lvl >= 9) { character.ClassFeatures.Add("Grim Psychometry", "meditate for 10 min, Wis check, learn dark events/sinister purpose of an object touched by evil"); } if (lvl >= 11) { character.ClassFeatures["Hunter's Bane"] = "gain adv on Insight and Intimidation"; character.ClassFeatures.Add("Dark Velocity", "speed +10ft, op atks against you suffer disadv"); character.Speed += 10; } if (lvl >= 14) { character.ClassFeatures.Add("Hardened Soul", "gain Immunity to fear, gain adv vs charm"); } if (lvl >= 17) { character.ClassFeatures.Add("Enduring Form", "1/turn, 2 Hitdie, reroll death save"); } if (lvl >= 20) { character.ClassFeatures.Add("Sanguine Mastery", "Crimson Rite no longer reduces max HP, if HP < 1/4 max HP - all Crimson Rite dmg is maximized"); } }
public static void Features(Character character) { int lvl = character.Lvl; var tuple = DeterminePowerPts(lvl); int pts = tuple.Item1; int maxLvl = tuple.Item2; character.ClassFeatures.Add("Power Points", $"you have {pts} pts and you can cast up to {maxLvl} lvl spells(uses spell pts by lvl chart DMG pg 289)" + $"\n there's a limit on how many times you can cast certain spell lvls, casting at higher lvls - pay pts = spell's new lvl, pt costs for spells below" + $"\n 1st = 2pts(no limit) 4th = 6pts(5/LR) 7th = 10pts(2/LR)" + $"\n 2nd = 3pts(no limit) 5th = 7pts(5/LR) 8th = 11pts(1/LR)" + $"\n 3rd = 5pts(no limit) 6th = 9pts(2/LR) 9th = 13pts(1/LR)"); character.ClassFeatures.Add("Spellcasting Description", "Instead of arcane magic, you channel psionic energy to 'cast' your powers/spells" + "\n Some say psions are harnessing the energy of the Astral Plane, others think psions create psionic energy from their minds" + "\n When you use a summoning spell, the creature has the appearance of a silver Astral Construct(solidified ectoplasm)" + "\n Psychokinetic spells or atk spells are examples of you manipulating the form of your psionic energy to create various mental blasts" + "\n Because the body is an extension of the mind, psychometabolism spells allow you to manipulate its form, abilites and heal" + "\n Spells that involve 'your god' ignore that aspect of the spell, psions can be religious but it isn't necessary for their powers/spells"); switch (character.Archetype) { case "Clairsentience(Seer)": Clairsentience(character); break; case "Metacreativity(Shaper)": Metacreativity(character); break; case "Psychokinesis(Savant)": Psychokinesis(character); break; case "Psychometabolism(Egoist)": Psychometabolism(character); break; case "Psychoportation(Nomad)": Psychoportation(character); break; case "Telepathy(Telepath)": Telepathy(character); break; } if (lvl >= 2) { int psionicDie = 6; for (int i = 0; i <= lvl; i++) { if (i == 5 || i == 10 || i == 15) { psionicDie += 2; } } string cmbMode = ""; string msg = ""; var psionicDict = GetPsionicModes(psionicDie, CastingStat); var modesList = new List <string>(); foreach (var item in psionicDict.Keys) { modesList.Add(item); } int options = 2; for (int i = 10; i <= lvl; i += 7) { options++; } character.ClassFeatures.Add($"Psionic Combat Modes(D{psionicDie})", $"{CastingStat}/LR, reaction, 60ft, 1 creature, you have {options} modes"); for (int i = 0; i < options; i++) { if (i == 0) { msg = "You get 2 Psionic Combat Modes of your choice"; } else { msg = "Pick a new Psionic Combat Mode option"; } cmbMode = CLIHelper.PrintChoices(psionicDict, modesList, msg); modesList.Remove(cmbMode); character.ClassFeatures["Psionic Combat Modes(D{psionicDie})"] += $"\n {cmbMode}({psionicDict[cmbMode]})"; } } if (lvl >= 4) { character.ClassFeatures.Add("Psionic Versatility", "When you get an Ability Score Improvement, you can replace a Psionic Combat Mode option or Psion cantrip"); } if (lvl >= 5) { character.ClassFeatures.Add("Astral Guidance", "expend 1 Psionic Combat Mode use, when you fail a check, reroll the check, must use new roll"); } if (lvl >= 20) { character.ClassFeatures.Add("Superior Psionic Combat", "on Init, if you have no Psionic Combat Mode uses - regain 1 use"); } Spells(character); }
public static void Base(Character character) { string msg = "Pick a type of Discipline that will determine your skill list, saves and give you features at levels 1, 6, and 14."; var archetype = new List <string> { "Clairsentience(Seer)", "Metacreativity(Shaper)", "Psychokinesis(Savant)", "Psychometabolism(Egoist)", "Psychoportation(Nomad)", "Telepathy(Telepath)" }; int input = CLIHelper.PrintChoices(msg, archetype); character.Archetype = archetype[input]; var classSkills = new List <string>(); switch (character.Archetype) { case "Clairsentience(Seer)": classSkills = new List <string> { "Arcana", "History", "Insight", "Investigation", "Nature", "Perception", "Religion" }; character.Saves.Add("Int"); character.Saves.Add("Wis"); break; case "Metacreativity(Shaper)": classSkills = new List <string> { "Animal Handling", "Arcana", "Insight", "Nature", "Persuasion", "Religion", "Stealth" }; character.Saves.Add("Wis"); character.Saves.Add("Cha"); break; case "Psychokinesis(Savant)": classSkills = new List <string> { "Arcana", "Athletics", "Deception", "Intimidation", "Perception", "Survival" }; character.Saves.Add("Con"); character.Saves.Add("Cha"); break; case "Psychometabolism(Egoist)": classSkills = new List <string> { "Acrobatics", "Athletics", "Intimidation", "Perception", "Performance", "Sleight of Hand", "Stealth" }; character.Saves.Add("Str"); character.Saves.Add("Con"); break; case "Psychoportation(Nomad)": classSkills = new List <string> { "Acrobatics", "Athletics", "History", "Investigation", "Nature", "Perception", "Survival" }; character.Saves.Add("Dex"); character.Saves.Add("Int"); break; case "Telepathy(Telepath)": classSkills = new List <string> { "Arcana", "Deception", "Insight", "Intimidation", "Investigation", "Persuasion", "Stealth" }; character.Saves.Add("Wis"); character.Saves.Add("Cha"); break; } character.GP += 75; character.HitDie = 6; character.Proficiencies.Add("Daggers"); character.Proficiencies.Add("Darts"); character.Proficiencies.Add("Slings"); character.Proficiencies.Add("Quarterstaffs"); character.Proficiencies.Add("Light crossbows"); BEHelper.GetSkills(character, classSkills, 2); }
public void LoadGeneralConfigurations(string content, CLIHelper cliHelper) { cliHelper.ShowAutoRunWindow = true; // // default is true to keep backward compatibility using (System.IO.StringReader reader = new System.IO.StringReader(content)) { string arg; while ((arg = reader.ReadLine()) != null) { int i = arg.IndexOf('='); string param = arg.Substring(0, i).Trim(); string value = arg.Substring(i + 1).Trim(); switch (param) { case "SourceControlType": cliHelper.SetSourceControlType(value); break; case "SourceControlUrl": cliHelper.SetSourceControlURL(value); break; case "SourceControlUser": cliHelper.SetSourceControlUser(value); break; case "SourceControlPassword": cliHelper.SetSourceControlPassword(value); break; case "PasswordEncrypted": cliHelper.PasswordEncrypted(value); break; case "SourceControlProxyServer": cliHelper.SourceControlProxyServer(value); break; case "SourceControlProxyPort": cliHelper.SourceControlProxyPort(value); break; case "Solution": case "solution": cliHelper.Solution = value; break; case "ShowAutoRunWindow": // Support old style case "showui": // TODO: use CLIOptionClassHelper.GetAttrLongName<RunOptions>(nameof(RunOptions.ShowUI)): cliHelper.ShowAutoRunWindow = bool.Parse(value); break; case "artifacts-path": cliHelper.TestArtifactsFolder = value; break; //default: // Reporter.ToLog(eLogLevel.ERROR, "Unknown argument: '" + param + "'"); // throw new ArgumentException("Unknown argument", param); } } } }
private static void Run(string[] args) { Mutex mutex = null; try { mutex = new Mutex(false, @"Global\82E6AC09-0FEF-4390-AD9F-0DD3F5561EFC"); // Required for installer IsSilentRun = CLIHelper.CheckArgs(args, "silent", "s"); IsSandbox = CLIHelper.CheckArgs(args, "sandbox"); if (!IsSandbox) { IsPortable = CLIHelper.CheckArgs(args, "portable", "p"); if (IsPortable) { CustomPersonalPath = PortablePersonalPath; } else { CheckPersonalPathConfig(); } if (!string.IsNullOrEmpty(PersonalPath) && !Directory.Exists(PersonalPath)) { Directory.CreateDirectory(PersonalPath); } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); DebugHelper.WriteLine("{0} started", Title); DebugHelper.WriteLine("Operating system: " + Environment.OSVersion.VersionString); DebugHelper.WriteLine("Command line: " + Environment.CommandLine); DebugHelper.WriteLine("Personal path: " + PersonalPath); SettingsResetEvent = new ManualResetEvent(false); UploaderSettingsResetEvent = new ManualResetEvent(false); HotkeySettingsResetEvent = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(state => LoadSettings()); DebugHelper.WriteLine("MainForm init started"); MainForm = new MainForm(); DebugHelper.WriteLine("MainForm init finished"); if (Settings == null) { SettingsResetEvent.WaitOne(); } Application.Run(MainForm); if (WatchFolderManager != null) { WatchFolderManager.Dispose(); } SaveSettings(); BackupSettings(); DebugHelper.WriteLine("ShareX closing"); DebugHelper.Logger.SaveLog(LogFilePath); } finally { if (mutex != null) { mutex.Close(); } } }
public void DynamicRunetExecutionTest() { //Arrange ObservableList <BusinessFlow> bfList = SR.GetAllRepositoryItems <BusinessFlow>(); BusinessFlow BF1 = bfList[0]; ObservableList <Activity> activityList = BF1.Activities; Activity activity = activityList[0]; BF1.Active = true; GingerRunner mGRForRunset = new GingerRunner(); mGRForRunset.Name = "Test Runner"; Agent a = new Agent(); a.DriverType = Agent.eDriverType.SeleniumChrome; mGRForRunset.SolutionAgents = new ObservableList <Agent>(); mGRForRunset.SolutionAgents.Add(a); mGRForRunset.ApplicationAgents.Add(new ApplicationAgent() { AppName = "SCM", Agent = a }); mGRForRunset.SolutionApplications = new ObservableList <ApplicationPlatform>(); mGRForRunset.SolutionApplications.Add(new ApplicationPlatform() { AppName = "SCM", Platform = ePlatformType.Web, Description = "New application" }); mGRForRunset.BusinessFlows.Add(BF1); WorkSpace.Instance.SolutionRepository = SR; mGRForRunset.SpecificEnvironmentName = environment.Name; mGRForRunset.UseSpecificEnvironment = false; RunSetConfig runSetConfig1 = new RunSetConfig(); mGRForRunset.IsUpdateBusinessFlowRunList = true; runSetConfig1.GingerRunners.Add(mGRForRunset); runSetConfig1.UpdateRunnersBusinessFlowRunsList(); runSetConfig1.mRunModeParallel = false; RunSetActionHTMLReport produceHTML2 = CreateProduceHTMlOperation(); runSetConfig1.RunSetActions.Add(produceHTML2); RunsetExecutor GMR1 = new RunsetExecutor(); GMR1.RunsetExecutionEnvironment = environment; GMR1.RunSetConfig = runSetConfig1; WorkSpace.Instance.RunsetExecutor = GMR1; CLIHelper cLIHelper1 = new CLIHelper(); cLIHelper1.RunAnalyzer = false; cLIHelper1.ShowAutoRunWindow = false; cLIHelper1.DownloadUpgradeSolutionFromSourceControl = false; RunSetAutoRunConfiguration autoRunConfiguration1 = new RunSetAutoRunConfiguration(solution, GMR1, cLIHelper1); CLIDynamicFile mCLIDynamicXML1 = new CLIDynamicFile(CLIDynamicFile.eFileType.XML); autoRunConfiguration1.SelectedCLI = mCLIDynamicXML1; String xmlFile = autoRunConfiguration1.SelectedCLI.CreateConfigurationsContent(solution, GMR1, cLIHelper1); autoRunConfiguration1.CreateContentFile(); CLIProcessor cLIProcessor = new CLIProcessor(); string[] args = new string[] { autoRunConfiguration1.SelectedCLI.Verb, "--" + CLIOptionClassHelper.FILENAME, autoRunConfiguration1.ConfigFileFullPath }; //Act cLIProcessor.ExecuteArgs(args); //Assert string path = TestResources.GetTestResourcesFolder(@"Solutions" + Path.DirectorySeparatorChar + "BasicSimple" + Path.DirectorySeparatorChar + "Reports" + Path.DirectorySeparatorChar + "Reports"); Assert.IsTrue(Directory.Exists(path)); }
public static void Base(Character character) { character.RacialTraits.Add("Powerful Build: count as Large for carry capacity, etc"); character.RacialTraits.Add("Godly Strength: adv on Str checks"); character.RacialTraits.Add("Godly Protection: +2 AC"); character.RacialTraits.Add("Divine Intervention: LR, gain adv on atk, save, or ability check"); character.MinHeight = 60; character.MaxHeight = 78; character.MinWeight = 100; character.MaxWeight = 300; character.Speed += 40; character.Vision = "Darkvision 60ft"; character.AlignmentOptions.Add("N-G"); character.AlignmentOptions.Add("C-G"); character.AlignmentOptions.Add("C-N"); character.AdultAge = 30; character.MaxAgeStart = 800; character.MaxAgeEnd = 1200; character.Languages.Add("Celestial"); BEHelper.AddLanguage(character, "race"); int index = -1; switch (character.DemigodDomain) { case "Beauty": character.RacialTraits.Add("Child of Love: impose disadv vs Enchantment spells"); character.RacialTraits.Add("Compelling Beauty: bonus, Cha save, disadv on atks, if attempt to move away from you Cha save"); character.Cantrips.Add("Friends(Cha to cast)"); character.SkillProficiencies.Add("Deception"); character.SkillProficiencies.Add("Persuasion"); break; case "Knowledge": character.RacialTraits.Add("Child of Wisdom: gain 1 skill, 1 tool, and Expertise in 1 skill"); character.RacialTraits.Add("Wit Without Measure: adv on all Int-based DCs"); character.Cantrips.Add("Guidance(Int to cast)"); index = CLIHelper.PrintChoices("Pick a skill", Options.Skills); character.SkillProficiencies.Add(Options.Skills[index]); BEHelper.GetTool(character); break; case "Life": character.RacialTraits.Add("Child of Life: healing spells heal extra HP = Wis"); character.RacialTraits.Add("Refute Death: LR, 30ft, you or ally auto-succeeds on 1 death save"); character.Cantrips.Add("Spare the Dying(Wis to cast)"); break; case "Luck": character.RacialTraits.Add("Child of Luck: Cha/LR, add 1D6 to any atk, save, or ability check"); character.RacialTraits.Add("Auspicious Dodge: LR, reaction, when hit - cause atk to miss"); character.RacialTraits.Add("Favored Attack: LR, on hit, cause atk to crit"); character.RacialTraits.Add("Prosperous Life: whenever you find treasure or try to sell goods, increase its value by 30%"); break; case "Madness": character.RacialTraits.Add("Child of Madness: auto-succeed on all Con checks for drinking, gain Immunity to charm, fear, and poison"); character.RacialTraits.Add("Party Starter: Cha check in social area, gain adv on all Cha-based DCs for 2hr"); character.SkillProficiencies.Add("Acrobatics"); character.SkillProficiencies.Add("Persuasion"); character.Cantrips.Add("Create Bonfire(Cha to cast)"); character.Cantrips.Add("Dancing Lights(Cha to cast)"); break; case "Music": character.RacialTraits.Add("Child of Music: creatures with Int 8 or less are charmed by music"); character.RacialTraits.Add("Devastating Notes: SR, Cha save, 30ft, all hostiles, 1 min, disadv on atks and saves"); character.SkillProficiencies.Add("Performance"); character.ToolProficiencies.Add("All instruments"); character.Cantrips.Add("Vicious Mockery(Cha to cast)"); break; case "Protection": character.RacialTraits.Add("Child of Protection: Dodge as a bonus, +2 HP/lvl"); character.RacialTraits.Add("Experienced Knight: gain the Protection fighting style"); character.SkillProficiencies.Add("Athletics"); character.Proficiencies.Add("All armor and shields"); character.Cantrips.Add("Blade Ward(Cha to cast)"); break; case "Smithing": character.RacialTraits.Add("Child of Creation: LR, create an object of any combination of wood, stone, iron, crystal, rope, or cloth" + "The object must smaller than a 5ft cube, and the object must be in a form that you have seen before"); character.RacialTraits.Add("Child of the Forge: gain Immunity to Fire, adv on all tool checks you're prof in"); character.ToolProficiencies.Add("Carpenter's Tools"); character.ToolProficiencies.Add("Cobbler's Tools"); character.ToolProficiencies.Add("Mason's Tools"); character.ToolProficiencies.Add("Smith's Tools"); character.ToolProficiencies.Add("Tinker's Tools"); character.Cantrips.Add("Sword Burst(Wis to cast)"); break; case "The Earth": character.RacialTraits.Add("Child of Nature: 30ft, create difficult terrain made of foliage, Str save or be restrained"); character.RacialTraits.Add("Earth Control: LR, cast Stoneshape or Wall of Stone"); character.SkillProficiencies.Add("Nature"); character.Cantrips.Add("Druidcraft(Wis to cast)"); break; case "The Hunt": character.RacialTraits.Add("Child of the Hunt: adv on Survival, identify creatures from tracks"); character.RacialTraits.Add("Hunter's Eyes: gain Superior Darkvision 120ft, 1/SR - cast Detect Poison and Disease"); character.Vision = "Superior Darkvision 120ft"; character.RacialTraits.Add("Godly Precision: +2 to atk/dmg with ranged wep"); character.SkillProficiencies.Add("Survival"); character.Proficiencies.Add("All ranged weapons"); character.Cantrips.Add("Thorn Whip(Wis to cast)"); break; case "The Sea": character.RacialTraits.Add("Child of the Sea: waterbreathing, swim 40ft"); character.RacialTraits.Add("Caress of the Ocean: gain regen = 1/4 lvl while in water"); character.Cantrips.Add("Shape Water(Int to cast)"); break; case "The Sky": character.RacialTraits.Add("Child of the Sky: gain Resistance Thunder and Lightning"); character.RacialTraits.Add("Lightning Wielder: +2 to atk/dmg while unarmed, 1/LR - Cha spell atk, range 30/120, 4D8 + Cha Lightning dmg"); character.Cantrips.Add("Gust(Cha to cast)"); break; case "The Sun": character.RacialTraits.Add("Child of the Sun: during the day, gain +2 Str, Dex, Con/at night, gain -2 Str, Dex, Con"); character.RacialTraits.Add("Solar Burst: LR, Con save - 30ft, 5D8 Radiant dmg, Con save - blindness"); character.Cantrips.Add("Light(Cha to cast)"); break; case "Travel": character.RacialTraits.Add("Child of Travel: move speed +10ft"); character.Speed += 50; character.RacialTraits.Add("Fast Travel: LR, cast Teleport"); character.Cantrips.Add("Message(Wis to cast)"); break; case "Trickery": character.RacialTraits.Add("Child of Shadows: adv with Stealth and Thieves' Tools"); character.SkillProficiencies.Add("Deception"); character.SkillProficiencies.Add("Sleight of Hand"); character.SkillProficiencies.Add("Stealth"); character.ToolProficiencies.Add("Thieves' Tools"); character.Cantrips.Add("Minor Illusion(Int to cast)"); break; case "Undead": character.RacialTraits.Add("Child of Death: gain Resistance to Necrotic, Superior Darkvision 120ft"); character.Vision = "Superior Darkvision 120ft"; character.RacialTraits.Add("Undead Affinity: SR, action, conjure 3 skeletons or zombies"); character.Cantrips.Add("Toll the Dead - Int or Wis to cast"); break; case "War": character.RacialTraits.Add("Child of War: can't be surprised, +5 on Init, use Str for Intimiation"); character.RacialTraits.Add("Aura of War: LR, 30ft, Con save, fear and prone, you and allies gain Str temp HP"); character.RacialTraits.Add("Godly Precision: +2 atk/dmg with melee"); character.Proficiencies.Add("All weapons and armor"); break; } }
private static void Run() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); IsSilentRun = CLIHelper.CheckArgs(Arguments, "silent", "s"); IsSandbox = CLIHelper.CheckArgs(Arguments, "sandbox"); if (!IsSandbox) { IsPortable = CLIHelper.CheckArgs(Arguments, "portable", "p"); if (IsPortable) { CustomPersonalPath = PortablePersonalPath; } else { CheckPersonalPathConfig(); } if (!Directory.Exists(PersonalPath)) { try { Directory.CreateDirectory(PersonalPath); } catch (Exception e) { MessageBox.Show("Unable to create folder: \"" + PersonalPath + "\"\r\n\r\n" + e.ToString(), "ShareX - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); CustomPersonalPath = ""; } } } DebugHelper.WriteLine("{0} started", Title); DebugHelper.WriteLine("Operating system: " + Environment.OSVersion.VersionString); DebugHelper.WriteLine("Command line: " + Environment.CommandLine); DebugHelper.WriteLine("Personal path: " + PersonalPath); string gitHash = GetGitHash(); if (!string.IsNullOrEmpty(gitHash)) { DebugHelper.WriteLine("Git: https://github.com/ShareX/ShareX/tree/" + gitHash); } LoadProgramSettings(); UploaderSettingsResetEvent = new ManualResetEvent(false); HotkeySettingsResetEvent = new ManualResetEvent(false); TaskEx.Run(() => LoadSettings()); LanguageHelper.ChangeLanguage(Settings.Language); DebugHelper.WriteLine("MainForm init started"); MainForm = new MainForm(); DebugHelper.WriteLine("MainForm init finished"); Application.Run(MainForm); if (WatchFolderManager != null) { WatchFolderManager.Dispose(); } SaveSettings(); BackupSettings(); DebugHelper.WriteLine("ShareX closing"); DebugHelper.Logger.SaveLog(LogsFilePath); }
private static void Run(string[] args) { string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); using (Mutex mutex = new Mutex(false, appGuid)) // Required for installer { IsSilentRun = CLIHelper.CheckArgs(args, "silent", "s"); IsSandbox = CLIHelper.CheckArgs(args, "sandbox"); if (!IsSandbox) { IsPortable = CLIHelper.CheckArgs(args, "portable", "p"); if (IsPortable) { CustomPersonalPath = PortablePersonalPath; } else { CheckPersonalPathConfig(); } if (!string.IsNullOrEmpty(PersonalPath) && !Directory.Exists(PersonalPath)) { Directory.CreateDirectory(PersonalPath); } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); DebugHelper.WriteLine("{0} started", Title); DebugHelper.WriteLine("Operating system: " + Environment.OSVersion.VersionString); DebugHelper.WriteLine("Command line: " + Environment.CommandLine); DebugHelper.WriteLine("Personal path: " + PersonalPath); SettingsResetEvent = new ManualResetEvent(false); UploaderSettingsResetEvent = new ManualResetEvent(false); HotkeySettingsResetEvent = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(state => LoadSettings()); DebugHelper.WriteLine("MainForm init started"); MainForm = new MainForm(); DebugHelper.WriteLine("MainForm init finished"); if (Settings == null) { SettingsResetEvent.WaitOne(); } Application.Run(MainForm); if (WatchFolderManager != null) { WatchFolderManager.Dispose(); } SaveSettings(); BackupSettings(); DebugHelper.WriteLine("ShareX closing"); DebugHelper.Logger.SaveLog(LogsFilePath); } }
private static async Task executeEC2(string[] args, Credentials credentials) { var nArgs = CLIHelper.GetNamedArguments(args); var ec2 = new EC2Helper(); var iam = new IAMHelper(credentials); switch (args[1]) { case "create-instance": { var imageId = nArgs["image"]; var keyName = nArgs["key"]; var instanceType = nArgs["instance-type"].ToEnum <InstanceModel>().ToInstanceType(); var securityGroupId = nArgs["security-group"]; var subnet = nArgs["subnet"]; var role = nArgs["role"]; var shutdownTermination = nArgs.GetValueOrDefault("on-shutdown-termination").ToBoolOrDefault(false); var publicIp = nArgs.GetValueOrDefault("public-ip").ToBoolOrDefault(true); var name = nArgs["name"]; var autoKill = nArgs.GetValueOrDefault("auto-kill").ToIntOrDefault(100 * 365 * 24 * 60); var tt = DateTime.UtcNow.AddMinutes(autoKill); var tt2 = tt.AddMinutes(15); var tags = new System.Collections.Generic.Dictionary <string, string>() { { "Name", name }, { "Auto Kill", $"{tt.Minute}-{tt2.Minute} {tt.Hour}-{tt2.Hour} {tt.Day}-{tt2.Day} {tt.Month}-{tt2.Month} * {tt.Year}-{tt2.Year}" }, }; var cname = nArgs.GetValueOrDefault("cname"); var zones = nArgs.GetValueOrDefault("zones")?.Split(',')?.ToArray(); if (cname != null && zones != null) { for (int i = 0; i < zones.Length; i++) { var suffix = i > 0 ? $" {i + 1}" : ""; tags.Add($"Route53 Enable{suffix}", "true"); tags.Add($"Route53 Name{suffix}", cname); tags.Add($"Route53 Zone{suffix}", zones[i]); } } string instanceId; var ebsOptymalized = nArgs.GetValueOrDefault("ebs-optymalized").ToBoolOrDefault(); if (nArgs.Any(x => x.Key.IsWildcardMatch("ebs-root-"))) { Console.WriteLine("Advanced Instance Creation Initiated..."); var rootDeviceName = nArgs["ebs-root-dev-name"]; var rootSnapshotId = nArgs.GetValueOrDefault("ebs-root-snapshot-id"); var rootVolumeSize = nArgs["ebs-root-volume-size"].ToInt32(); var rootIOPS = nArgs["ebs-root-iops"].ToIntOrDefault(0); var rootVolumeType = nArgs["ebs-root-volume-type"]; instanceId = ec2.CreateInstanceAsync( imageId: imageId, instanceType: instanceType, keyName: keyName, securityGroupIDs: new string[] { securityGroupId }, subnetId: subnet, roleName: role, shutdownBehavior: shutdownTermination ? ShutdownBehavior.Terminate : ShutdownBehavior.Stop, associatePublicIpAddress: publicIp, ebsOptymalized: ebsOptymalized, rootDeviceName: rootDeviceName, rootSnapshotId: rootSnapshotId, rootVolumeSize: rootVolumeSize, rootIOPS: rootIOPS, rootVolumeType: rootVolumeType, tags: tags ).Result.Reservation.Instances.Single().InstanceId; } else { Console.WriteLine("Basic Instance Creation Initiated..."); instanceId = ec2.CreateInstanceAsync( imageId: imageId, instanceType: instanceType, keyName: keyName, securityGroupId: securityGroupId, subnetId: subnet, roleName: role, shutdownBehavior: shutdownTermination ? ShutdownBehavior.Terminate : ShutdownBehavior.Stop, associatePublicIpAddress: publicIp, ebsOptymalized: ebsOptymalized, tags: tags).Result.Reservation.Instances.Single().InstanceId; } if (nArgs.GetValueOrDefault("await-start").ToBoolOrDefault(false)) { var timeout_ms = nArgs.GetValueOrDefault("await-start-timeout").ToIntOrDefault(5 * 60 * 1000); Console.WriteLine($"Awaiting up to {timeout_ms} [ms] for instance '{instanceId}' to start..."); ec2.AwaitInstanceStateCode(instanceId, EC2Helper.InstanceStateCode.running, timeout_ms: timeout_ms).Wait(); } if (nArgs.GetValueOrDefault("await-system-start").ToBoolOrDefault(false)) { var timeout_ms = nArgs.GetValueOrDefault("await-system-start-timeout").ToIntOrDefault(5 * 60 * 1000); Console.WriteLine($"Awaiting up to {timeout_ms} [ms] for instance '{instanceId}' OS to start..."); ec2.AwaitInstanceStatus(instanceId, EC2Helper.InstanceSummaryStatus.Ok, timeout_ms: timeout_ms).Wait(); } Console.WriteLine($"SUCCESS, Instance '{instanceId}' was created."); } ; break; case "terminate-instance": { var name = nArgs.GetValueOrDefault("name"); Instance[] instances = null; if (!name.IsNullOrEmpty()) { instances = ec2.ListInstancesByName(name).Result; Console.WriteLine($"Found {instances?.Length ?? 0} instances with name: '{name}'."); } else { throw new Exception("Not Supported Arguments"); } instances.ParallelForEach(i => { void TryRemoveTags() { if (!nArgs.GetValueOrDefault("try-delete-tags").ToBoolOrDefault(false)) { return; } var err = ec2.DeleteAllInstanceTags(i.InstanceId).CatchExceptionAsync().Result; if (err == null) { Console.WriteLine("Removed instance tags."); } else { Console.WriteLine($"Failed to remove instance tags, Error: {err.JsonSerializeAsPrettyException()}"); } } if (i.State.Code == (int)InstanceStateCode.terminating || i.State.Code == (int)InstanceStateCode.terminated) { Console.WriteLine($"Instance {i.InstanceId} is already terminating or terminated."); TryRemoveTags(); return; } Console.WriteLine($"Terminating {i.InstanceId}..."); var result = ec2.TerminateInstance(i.InstanceId).Result; Console.WriteLine($"Instance {i.InstanceId} state changed {result.PreviousState.Name} -> {result.CurrentState.Name}"); TryRemoveTags(); }); Console.WriteLine($"SUCCESS, All Instances Are Terminated."); } ; break; case "describe-instance": { var name = nArgs.GetValueOrDefault("name"); Instance instance = null; if (name != null) { instance = ec2.ListInstancesByName(name: name).Result .SingleOrDefault(x => (x.State.Name != InstanceStateName.Terminated) && (x.State.Name != InstanceStateName.ShuttingDown)); if (instance == null) { throw new Exception($"No non terminated instance with name '{name}' was found."); } var property = nArgs.GetValueOrDefault("property"); var output = nArgs.GetValueOrDefault("output"); if (!property.IsNullOrEmpty()) { var value = instance.GetType().GetProperty(property).GetValue(instance, null); var strValue = TypeEx.IsSimple(value.GetType().GetTypeInfo()) ? value.ToString() : value.JsonSerialize(Newtonsoft.Json.Formatting.Indented); Console.WriteLine($"Instance '{instance.InstanceId}' Property '{property}', Value: '{strValue}'."); if (!output.IsNullOrEmpty()) { Console.WriteLine($"Saving Property Value into output file: '{output}'..."); output.ToFileInfo().WriteAllText(strValue); } } else { Console.WriteLine($"Instance '{instance.InstanceId}' properties: {instance.JsonSerialize(Newtonsoft.Json.Formatting.Indented)}"); if (!output.IsNullOrEmpty()) { Console.WriteLine($"Saving Properties into output file: '{output}'..."); output.ToFileInfo().WriteAllText(instance.JsonSerialize(Newtonsoft.Json.Formatting.Indented)); } } } else { throw new Exception("Only describe property by name option is available."); } Console.WriteLine($"SUCCESS, instance '{instance.InstanceId}' properties were found."); } ; break; case "help": case "--help": case "-help": case "-h": case "h": HelpPrinter($"{args[0]}", "Amazon Elastic Compute Cloud", ("create-instance", "Accepts params: "), ("terminate-instance", "Accepts params: name")); break; default: { Console.WriteLine($"Try '{args[0]} help' to find out list of available commands."); throw new Exception($"Unknown EC2 command: '{args[0]} {args[1]}'"); } } }
private static void executeHash(string[] args) { var nArgs = CLIHelper.GetNamedArguments(args); void Verify(string verify, string hash, string hash_type) { var verifiers = new List <string>(); if (verify.ContainsAny(".", "/", "\\", "json") && File.Exists(verify)) { WriteLine("Determined that verify argument is a file, extracting hash whitelist string array..."); var fi = verify.ToFileInfo(); var arr = fi.ReadAllText()?.JsonDeserialize <string[]>(); WriteLine($"Success, found '{arr?.Length ?? 0}' hashes within '{fi.FullName}' file."); verifiers.AddRange(arr); } else { verifiers.Add(verify); } if (verifiers.Any(x => x != "*" && !x.IsNullOrEmpty() && hash.HexEquals(x))) { WriteLine($"{hash_type} Hash Verification Succeeded"); } else { WriteLine($"{hash_type} Hash Verification Failed"); var err_message = $"{hash_type} Hash Verification failed, expected one of: '{verifiers?.JsonSerialize()}', but was: '{hash}'."; if (verifiers.Any(x => x == "*")) { WriteLine($"WARNING!!! Hash wildcard was present, following error will not be thrown: {err_message}"); } else { throw new Exception(err_message); } } } switch (args[1]?.ToLower()) { case "sha256": { var path = (nArgs.FirstOrDefault(x => x.Key.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "p", "path")).Value ?? args[2]); string hash; var excludeRootName = nArgs.Keys.Any(k => k.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "x", "exclude-root-name")); if (Directory.Exists(path)) { var di = path.ToDirectoryInfo(); var recursive = nArgs.Keys.Any(k => k.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "r", "recursive")); var ignore = nArgs.GetFirstValueOrDefault("i", "ignore")?.Split(",") ?? new string[] { }; WriteLine($"Directory verificarion started, Path: {di.FullName}, Exclude Root Name: {excludeRootName}, Recursive: {recursive}, Ignore {ignore.JsonSerialize()}"); hash = HashHelper.SHA256(di, excludeRootName: excludeRootName, recursive: recursive, encoding: Encoding.UTF8, ignore: ignore).Result.ToHexString(); } else if (File.Exists(path)) { var fi = path.ToFileInfo(); WriteLine($"File verificarion started, Path: {fi.FullName}, Exclude Name: {excludeRootName}"); if (excludeRootName) { hash = HashHelper.SHA256(fi).ToHexString(); } else { hash = HashHelper.SHA256(fi, Encoding.UTF8).ToHexString(); } } else { throw new Exception($"Can't hash path '{path}' because it does not exist."); } var verify = nArgs.FirstOrDefault(kvp => kvp.Key.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "v", "verify") && !kvp.Value.IsNullOrEmpty()); if (verify.Value != null) { Verify(verify.Value, hash, "SHA256"); } else { Console.Write(hash); } } break; case "md5": { var path = (nArgs.FirstOrDefault(x => x.Key.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "p", "path")).Value ?? args[2]); string hash; var excludeRootName = nArgs.Keys.Any(k => k.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "x", "exclude-root-name")); if (Directory.Exists(path)) { var di = path.ToDirectoryInfo(); var recursive = nArgs.Keys.Any(k => k.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "r", "recursive")); var ignore = nArgs.GetFirstValueOrDefault("i", "ignore")?.Split(",") ?? new string[] { }; WriteLine($"Directory verificarion started, Path: {di.FullName}, Exclude Root Name: {excludeRootName}, Recursive: {recursive}, Ignore {ignore.JsonSerialize()}"); hash = HashHelper.MD5(di, excludeRootName: excludeRootName, recursive: recursive, encoding: Encoding.UTF8, ignore: ignore).Result.ToHexString(); } else if (File.Exists(path)) { var fi = path.ToFileInfo(); WriteLine($"File verificarion started, Path: {fi.FullName}, Exclude Name: {excludeRootName}"); if (excludeRootName) { hash = HashHelper.MD5(fi).ToHexString(); } else { hash = HashHelper.MD5(fi, Encoding.UTF8).ToHexString(); } } else { throw new Exception($"Can't hash path '{path}' because it does not exist."); } var verify = nArgs.FirstOrDefault(kvp => kvp.Key.EquailsAny(StringComparison.InvariantCultureIgnoreCase, "v", "verify") && !kvp.Value.IsNullOrEmpty()); if (verify.Value != null) { Verify(verify.Value, hash, "MD5"); } else { Console.Write(hash); } } break; case "help": case "--help": case "-help": case "-h": case "h": HelpPrinter($"{args[0]}", "Hash Helper", ("SHA256", "Accepts params: [as first param] [p]ath='<dir/file>', [v]erify='0x<hex string>', Accepted Flags: [r]ecursive, e[x]clude-root-name, [i]gnore"), ("MD5", "Accepts params: [as first param] [p]ath='<dir/file>', [v]erify='0x<hex string>', Accepted Flags: [r]ecursive, e[x]clude-root-name, [i]gnore")); break; default: { Console.WriteLine($"Try '{args[0]} help' to find out list of available commands."); throw new Exception($"Unknown HASH command: '{args[0]} {args[1]}'"); } } }
public string CreateConfigurationsContent(Solution solution, RunsetExecutor runsetExecutor, CLIHelper cliHelper) { string sConfig = null; if (cliHelper.DownloadUpgradeSolutionFromSourceControl == true) { sConfig = "SourceControlType=" + solution.SourceControl.GetSourceControlType.ToString() + Environment.NewLine; if (solution.SourceControl.GetSourceControlType == SourceControlBase.eSourceControlType.SVN)//added for supporting Jenkins way of config creation- need to improve it { string modifiedURI = solution.SourceControl.SourceControlURL.TrimEnd(new char[] { '/' }); int lastSlash = modifiedURI.LastIndexOf('/'); modifiedURI = (lastSlash > -1) ? modifiedURI.Substring(0, lastSlash) : modifiedURI; sConfig += "SourceControlUrl=" + modifiedURI + Environment.NewLine; } else { sConfig += "SourceControlUrl=" + solution.SourceControl.SourceControlURL + Environment.NewLine; } if (solution.SourceControl.SourceControlUser != null && solution.SourceControl.SourceControlPass != null) { sConfig += "SourceControlUser="******"SourceControlPassword="******"PasswordEncrypted=" + "Y" + Environment.NewLine; } else { sConfig += "SourceControlUser=N/A" + Environment.NewLine; sConfig += "SourceControlPassword=N/A" + Environment.NewLine; } if (solution.SourceControl.GetSourceControlType == SourceControlBase.eSourceControlType.GIT) { if (solution.SourceControl.SourceControlProxyAddress != null && solution.SourceControl.SourceControlProxyAddress.ToLower().ToString() == "true") { sConfig += "SourceControlProxyServer=" + solution.SourceControl.SourceControlProxyAddress.ToString() + Environment.NewLine; sConfig += "SourceControlProxyPort=" + solution.SourceControl.SourceControlProxyPort.ToString() + Environment.NewLine; } } } sConfig += "solution=" + solution.Folder + Environment.NewLine; sConfig += "env=" + runsetExecutor.RunsetExecutionEnvironment.Name + Environment.NewLine; sConfig += "runset=" + runsetExecutor.RunSetConfig.Name + Environment.NewLine; sConfig += "analyze=" + cliHelper.RunAnalyzer.ToString() + Environment.NewLine; if (!string.IsNullOrEmpty(cliHelper.TestArtifactsFolder)) { sConfig += "artifacts-path=" + cliHelper.TestArtifactsFolder + Environment.NewLine; } //OLD sConfig += "ShowAutoRunWindow=" + cliHelper.ShowAutoRunWindow.ToString() + Environment.NewLine; sConfig += CLIOptionClassHelper.GetAttrLongName <RunOptions>(nameof(RunOptions.ShowUI)) + "=" + cliHelper.ShowAutoRunWindow.ToString() + Environment.NewLine; return(sConfig); }
public static Tuple <Dictionary <int, List <string> >, string> PickClassForSpells() { var result = new Dictionary <int, List <string> >(); string stat = ""; var classes = new List <string> { "Bard", "Cleric", "Druid", "Sorcerer", "Warlock", "Wizard" }; int index = CLIHelper.PrintChoices("Pick a class that will determine the spells you can gain", classes); string spellcastingClass = classes[index]; AllSpells spells = new AllSpells(spellcastingClass); switch (spellcastingClass) { case "Bard": foreach (var item in spells.Bard.Keys) { result.Add(item, spells.Bard[item]); } stat = "Cha"; break; case "Cleric": foreach (var item in spells.Cleric.Keys) { result.Add(item, spells.Cleric[item]); } stat = "Wis"; break; case "Druid": foreach (var item in spells.Druid.Keys) { result.Add(item, spells.Druid[item]); } stat = "Wis"; break; case "Sorcerer": foreach (var item in spells.Sorcerer.Keys) { result.Add(item, spells.Sorcerer[item]); } stat = "Cha"; break; case "Warlock": foreach (var item in spells.Warlock.Keys) { result.Add(item, spells.Warlock[item]); } stat = "Cha"; break; case "Wizard": foreach (var item in spells.Wizard.Keys) { result.Add(item, spells.Wizard[item]); } stat = "Int"; break; } return(new Tuple <Dictionary <int, List <string> >, string>(result, stat)); }
private static void executeRSA(string[] args) { var nArgs = CLIHelper.GetNamedArguments(args); switch (args[1]?.ToLower()) { case "create-pem-key": { var dir = nArgs["output"].ToDirectoryInfo(); var size = nArgs["size"].ToInt32(); if (!dir.Exists) { dir.Create(); } var keys = RSA.GeneratePemKeyPair(size); Console.WriteLine($"Public Key:\n{keys.Public}"); var pubFile = Path.Combine(dir.FullName, $"{dir.Name}.pub.pem").ToFileInfo(); var prvFile = Path.Combine(dir.FullName, $"{dir.Name}.prv.pem").ToFileInfo(); Console.WriteLine($"Saving RSA Public Key to: '{pubFile.FullName}'."); pubFile.WriteAllText(keys.Public); Console.WriteLine($"Saving RSA private Key to: '{prvFile.FullName}'."); prvFile.WriteAllText(keys.Private); } ; break; case "sign": { var key = nArgs["key"].ToFileInfo(); var input = nArgs["input"].ToFileInfo(); var output = nArgs["output"].ToFileInfo(); var algo = EnumEx.ToEnum <RSA.Algorithm>(nArgs["algorithm"]); Console.WriteLine($"Signing: '{input.FullName}' with Algorithm: '{algo.ToString()}'."); var sig = RSA.SignWithPemKey(input: input, pem: key, algorithm: algo); Console.WriteLine($"Signature:\n{sig.ToHexString()}"); Console.WriteLine($"Saving Signature to: '{output.FullName}'."); output.WriteAllBytes(sig); } ; break; case "verify": { var key = nArgs["key"].ToFileInfo(); var input = nArgs["input"].ToFileInfo(); var signature = nArgs["signature"].ToFileInfo(); var algo = EnumEx.ToEnum <RSA.Algorithm>(nArgs["algorithm"]); var @throw = nArgs.GetValueOrDefault("throw").ToBoolOrDefault(true); Console.WriteLine($"Veryfying: '{input.FullName}' with Algorithm: '{algo.ToString()}' and Public Key: {key.FullName}."); var success = RSA.VerifyWithPemKey(input: input, signature: signature, pem: key, algorithm: algo); if (success) { Console.WriteLine("Veryfication Suceeded."); } else { Console.WriteLine("Veryfication Failed."); if (@throw) { throw new Exception($"Signature verification failed, input: '{input?.FullName}'"); } } } ; break; case "help": case "--help": case "-help": case "-h": case "h": HelpPrinter($"{args[0]}", $"Rivest–Shamir–Adleman Algoritm, with following allowed algorithms: '{EnumEx.ToStringArray<RSA.Algorithm>().JsonSerialize()}'.", ("create-key", "Accepts params: output, size"), ("sign", "Accepts params: key, input, output, algorithm"), ("verify", "Accepts params: key, input, signature, algorithm, throw (optional, default: true)")); break; default: { Console.WriteLine($"Try '{args[0]} help' to find out list of available commands."); throw new Exception($"Unknown RSA command: '{args[0]} {args[1]}'"); } } }
public static void AddFeat(Character character) { string race = ""; var elves = new List <string> { "Avariel", "Eladrin", "Moon Elf", "Sea Elf", "Shadar-Kai", "Wild Elf" }; if (character.ChosenRace.Contains("Dwarf")) { race = "Dwarf"; } else if (elves.Contains(character.ChosenRace)) { race = "Elf"; } else if (character.ChosenRace.Contains("Gnome")) { race = "Gnome"; } else if (character.ChosenRace.Contains("Halfling")) { race = "Halfling"; } else if (character.ChosenRace.Contains("Human")) { race = "Human"; } else if (character.ChosenRace.Contains("Tiefling")) { race = "Tiefling"; } else { race = character.ChosenRace; } switch (race) { case "Cambion": FeatNames.Add("Flames of Phlegethos"); FeatNames.Add("Infernal Constitution"); break; case "Dragonborn": FeatNames.Add("Dragon Fear"); FeatNames.Add("Dragon Hide"); break; case "Dwarf": FeatNames.Add("Dwarven Fortitude"); FeatNames.Add("Squat Nimbleness"); break; case "Elf": FeatNames.Add("Elven Accuracy"); break; case "Drow": FeatNames.Add("Drow High Magic"); FeatNames.Add("Elven Accuracy"); break; case "High Elf": FeatNames.Add("Elven Accuracy"); FeatNames.Add("Fey Teleportation"); break; case "Wood Elf": FeatNames.Add("Elven Accuracy"); FeatNames.Add("Wood Elf Magic"); break; case "Gnome": FeatNames.Add("Fade Away"); FeatNames.Add("Squat Nimbleness"); break; case "Half-Elf": FeatNames.Add("Elven Accuracy"); FeatNames.Add("Prodigy"); break; case "Half-Orc": FeatNames.Add("Orcish Fury"); FeatNames.Add("Prodigy"); break; case "Halfling": FeatNames.Add("Bountiful Luck"); FeatNames.Add("Second Chance"); FeatNames.Add("Squat Nimbleness"); break; case "Human": FeatNames.Add("Prodigy"); break; case "Tiefling": FeatNames.Add("Flames of Phlegethos"); FeatNames.Add("Infernal Constitution"); break; } FeatNames.Sort(); foreach (var item in character.Feats.Keys) { if (FeatNames.Contains(item)) { FeatNames.Remove(item); } } string feat = CLIHelper.PrintChoices(Options.FeatDefinitions, FeatNames, "Pick a feat"); character.Feats.Add(feat, Options.FeatDefinitions[feat]); AddFeatBenefits(character, feat); }
private static async Task executeS3(string[] args, Credentials credentials) { var nArgs = CLIHelper.GetNamedArguments(args); var helper = new S3Helper(credentials); switch (args[1]?.ToLower()) { case "upload-text": { var keyId = nArgs.GetValueOrDefault("key"); var result = await helper.UploadTextAsync( bucketName : nArgs["bucket"], key : nArgs["path"], text : nArgs["text"], keyId : keyId, encoding : Encoding.UTF8); WriteLine($"SUCCESS, Text Saved, Bucket {nArgs["bucket"]}, Path {nArgs["path"]}, Encryption Key {keyId}, ETag: {result}"); } ; break; case "upload-object": { var file = nArgs["input"].ToFileInfo(); if (!file.Exists) { throw new Exception($"Can't upload file '{file}' because it doesn't exists."); } using (var stream = file.OpenRead()) { var keyId = nArgs.GetValueOrDefault("key"); var result = await helper.UploadStreamAsync( bucketName : nArgs["bucket"], key : nArgs["path"], inputStream : stream, keyId : keyId); WriteLine($"SUCCESS, File was uploaded, result: {result}"); } } ; break; case "upload-folder": { var bucket = nArgs["bucket"]; var path = nArgs["path"]; var directory = nArgs["input"].ToDirectoryInfo(); var excludeFiles = nArgs.GetValueOrDefault("exclude-files", "") .EscapedSplit(',').Where(x => !x.IsNullOrWhitespace()).Select(x => x.ToFileInfo()).ToArray(); var excludeDirectories = nArgs.GetValueOrDefault("exclude-directories", "") .EscapedSplit(',').Where(x => !x.IsNullOrWhitespace()).Select(x => x.ToDirectoryInfo()).ToArray(); var excludePatterns = nArgs.GetValueOrDefault("exclude-file-patterns", "") .EscapedSplit(',').Where(x => !x.IsNullOrWhitespace()).ToArray(); var includePatterns = nArgs.GetValueOrDefault("include-file-patterns", "*") .EscapedSplit(',').Where(x => !x.IsNullOrWhitespace()).ToArray(); var recursive = nArgs.GetValueOrDefault("recursive").ToBoolOrDefault(); //default false var force = nArgs.GetValueOrDefault("force").ToBoolOrDefault(true); //upload even if exists if (!directory.Exists) { throw new Exception($"Can't upload directory '{directory?.FullName}' because it doesn't exists."); } var files = directory.GetFiles(recursive: recursive, inclusivePatterns: includePatterns, exclusivePatterns: excludePatterns); var directories = directory.GetDirectories(recursive: recursive).Merge(directory); if (files.IsNullOrEmpty()) { WriteLine($"No files were found in directory '{directory?.FullName}'"); } if (directories.IsNullOrEmpty()) { WriteLine($"No sub-directories were found in directory '{directory?.FullName}'"); } var prefix = directory.FullName; int uploadedFiles = 0; int uploadedDirectories = 0; WriteLine("Uploading Files..."); files.ParallelForEach(file => { if (excludeFiles.Any(x => x.FullName == file.FullName) || excludeDirectories.Any(x => file.HasSubDirectory(x))) { WriteLine($"Skipping following File Upload due to exclude-files/directories parameter: '{file.FullName}'"); return; } var destination = (path.StartsWith("/") ? path.TrimStart("/") : path).TrimEnd("/") + "/" + file.FullName.TrimStartSingle(prefix).TrimStart('/', '\\').Replace("\\", "/"); destination = destination.TrimStart("/"); //in case path was null or '/' WriteLine($"Uploading '{file.FullName}' => '{bucket}/{destination}' ..."); using (var stream = file.OpenRead()) { var result = helper.UploadStreamAsync( bucketName: bucket, key: destination, inputStream: stream, keyId: null, throwIfAlreadyExists: !force).Result; ++uploadedFiles; WriteLine($"SUCCESS, File '{destination}' was uploaded, result: {result}"); } }); if (nArgs.GetValueOrDefault("create-directories").ToBoolOrDefault(false)) { WriteLine("Creating Directories..."); directories.ParallelForEach(dir => { if (excludeDirectories.Any(x => x.FullName == dir.FullName) || excludeDirectories.Any(x => dir.HasSubDirectory(x))) { WriteLine($"Skipping following Directory Creation due to exclude-files/directories parameter: '{dir.FullName}'"); return; } var destination = (path.StartsWith("/") ? path.TrimStart("/") : path).TrimEnd("/") + "/" + dir.FullName.TrimStartSingle(prefix).Trim('/', '\\').Replace("\\", "/"); destination = destination.TrimStart("/"); //in case path was null or '/' if (destination.IsNullOrEmpty() || helper.ObjectExistsAsync(bucket, key: destination + "/").Result) { WriteLine($"Directory '{destination}' already exists or is an empty destination."); return; } helper.CreateDirectory(bucketName: bucket, path: destination).Await(); ++uploadedDirectories; WriteLine($"Created empty directory '{destination}'."); }); } WriteLine($"SUCCESS, uploaded {uploadedFiles} files and {uploadedDirectories} directories."); } ; break; case "download-text": { var result = await helper.DownloadTextAsync( bucketName : nArgs["bucket"], key : nArgs["path"], eTag : nArgs.GetValueOrDefault("etag"), version : nArgs.GetValueOrDefault("version"), throwIfNotFound : nArgs.GetValueOrDefault("throw-if-not-found").ToBoolOrDefault(true), encoding : Encoding.UTF8); WriteLine($"SUCCESS, Text Read, Bucket: {nArgs["bucket"]}, Path: {nArgs.GetValueOrDefault("path")}, Version: {nArgs.GetValueOrDefault("version")}, eTag: {nArgs.GetValueOrDefault("etag")}, Read: {result?.Length ?? 0} [characters], Result:"); Console.WriteLine(result ?? ""); } ; break; case "delete-object": { var bucket = nArgs["bucket"]; var path = nArgs["path"]; var result = await helper.DeleteVersionedObjectAsync( bucketName : bucket, key : path, throwOnFailure : nArgs.GetValueOrDefault("throw-on-failure").ToBoolOrDefault(true)); if (!result && nArgs.GetValueOrDefault("throw-if-not-deleted").ToBoolOrDefault(false)) { throw new Exception($"File was NOT deleted, Bucket: {bucket}, Path: {path}"); } WriteLine($"SUCCESS, Text Read, Bucket: {bucket}, Path: {path}, Deleted: '{(result ? "true" : "false")}'"); } ; break; case "object-exists": { var throwIfNotFound = nArgs.GetValueOrDefault("throw-if-not-found").ToBoolOrDefault(false); var exists = await helper.ObjectExistsAsync( bucketName : nArgs["bucket"], key : nArgs["path"]); if (!exists && throwIfNotFound) { throw new Exception($"File Does NOT exists, Bucket: {nArgs["bucket"]}, Path: {nArgs["path"]}"); } WriteLine($"SUCCESS, Object Exists Check, Bucket: {nArgs["bucket"]}, Path: {nArgs["path"]}, Exists: {(exists ? "true" : "false")}"); if (!throwIfNotFound) { Console.WriteLine(exists); } } ; break; case "download-object": { var bucket = nArgs["bucket"]; var path = nArgs["path"]; var output = nArgs["output"]; if (Directory.Exists(output)) { output = Path.Combine(output, path.Contains("/") ? path.SplitByLast('/')[1] : path); } WriteLine($"Started Download '{bucket}' -> '{output}'..."); var result = await helper.DownloadObjectAsync( bucketName : nArgs["bucket"], key : path, eTag : nArgs.GetValueOrDefault("etag"), version : nArgs.GetValueOrDefault("version"), outputFile : output, @override : nArgs.GetValueOrDefault("override").ToBoolOrDefault(false)); WriteLine($"SUCCESS, Text Read, Bucket: {bucket}, Path: {path}, Version: {nArgs.GetValueOrDefault("version")}, eTag: {nArgs.GetValueOrDefault("etag")}, Read: {result?.Length ?? 0} [B], Result: {result}"); } ; break; case "download-folder": { var bucket = nArgs["bucket"]; var path = nArgs["path"].TrimEnd('/') + "/"; //path must contain '/' var output = nArgs["output"].ToDirectoryInfo(); var @override = nArgs.GetValueOrDefault("override").ToBoolOrDefault(); var recursive = nArgs.GetValueOrDefault("recursive").ToBoolOrDefault(false); var exclude = nArgs.GetValueOrDefault("exclude", "") .EscapedSplit(',').Where(x => !(x?.TrimStart('/')).IsNullOrWhitespace()).Select(x => x.TrimStart('/')).ToArray(); if (!output.Exists) { if (nArgs.GetValueOrDefault("create-output").ToBoolOrDefault(false)) { output.Create(); } else { throw new Exception($"Can't download S3 objects, because output directory '{output?.FullName}' does NOT exists."); } } var list = helper.ListObjectsAsync(bucket, prefix: path == "/" ? null : path).Result; if (list.IsNullOrEmpty()) { WriteLine($"Coudn't find any object in bucket '{bucket}' with prefix '{path}'."); } list.ParallelForEach(o => { var baseKey = o.Key.TrimStart('/').TrimStart(path.Trim('/')).TrimStart('/'); var excludeMatch = exclude?.FirstOrDefault(ex => baseKey.IsWildcardMatch(ex)); if (excludeMatch != null) { WriteLine($"Skipping download of object: '{o.Key}' due to exclude of '{excludeMatch}'."); return; } var destination = Path.Combine(output.FullName, baseKey).ToFileInfo(); var nonRecursivefileName = o.Key.TrimStart('/').TrimStart(path); if (!recursive && nonRecursivefileName.Count("/") > 0) { WriteLine($"Object '{o.Key}' will NOT be downloaded, because processing has non recursive mode."); return; } if (!@override && destination.Exists) { throw new Exception($"Override not allowed and file already fxists: '{destination?.FullName}'"); } if (o.Key.EndsWith("/")) { WriteLine($"Found Directory, not a file: '{o.BucketName}/{o.Key}', no need to download, created direcory '{destination.Directory.FullName}'."); return; } if (!destination.Directory.Exists) { WriteLine($"Creating missing directory '{destination.Directory.FullName}'..."); destination.Directory.Create(); } WriteLine($"Started Download '{bucket}/{o.Key}' -> '{destination?.FullName}'..."); var result = helper.DownloadObjectAsync( bucketName: bucket, key: o.Key, eTag: o.ETag, version: null, outputFile: destination.FullName, @override: @override).Result; WriteLine($"SUCCESS, File '{destination.FullName}' was saved."); }); } ; break; case "delete-folder": { var bucket = nArgs["bucket"]; var path = nArgs["path"].Trim('/') + "/"; var recursive = nArgs.GetValueOrDefault("recursive").ToBoolOrDefault(false); var list = await helper.ListObjectsAsync(bucket, prefix : path); WriteLine($"Found '{list.Length}' objects with '{path}' prefix in bucket '{bucket}'."); var rootPathCount = path.Trim('/').Count("/") + 1; int counter = 0; list.ParallelForEach(o => { if (!recursive && o.Key.Trim('/').Count("/") > rootPathCount) { WriteLine($"Object '{o.Key}' will NOT be removed from bucket '{bucket}', due to NON recursive execution mode."); return; } WriteLine($"Removing '{o.Key}' from bucket '{bucket}'..."); var success = helper.DeleteObjectAsync(bucketName: bucket, key: o.Key, throwOnFailure: true).Result; ++counter; WriteLine($"Sucesfully removed '{o.Key}' from bucket '{bucket}', response: {success}."); }); list = await helper.ListObjectsAsync(bucket, prefix : path); if (list.IsNullOrEmpty() && await helper.ObjectExistsAsync(bucket, key: path)) { WriteLine($"Removing root directory '{path}' from bucket '{bucket}'..."); var success = await helper.DeleteObjectAsync(bucketName : bucket, key : path, throwOnFailure : true); ++counter; WriteLine($"Sucesfully removed root directory '{path}' from bucket '{bucket}', response: {success}."); } WriteLine($"SUCCESS, removed {counter} files."); } ; break; case "hash-download": { var sync = nArgs.GetOrThrow("sync")?.ToDirectoryInfo(); if (sync?.TryCreate() != true) { throw new Exception($"Sync directory '{sync?.FullName ?? "undefined"}' was not found or could not be created."); } var st = new SyncTarget() { id = nArgs.GetValueOrDefault("id", GuidEx.SlimUID()), source = nArgs.GetOrThrow("source"), status = nArgs.GetOrThrow("status"), destination = nArgs.GetOrThrow("destination"), sync = sync.FullName, verbose = nArgs.GetValueOrDefault("verbose").ToBoolOrDefault(true), verify = nArgs.GetValueOrDefault("verify").ToBoolOrDefault(false), profile = nArgs.GetValueOrDefault("profile", ""), parallelism = nArgs.GetValueOrDefault("parallelism").ToIntOrDefault(2), maxTimestamp = nArgs.GetValueOrDefault("maxTimestamp").ToLongOrDefault(20991230121314), minTimestamp = nArgs.GetValueOrDefault("minTimestamp").ToLongOrDefault(0), wipe = nArgs.GetOrThrow("wipe").ToBoolOrDefault(false), compress = nArgs.GetValueOrDefault("compress").ToBoolOrDefault(false), retry = nArgs.GetValueOrDefault("retry").ToIntOrDefault(5), timeout = nArgs.GetValueOrDefault("timeout").ToIntOrDefault(60000), type = SyncTarget.types.download, throwIfSourceNotFound = nArgs.GetValueOrDefault("throwIfSourceNotFound").ToBoolOrDefault(true), }; var s3hs = new S3HashStore(st); var result = await s3hs.Process(); Console.Write(result.JsonSerialize()); } ; break; case "hash-upload": { var sync = nArgs.GetOrThrow("sync")?.ToDirectoryInfo(); if (sync?.TryCreate() != true) { throw new Exception($"Sync directory '{sync?.FullName ?? "undefined"}' was not found or could not be created."); } var st = new SyncTarget() { id = nArgs.GetValueOrDefault("id", GuidEx.SlimUID()), source = nArgs.GetOrThrow("source"), status = nArgs.GetOrThrow("status"), sync = sync.FullName, destination = nArgs.GetOrThrow("destination"), profile = nArgs.GetValueOrDefault("profile", ""), verbose = nArgs.GetValueOrDefault("verbose").ToBoolOrDefault(true), recursive = nArgs.GetOrThrow("recursive").ToBoolOrDefault(false), parallelism = nArgs.GetValueOrDefault("parallelism").ToIntOrDefault(2), retry = nArgs.GetValueOrDefault("retry").ToIntOrDefault(5), rotation = nArgs.GetOrThrow("rotation").ToInt32(), retention = nArgs.GetValueOrDefault("retention").ToIntOrDefault(1), // retention 1 second compress = nArgs.GetValueOrDefault("compress").ToBoolOrDefault(false), timeout = nArgs.GetValueOrDefault("timeout").ToIntOrDefault(180000), // 3 minutes type = SyncTarget.types.upload, throwIfSourceNotFound = nArgs.GetValueOrDefault("throwIfSourceNotFound").ToBoolOrDefault(true), }; var s3hs = new S3HashStore(st); var result = await s3hs.Process(); Console.Write(result.JsonSerialize()); } ; break; case "help": case "--help": case "-help": case "-h": case "h": HelpPrinter($"{args[0]}", "Amazon S3", ("upload-text", "Accepts params: bucket, path, key, text"), ("download-text", "Accepts params: bucket, path, etag (optional), version (optional)"), ("delete-object", "Accepts params: bucket, path"), ("object-exists", "Accepts params: bucket, path"), ("hash-upload", "Accepts params: id (optional-UID), profile, sourc, status, sync, verbose (optional), parallelism (optional), maxTimestamp (optional), minTimestamp (optional), retry (optional), compress (optional:false), wipe, verify (optional:false), timeout (optional: 60000), throwIfSourceNotFound (optional: true)"), ("hash-download", "Accepts params: id (optional), profile, sourc, status, sync, destination, recursive, verbose (optional), parallelism (optional), wipe, timeout (optional: 180000), retention, rotation, compress (optional:false), throwIfSourceNotFound (optional: true)")); break; default: { Console.WriteLine($"Try '{args[0]} help' to find out list of available commands."); throw new Exception($"Unknown S3 command: '{args[0]} {args[1]}'"); } } }