context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; /// <summary> /// Some helper extensions methods for the KMBombInfo class. /// </summary> public static class KMBombInfoExtensions { #region JSON Types private class IndicatorJSON { public string label = null; public string on = null; public bool IsOn() { bool isOn = false; bool.TryParse(on, out isOn); return isOn; } } private class BatteryJSON { public int numbatteries = 0; } private class PortsJSON { public string[] presentPorts = null; } private class SerialNumberJSON { public string serial = null; } #endregion #region Helpers public enum KnownBatteryType { Unknown = 0, D = 1, //D batteries currently always come as 1 battery in the one battery holder AAx2 = 2, AAx3 = 3, AAx4 = 4 } public enum KnownPortType { DVI, Parallel, PS2, RJ45, Serial, StereoRCA } public enum KnownIndicatorLabel { SND, CLR, CAR, IND, FRQ, SIG, NSA, MSA, TRN, BOB, FRK } private static IEnumerable<T> GetJSONEntries<T>(KMBombInfo bombInfo, string queryKey, string queryInfo) where T : new() { return bombInfo.QueryWidgets(queryKey, queryInfo).Select(delegate (string queryEntry) { return JsonConvert.DeserializeObject<T>(queryEntry); }); } private static IEnumerable<IndicatorJSON> GetIndicatorEntries(KMBombInfo bombInfo) { return GetJSONEntries<IndicatorJSON>(bombInfo, KMBombInfo.QUERYKEY_GET_INDICATOR, null); } private static IEnumerable<BatteryJSON> GetBatteryEntries(KMBombInfo bombInfo) { return GetJSONEntries<BatteryJSON>(bombInfo, KMBombInfo.QUERYKEY_GET_BATTERIES, null); } private static IEnumerable<PortsJSON> GetPortEntries(KMBombInfo bombInfo) { return GetJSONEntries<PortsJSON>(bombInfo, KMBombInfo.QUERYKEY_GET_PORTS, null); } private static IEnumerable<SerialNumberJSON> GetSerialNumberEntries(KMBombInfo bombInfo) { return GetJSONEntries<SerialNumberJSON>(bombInfo, KMBombInfo.QUERYKEY_GET_SERIAL_NUMBER, null); } #endregion #region Public Extensions public static bool IsIndicatorPresent(this KMBombInfo bombInfo, KnownIndicatorLabel indicatorLabel) { return bombInfo.IsIndicatorPresent(indicatorLabel.ToString()); } public static bool IsIndicatorPresent(this KMBombInfo bombInfo, string indicatorLabel) { return GetIndicatorEntries(bombInfo).Any((x) => indicatorLabel.Equals(x.label)); } public static bool IsIndicatorOn(this KMBombInfo bombInfo, KnownIndicatorLabel indicatorLabel) { return bombInfo.IsIndicatorOn(indicatorLabel.ToString()); } public static bool IsIndicatorOn(this KMBombInfo bombInfo, string indicatorLabel) { return GetIndicatorEntries(bombInfo).Any((x) => x.IsOn() && indicatorLabel.Equals(x.label)); } public static IEnumerable<string> GetIndicators(this KMBombInfo bombInfo) { return GetIndicatorEntries(bombInfo).Select((x) => x.label); } public static IEnumerable<string> GetOnIndicators(this KMBombInfo bombInfo) { return GetIndicatorEntries(bombInfo).Where((x) => x.IsOn()).Select((x) => x.label); } public static IEnumerable<string> GetOffIndicators(this KMBombInfo bombInfo) { return GetIndicatorEntries(bombInfo).Where((x) => !x.IsOn()).Select((x) => x.label); } public static int GetBatteryCount(this KMBombInfo bombInfo) { return GetBatteryEntries(bombInfo).Sum((x) => x.numbatteries); } public static int GetBatteryCount(this KMBombInfo bombInfo, KnownBatteryType batteryType) { return GetBatteryEntries(bombInfo).Where((x) => x.numbatteries == (int)batteryType).Sum((x) => x.numbatteries); } public static int GetBatteryHolderCount(this KMBombInfo bombInfo) { return GetBatteryEntries(bombInfo).Count(); } public static int GetPortCount(this KMBombInfo bombInfo) { return GetPortEntries(bombInfo).Sum((x) => x.presentPorts.Length); } public static int GetPortCount(this KMBombInfo bombInfo, KnownPortType portType) { return bombInfo.GetPortCount(portType.ToString()); } public static int GetPortCount(this KMBombInfo bombInfo, string portType) { return GetPortEntries(bombInfo).Sum((x) => x.presentPorts.Count((y) => portType.Equals(y))); } public static int GetPortPlateCount(this KMBombInfo bombInfo) { return GetPortEntries(bombInfo).Count(); } public static IEnumerable<string> GetPorts(this KMBombInfo bombInfo) { return GetPortEntries(bombInfo).SelectMany((x) => x.presentPorts); } public static IEnumerable<string[]> GetPortPlates(this KMBombInfo bombInfo) { return GetPortEntries(bombInfo).Select((x) => x.presentPorts); } public static bool IsPortPresent(this KMBombInfo bombInfo, KnownPortType portType) { return bombInfo.IsPortPresent(portType.ToString()); } public static bool IsPortPresent(this KMBombInfo bombInfo, string portType) { return GetPortEntries(bombInfo).Any((x) => x.presentPorts != null && x.presentPorts.Any((y) => portType.Equals(y))); } public static string GetSerialNumber(this KMBombInfo bombInfo) { return GetSerialNumberEntries(bombInfo).First().serial; } public static IEnumerable<char> GetSerialNumberLetters(this KMBombInfo bombInfo) { return GetSerialNumber(bombInfo).Where((x) => x < '0' || x > '9'); } public static IEnumerable<int> GetSerialNumberNumbers(this KMBombInfo bombInfo) { return GetSerialNumber(bombInfo).Where((x) => x >= '0' && x <= '9').Select((y) => int.Parse("" + y)); } #endregion }
using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.AspNetCore.Hosting; using Elixr.Api.Models; namespace Elixr.Api.Services { public class Seeder { private enum RequiredFeature { CatLikeVision, SpeakLanguage, NimbleFingers, NaturalStrength, NaturalCharm, NaturalAgility, NaturalFocus, NaturalAdept, Dexterous, Insightful, MinuteBenefits, TinyBenefits, ShortBenefits, LargeBenefits, HugeBenefits, MassiveBenefits, } private enum RequiredFlaw { MinuteDrawbacks, TinyDrawbacks, ShortDrawbacks, LargeDrawbacks, HugeDrawbacks, MassiveDrawbacks, Unappealing, WeakConstitution, Bulky, Gruff } private long now = 1473303913983; private IHostingEnvironment hostingEnvironment; private ElixrDbContext dbCtx; private readonly ElixrSettings elixrSettings; private readonly Utilities utilities; public Seeder(ElixrDbContext dbCtx, IHostingEnvironment hostingEnvironment, ElixrSettings elixrSettings, Utilities utilities) { this.dbCtx = dbCtx; this.hostingEnvironment = hostingEnvironment; this.elixrSettings = elixrSettings; this.utilities = utilities; } public void Seed() { string initialCode = "seed.initial"; if (!dbCtx.SeedInformation.Any(si => si.Code == initialCode)) { Player gameMaster = SeedPlayers(); SeedSpells(gameMaster); var requiredFlaws = SeedFlaws(gameMaster); var requiredFeatures = SeedFeatures(gameMaster, requiredFlaws); SeedRaces(gameMaster, requiredFeatures, requiredFlaws); Elixr.Api.ApiModels.SeedInfo seedInfo = new Elixr.Api.ApiModels.SeedInfo { Code = initialCode, PerformedAtMS = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }; dbCtx.SeedInformation.Add(seedInfo); } dbCtx.SaveChanges(); } private string GetDescriptionFor(string folder, string file) { string path = Path.Combine(hostingEnvironment.ContentRootPath, "Content", folder, file); return File.ReadAllText(path); } private Player SeedPlayers() { Player player = new Player(); player.Name = "The Game Master"; player.Email = "elixrrpg@gmail.com"; player.SecurityHash = utilities.HashText(elixrSettings.GameMasterPassword); dbCtx.Players.Add(player); return player; } private void SeedRaces(Player gameMaster, Dictionary<RequiredFeature, Feature> requiredFeatures, Dictionary<RequiredFlaw, Flaw> requiredFlaws) { var speakLanguageFeature = requiredFeatures[RequiredFeature.SpeakLanguage]; var catLikeVision = requiredFeatures[RequiredFeature.CatLikeVision]; var nimbleFingers = requiredFeatures[RequiredFeature.NimbleFingers]; var insightful = requiredFeatures[RequiredFeature.Insightful]; var dexterous = requiredFeatures[RequiredFeature.Dexterous]; var naturalAgility = requiredFeatures[RequiredFeature.NaturalAgility]; var naturalCharm = requiredFeatures[RequiredFeature.NaturalCharm]; var naturalFocus = requiredFeatures[RequiredFeature.NaturalFocus]; var naturalStrength = requiredFeatures[RequiredFeature.NaturalStrength]; //size based //flaws var shortDrawbacks = requiredFlaws[RequiredFlaw.ShortDrawbacks]; var tinyDrawbacks = requiredFlaws[RequiredFlaw.TinyDrawbacks]; var minuteDrawbacks = requiredFlaws[RequiredFlaw.MinuteDrawbacks]; var largeDrawbacks = requiredFlaws[RequiredFlaw.LargeDrawbacks]; var hugeDrawbacks = requiredFlaws[RequiredFlaw.HugeDrawbacks]; var massiveDrawbacks = requiredFlaws[RequiredFlaw.MassiveDrawbacks]; //features var shortBenefits = requiredFeatures[RequiredFeature.ShortBenefits]; var tinyBenefits = requiredFeatures[RequiredFeature.TinyBenefits]; var minuteBenefits = requiredFeatures[RequiredFeature.MinuteBenefits]; var largeBenefits = requiredFeatures[RequiredFeature.LargeBenefits]; var hugeBenefits = requiredFeatures[RequiredFeature.HugeBenefits]; var massiveBenefits = requiredFeatures[RequiredFeature.MassiveBenefits]; var unappealingFlaw = requiredFlaws[RequiredFlaw.Unappealing]; var weakConstitution = requiredFlaws[RequiredFlaw.WeakConstitution]; var bulky = requiredFlaws[RequiredFlaw.Bulky]; var gruff = requiredFlaws[RequiredFlaw.Gruff]; string racesFolder = "Races"; List<Race> races = new List<Race>(); Race dwarf = new Race(); dwarf.AuthorId = gameMaster.Id; dwarf.Name = "Dwarf"; dwarf.Description = GetDescriptionFor(racesFolder, "dwarf.md"); dwarf.FlawInformation.Add(new FlawInfo { FlawId = bulky.Id }); dwarf.FlawInformation.Add(new FlawInfo { FlawId = gruff.Id }); dwarf.FeatureInformation.Add(new FeatureInfo { FeatureId = speakLanguageFeature.Id, Notes = "Dwarvish" }); dwarf.FeatureInformation.Add(new FeatureInfo { FeatureId = catLikeVision.Id, }); dwarf.FeatureInformation.Add(new FeatureInfo { FeatureId = naturalStrength.Id }); races.Add(dwarf); Race elf = new Race(); elf.AuthorId = gameMaster.Id; elf.Name = "Elf"; elf.Description = GetDescriptionFor(racesFolder, "elf.md"); elf.FlawInformation.Add(new FlawInfo { FlawId = weakConstitution.Id }); elf.FeatureInformation.Add(new FeatureInfo { FeatureId = speakLanguageFeature.Id, Notes = "Elvish" }); elf.FeatureInformation.Add(new FeatureInfo { FeatureId = naturalAgility.Id }); races.Add(elf); Race gnome = new Race(); gnome.AuthorId = gameMaster.Id; gnome.Name = "Gnome"; gnome.Description = GetDescriptionFor(racesFolder, "gnome.md"); gnome.FlawInformation.Add(new FlawInfo { FlawId = shortDrawbacks.Id }); gnome.FeatureInformation.Add(new FeatureInfo { FeatureId = shortBenefits.Id }); gnome.FeatureInformation.Add(new FeatureInfo { FeatureId = speakLanguageFeature.Id, Notes = "Gnomish" }); gnome.FeatureInformation.Add(new FeatureInfo { FeatureId = nimbleFingers.Id }); gnome.FeatureInformation.Add(new FeatureInfo { FeatureId = catLikeVision.Id }); gnome.FeatureInformation.Add(new FeatureInfo { FeatureId = naturalFocus.Id }); races.Add(gnome); Race halfling = new Race(); halfling.AuthorId = gameMaster.Id; halfling.Name = "Halfling"; halfling.Description = GetDescriptionFor(racesFolder, "halfling.md"); halfling.FlawInformation.Add(new FlawInfo { FlawId = shortDrawbacks.Id }); halfling.FeatureInformation.Add(new FeatureInfo { FeatureId = shortBenefits.Id }); halfling.FeatureInformation.Add(new FeatureInfo { FeatureId = dexterous.Id }); halfling.FeatureInformation.Add(new FeatureInfo { FeatureId = insightful.Id }); halfling.FeatureInformation.Add(new FeatureInfo { FeatureId = naturalCharm.Id }); races.Add(halfling); Race human = new Race(); human.AuthorId = gameMaster.Id; human.Name = "Human"; human.Description = GetDescriptionFor(racesFolder, "human.md"); races.Add(human); Race orc = new Race(); orc.AuthorId = gameMaster.Id; orc.Name = "Orc"; orc.Description = GetDescriptionFor(racesFolder, "orc.md"); orc.FeatureInformation.Add(new FeatureInfo { FeatureId = speakLanguageFeature.Id, Notes = "Orcish" }); orc.FeatureInformation.Add(new FeatureInfo { FeatureId = naturalStrength.Id }); orc.FlawInformation.Add(new FlawInfo { FlawId = unappealingFlaw.Id }); races.Add(orc); foreach (var race in races) { race.CreatedAtMS = now; dbCtx.Races.Add(race); } } private Dictionary<RequiredFeature, Feature> SeedFeatures(Player gameMaster, Dictionary<RequiredFlaw, Flaw> requiredFlaws) { Dictionary<RequiredFeature, Feature> requiredFeatures = new Dictionary<RequiredFeature, Feature>(); string featureFolder = "Features"; List<Feature> features = new List<Feature>(); Feature feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 4; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "animal-companion-small.md"); feature.Name = "Animal Companion, Small"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 6; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "animal-companion-medium.md"); feature.Name = "Animal Companion, medium"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 8; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "animal-companion-large.md"); feature.Name = "Animal Companion, large"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Spell; feature.CanBeTakenEachLevel = true; feature.MustSacrificeEnergy = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "at-will-spell.md"); feature.Name = "At Will Spell"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 8; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "cohort.md"); feature.Name = "Cohort"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "dodge.md"); feature.Name = "Dodge"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 1, ModifierType = ModifierType.Normal, Reason = "Feature: Dodge", Stat = Stat.Defense }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 11; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "fast-healing.md"); feature.Name = "Fast Healing"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 18; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "fly.md"); feature.Name = "Fly"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 2; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "haste.md"); feature.Name = "Haste"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 1, ModifierType = ModifierType.Normal, Reason = "Feature: Haste", Stat = Stat.Initiative }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 16; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "immunity.md"); feature.Name = "Immunity, Energy"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "learn-spell.md"); feature.Name = "Learn Spell"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 9; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "leech.md"); feature.Name = "Leech"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 12; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "resistance-energy.md"); feature.Name = "Resistance, Energy"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 20; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "resistance-physical.md"); feature.Name = "Resistance, Physical"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Spell; feature.CanBeTakenEachLevel = true; feature.Cost = 2; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "silent-spell.md"); feature.Name = "Silent Spell"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 2; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "skill-training.md"); feature.Name = "Skill Training"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "speak-language.md"); feature.Name = "Speak Language"; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.SpeakLanguage, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 7; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "speed.md"); feature.Name = "Speed"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 10, ModifierType = ModifierType.Normal, Reason = "Feature: Speed", Stat = Stat.Speed }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Spell; feature.CanBeTakenEachLevel = true; feature.Cost = 2; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "still-spell.md"); feature.Name = "Still Spell"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 4; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "two-weapon-training.md"); feature.Name = "Two Weapon Training"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "vitality.md"); feature.Name = "Vitality"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "wealth-major.md"); feature.Name = "Wealth, Major"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 200, ModifierType = ModifierType.Normal, Reason = "Feature: Wealth, Major", Stat = Stat.Wealth }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "wealth-minor.md"); feature.Name = "Wealth, Minor"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 50, ModifierType = ModifierType.Normal, Reason = "Feature: Wealth, Minor", Stat = Stat.Wealth }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Weapon; feature.CanBeTakenEachLevel = true; feature.Cost = 2; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "weapon-specialization.md"); feature.Name = "Weapon Specialization"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 1, ModifierType = ModifierType.Normal, Reason = "Feature: Weapon Specialization", Stat = Stat.WeaponDamageIncrease }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Weapon; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "weapon-training.md"); feature.Name = "Weapon Training"; feature.Player = gameMaster; feature.Mods.Add(new StatMod { Modifier = 1, ModifierType = ModifierType.Normal, Reason = "Feature: Weapon Training", Stat = Stat.WeaponAttackIncrease }); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "cat-like-vision.md"); feature.Name = "Catlike Vision"; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.CatLikeVision, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "nimble-fingers.md"); feature.Name = "Nimble Fingers"; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.NimbleFingers, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "natural-strength.md"); feature.Name = "Natural Strength"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialStrengthScore, Modifier = 2, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.NaturalStrength, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "natural-agility.md"); feature.Name = "Natural Agility"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialAgilityScore, Modifier = 2, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.NaturalAgility, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "natural-focus.md"); feature.Name = "Natural Focus"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialFocusScore, Modifier = 2, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.NaturalFocus, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "natural-charm.md"); feature.Name = "Natural Charm"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialCharmScore, Modifier = 2, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.NaturalCharm, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 3; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "natural-adept.md"); feature.Name = "Natural Adept"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.GenericAbilityPool, Modifier = 2, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.NaturalAdept, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "dexterous.md"); feature.Name = "Dexterous"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.SleightOfHand, Modifier = 1, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.Dexterous, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = true; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "insightful.md"); feature.Name = "Insightful"; feature.Player = gameMaster; feature.Mods = new List<StatMod> { new StatMod { Stat = Stat.Insight, Modifier = 1, ModifierType = ModifierType.Normal } }; requiredFeatures.Add(RequiredFeature.Insightful, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 1; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "echolocation-20ft.md"); feature.Name = "Echolocation (20ft)"; feature.Player = gameMaster; features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 0; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "short-benefits.md"); feature.Name = "Short Benefits"; feature.RequiredFlaws = new List<Flaw> { requiredFlaws[RequiredFlaw.ShortDrawbacks] }; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.ShortBenefits, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 0; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "tiny-benefits.md"); feature.Name = "Tiny Benefits"; feature.RequiredFlaws = new List<Flaw> { requiredFlaws[RequiredFlaw.TinyDrawbacks] }; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.TinyBenefits, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 0; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "minute-benefits.md"); feature.Name = "Minute Benefits"; feature.RequiredFlaws = new List<Flaw> { requiredFlaws[RequiredFlaw.MinuteDrawbacks] }; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.MinuteBenefits, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 0; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "large-benefits.md"); feature.Name = "Large Benefits"; feature.RequiredFlaws = new List<Flaw> { requiredFlaws[RequiredFlaw.LargeDrawbacks] }; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.LargeBenefits, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 0; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "huge-benefits.md"); feature.Name = "Huge Benefits"; feature.RequiredFlaws = new List<Flaw> { requiredFlaws[RequiredFlaw.HugeDrawbacks] }; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.HugeBenefits, feature); features.Add(feature); feature = new Feature(); feature.ApplyType = FeatureApplyingType.Self; feature.CanBeTakenEachLevel = false; feature.Cost = 0; feature.CreatedAtMS = now; feature.Description = GetDescriptionFor(featureFolder, "massive-benefits.md"); feature.Name = "Massive Benefits"; feature.RequiredFlaws = new List<Flaw> { requiredFlaws[RequiredFlaw.MassiveDrawbacks] }; feature.Player = gameMaster; requiredFeatures.Add(RequiredFeature.MassiveBenefits, feature); features.Add(feature); features.ForEach(f => dbCtx.Features.Add(f)); return requiredFeatures; } private Dictionary<RequiredFlaw, Flaw> SeedFlaws(Player gameMaster) { Dictionary<RequiredFlaw, Flaw> flawsByRequired = new Dictionary<RequiredFlaw, Flaw>(); List<Flaw> flaws = new List<Flaw>(); Flaw flaw = new Flaw { Name = "Short Drawbacks", Description = GetDescriptionFor("Flaws", "short-drawbacks.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.Speed, Modifier = -10, Reason = "Flaw: Short Drawbacks" }, new StatMod { Stat = Stat.SpecialStrengthScore, Modifier = -2, Reason = "Flaw: Short Drawbacks" }, } }; flawsByRequired.Add(RequiredFlaw.ShortDrawbacks, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Tiny Drawbacks", Description = GetDescriptionFor("Flaws", "tiny-drawbacks.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.Speed, Modifier = -20, Reason = "Flaw: Tiny Drawbacks" }, new StatMod { Stat = Stat.SpecialStrengthScore, Modifier = -4, Reason = "Flaw: Tiny Drawbacks" }, } }; flawsByRequired.Add(RequiredFlaw.TinyDrawbacks, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Minute Drawbacks", Description = GetDescriptionFor("Flaws", "minute-drawbacks.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.Speed, Modifier = -40, Reason = "Flaw: Minute Drawbacks" }, new StatMod { Stat = Stat.SpecialStrengthScore, Modifier = -8, Reason = "Flaw: Minute Drawbacks" }, } }; flawsByRequired.Add(RequiredFlaw.MinuteDrawbacks, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Large Drawbacks", Description = GetDescriptionFor("Flaws", "large-drawbacks.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialAgilityScore, Modifier = -2, Reason = "Flaw: Large Drawbacks" }, } }; flawsByRequired.Add(RequiredFlaw.LargeDrawbacks, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Huge Drawbacks", Description = GetDescriptionFor("Flaws", "huge-drawbacks.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialAgilityScore, Modifier = -4, Reason = "Flaw: Huge Drawbacks" }, } }; flawsByRequired.Add(RequiredFlaw.HugeDrawbacks, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Massive Drawbacks", Description = GetDescriptionFor("Flaws", "massive-drawbacks.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialAgilityScore, Modifier = -2, Reason = "Flaw: Massive Drawbacks" }, } }; flawsByRequired.Add(RequiredFlaw.MassiveDrawbacks, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Unappealing", Description = GetDescriptionFor("Flaws", "unappealing.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialCharmScore, Modifier = -2, Reason = "Flaw: Unappealing" } } }; flawsByRequired.Add(RequiredFlaw.Unappealing, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Weak Constitution", Description = GetDescriptionFor("Flaws", "weak-constitution.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.MaxEnergy, Modifier = -2, Reason = "Flaw: Weak Constitution" } } }; flawsByRequired.Add(RequiredFlaw.WeakConstitution, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Bulky", Description = GetDescriptionFor("Flaws", "bulky.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.Speed, Modifier = -5, Reason = "Flaw: Bulky" } } }; flawsByRequired.Add(RequiredFlaw.Bulky, flaw); flaws.Add(flaw); flaw = new Flaw { Name = "Gruff", Description = GetDescriptionFor("Flaws", "gruff.md"), CreatedAtMS = now, Player = gameMaster, Mods = new List<StatMod> { new StatMod { Stat = Stat.SpecialCharmScore, Modifier = -2, Reason = "Flaw: Gruff" } } }; flawsByRequired.Add(RequiredFlaw.Gruff, flaw); flaws.Add(flaw); flaws.ForEach(f => this.dbCtx.Add(f)); return flawsByRequired; } private void SeedSpells(Player gameMaster) { const string spellsFolder = "Spells"; List<Spell> spells = new List<Spell>(); Spell spell = new Spell(); spell.Name = "Automate"; spell.Description = GetDescriptionFor(spellsFolder, "automate.md"); spell.EnergyCost = "1 per hour "; spell.RegenTimeInRounds = 1; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Clairvoyance"; spell.Description = GetDescriptionFor(spellsFolder, "clairvoyance.md"); spell.EnergyCost = "Up to your Current Energy"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 60; spells.Add(spell); spell = new Spell(); spell.Name = "Compel"; spell.Description = GetDescriptionFor(spellsFolder, "compel.md"); spell.EnergyCost = "1 per 1d6 you wish to roll to overcome the target's Concentration Defense."; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Conjure Object"; spell.Description = GetDescriptionFor(spellsFolder, "conjure-object.md"); spell.EnergyCost = "1 per 10 pounds of mass created"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Divinate"; spell.Description = GetDescriptionFor(spellsFolder, "divinate.md"); spell.EnergyCost = "Up to your Current Energy"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 60; spells.Add(spell); spell = new Spell(); spell.Name = "Energy Blast"; spell.Description = GetDescriptionFor(spellsFolder, "energy-blast.md"); spell.EnergyCost = "Up to your Current Energy"; spell.RegenTimeInRounds = 1; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Fly"; spell.Description = GetDescriptionFor(spellsFolder, "fly.md"); spell.EnergyCost = "2 per 10ft you want to be able to fly in a round"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Illusion"; spell.Description = GetDescriptionFor(spellsFolder, "illusion.md"); spell.EnergyCost = "1 per 1d6 you wish to roll to overcome the target's Concentration Defense"; spell.RegenTimeInRounds = 0; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Invisibility"; spell.Description = GetDescriptionFor(spellsFolder, "invisibility.md"); spell.EnergyCost = "1 per creature made Invisible. Spending more Energy makes it less likely to be seen through other magical effects."; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Mind Read"; spell.Description = GetDescriptionFor(spellsFolder, "mind-read.md"); spell.EnergyCost = "1 per 1d6 you wish to roll to overcome the target's Concentration Defense"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Necromancy"; spell.Description = GetDescriptionFor(spellsFolder, "necromancy.md"); spell.EnergyCost = "Equal to the number of days you wish the undead to remain animated + the level each of the deceased had in life, minimum of 1"; spell.RegenTimeInRounds = 10; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Plane Shift"; spell.Description = GetDescriptionFor(spellsFolder, "plane-shift.md"); spell.EnergyCost = "14"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Resurrect"; spell.Description = GetDescriptionFor(spellsFolder, "resurrect.md"); spell.EnergyCost = "Up to your Current Energy"; spell.RegenTimeInRounds = Spell.SeeDescriptionRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Reveal"; spell.Description = GetDescriptionFor(spellsFolder, "reveal.md"); spell.EnergyCost = "Up to your Current Energy"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Speak With Entity"; spell.Description = GetDescriptionFor(spellsFolder, "speak-with-entity.md"); spell.EnergyCost = "1 per minute you wish to spend talking"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Spider Walk"; spell.Description = GetDescriptionFor(spellsFolder, "spider-walk.md"); spell.EnergyCost = "1 per 10ft of surface you wish to Spider Walk"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Telekinesis"; spell.Description = GetDescriptionFor(spellsFolder, "telekinesis.md"); spell.EnergyCost = "1 per 10 pounds moved"; spell.RegenTimeInRounds = Spell.SeeDescriptionRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Teleport"; spell.Description = GetDescriptionFor(spellsFolder, "teleport.md"); spell.EnergyCost = "1 per 100ft travelled"; spell.RegenTimeInRounds = 10; spell.MovementCost = 60; spells.Add(spell); spell = new Spell(); spell.Name = "Tongues"; spell.Description = GetDescriptionFor(spellsFolder, "tongues.md"); spell.EnergyCost = "2"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Transmute Object"; spell.Description = GetDescriptionFor(spellsFolder, "transmute-object.md"); spell.EnergyCost = "1 per 5 pounds of mass transmuted"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); spell = new Spell(); spell.Name = "Wild Shape"; spell.Description = GetDescriptionFor(spellsFolder, "wild-shape.md"); spell.EnergyCost = "Equal to level of creature"; spell.RegenTimeInRounds = Spell.ConcentrationRegen; spell.MovementCost = 30; spells.Add(spell); foreach (var item in spells) { item.Player = gameMaster; item.CreatedAtMS = now; dbCtx.Spells.Add(item); } } } }
#if VS10 #else // ported from $/DevDiv/PU/WPT/venus/mvw/data/LocalDB/LocalDB.cs namespace OpenRiaServices.VisualStudio.DomainServices.Tools { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Registry = global::Microsoft.Win32.Registry; using Configuration = global::System.Configuration.Configuration; using ConfigurationManager = global::System.Configuration.ConfigurationManager; using ExeConfigurationFileMap = global::System.Configuration.ExeConfigurationFileMap; using ConfigurationUserLevel = global::System.Configuration.ConfigurationUserLevel; using ConnectionStringSettingsList = global::System.Collections.Generic.List<global::System.Configuration.ConnectionStringSettings>; using ConnectionStringSettings = global::System.Configuration.ConnectionStringSettings; using ConnectionStringSettingsCollection = global::System.Configuration.ConnectionStringSettingsCollection; using ConnectionStringsSection = global::System.Configuration.ConnectionStringsSection; using EntityConnectionStringBuilder = global::System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder; using SqlConnectionStringBuilder = global::System.Data.SqlClient.SqlConnectionStringBuilder; using IServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using IVsShell = Microsoft.VisualStudio.Shell.Interop.IVsShell; using __VSSPROPID = Microsoft.VisualStudio.Shell.Interop.__VSSPROPID; public class LocalDBUtil : IDisposable { private IServiceProvider _serviceProvider; private readonly string _webConfigPath; //------------------------------------------------------------------------------ // Create the instance using a managed service provider //------------------------------------------------------------------------------ public LocalDBUtil(IServiceProvider serviceProvider, string webConfigPath) { _serviceProvider = serviceProvider; _webConfigPath = webConfigPath; } //------------------------------------------------------------------------------ // Ensure resources are released if not disposed //------------------------------------------------------------------------------ ~LocalDBUtil() { Dispose(); } //------------------------------------------------------------------------------ // Ensure resources are released //------------------------------------------------------------------------------ public void Dispose() { _serviceProvider = null; GC.SuppressFinalize(this); } //------------------------------------------------------------------------------ // Get the service provider for the web project context we were initlialized with //------------------------------------------------------------------------------ private IServiceProvider ServiceProvider { get { return _serviceProvider; } } //------------------------------------------------------------------------------ // Opens web configuration for read or write access //------------------------------------------------------------------------------ private Configuration OpenWebConfiguration(bool readOnly) { ExeConfigurationFileMap webConfig = new ExeConfigurationFileMap { ExeConfigFilename = _webConfigPath }; return ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None); } //------------------------------------------------------------------------------ // Gets a list of all the web specific connection string settings, filtering out parent settings //------------------------------------------------------------------------------ private ConnectionStringSettingsList GetConnectionStringSettingsList(Configuration configuration) { if (configuration == null) return null; ConnectionStringSettingsList connectionStringSettingsList = new ConnectionStringSettingsList(); try { // Get the connection string settings from config ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)configuration.GetSection("connectionStrings"); ConnectionStringSettingsCollection connectionStringSettingsCollection = connectionStringsSection.ConnectionStrings; // Get the parent connection string settings from config ConnectionStringsSection parentConnectionStringsSection = (ConnectionStringsSection)connectionStringsSection.SectionInformation.GetParentSection(); ConnectionStringSettingsCollection parentConnectionStringSettingsCollection = parentConnectionStringsSection.ConnectionStrings; // Filter out parent connection string settings foreach (ConnectionStringSettings connectionStringSettings in connectionStringSettingsCollection) { if (string.IsNullOrEmpty(connectionStringSettings.Name) || parentConnectionStringSettingsCollection[connectionStringSettings.Name] == null) { connectionStringSettingsList.Add(connectionStringSettings); } } } catch (Exception) { //If web.config file is in bad shape, configuration API will throw an exception. We should silently eat the exception and display the message connectionStringSettingsList = null; } return connectionStringSettingsList; } //------------------------------------------------------------------------------ // Get writable collection of connections from web.config //------------------------------------------------------------------------------ private DBConnectionList GetConfigConnections(out Configuration configuration) { configuration = OpenWebConfiguration(false/*readOnly*/); return GetConfigConnections(configuration); } //------------------------------------------------------------------------------ // Get collection of connections from provided configuration //------------------------------------------------------------------------------ private DBConnectionList GetConfigConnections(Configuration configuration) { DBConnectionList configConnections = null; if (configuration != null) { ConnectionStringSettingsList connectionStringSettingsList = GetConnectionStringSettingsList(configuration); if (connectionStringSettingsList != null) { foreach (ConnectionStringSettings connectionStringSettings in connectionStringSettingsList) { DBConnection configConnection = new ConfigConnection(ServiceProvider, connectionStringSettings); if (configConnections == null) { configConnections = new DBConnectionList(); } configConnections.Add(configConnection); } } } return configConnections; } //-------------------------------------------------------------------------------------------------------------------------- // Finds all the Connection Strings in web.config, converts them to LocalDB if updateDataSourceToLocalDB is set, and saves //------------------------------------------------------------------------------------------------------------------------- private bool UpdateConfigConnections(bool updateDataSourceToLocalDB, string projectName) { Configuration configuration; DBConnectionList configConnections = GetConfigConnections(out configuration); if (configuration != null && configConnections != null && configConnections.Count > 0) { foreach (DBConnection configConnection in configConnections) { if (configConnection != null && configConnection.IsSQLExpress) { if (updateDataSourceToLocalDB) { configConnection.ConvertToLocalDB(); } // For ALL Projects - Use InitialCatalog instead of AttachDBFileName // We are using NugetPackages to add connection strings in web.config file and by default it had "MultipleActiveResultSets=True" set configConnection.UpdateConnStrToUseInitialCatalog(projectName); } } configuration.Save(); return true; } return false; } //------------------------------------------------------------------------------ // Determines if LocalDB should be the default in new projects //------------------------------------------------------------------------------ private bool LocalDBIsDefault { get { return MVWUtilities.GetLocalDBIsDefault(_serviceProvider); } } //------------------------------------------------------------------------------ // Silently converts the SQL Express connections in web.config to LocalDB //------------------------------------------------------------------------------ public bool UpdateDBConnectionStringsForNewProject(bool updateDataSourceToLocalDB, string projectName) { return UpdateConfigConnections(LocalDBIsDefault && updateDataSourceToLocalDB, projectName); } private class DBConnection { private string _connectionName; private string _providerName; private string _connectionString; private bool _initializing; private SqlConnectionStringBuilder _sqlConnectionStringBuilder; private EntityConnectionStringBuilder _entityConnectionStringBuilder; //------------------------------------------------------------------------------ // Called by derived classes to initialize the connection //------------------------------------------------------------------------------ public void Initialize() { _initializing = true; try { OnInitialize(); } finally { _initializing = false; } } //------------------------------------------------------------------------------ // Overriden to initialize properties in derived classes //------------------------------------------------------------------------------ protected virtual void OnInitialize() { } //------------------------------------------------------------------------------ // True while initializing //------------------------------------------------------------------------------ public bool Initializing { get { return _initializing; } } //------------------------------------------------------------------------------ // The name of the connection //------------------------------------------------------------------------------ public string ConnectionName { get { return _connectionName; } set { if (!String.Equals(_connectionName, value, StringComparison.Ordinal)) { _connectionName = value; if (!Initializing) { OnConnectionNameChanged(); } } } } //------------------------------------------------------------------------------ // The name of the connection //------------------------------------------------------------------------------ protected virtual void OnConnectionNameChanged() { } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public string ProviderName { get { return _providerName; } set { if (!String.Equals(_providerName, value, StringComparison.Ordinal)) { _providerName = value; if (!Initializing) { OnProviderNameChanged(); } } } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ protected virtual void OnProviderNameChanged() { } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public string ConnectionString { get { return _connectionString; } set { if (!String.Equals(_connectionString, value, StringComparison.Ordinal)) { _connectionString = value; // Set up connection string builders _entityConnectionStringBuilder = null; _sqlConnectionStringBuilder = null; string provider = ProviderName; string connectionString = value; if (String.Equals(provider, "System.Data.EntityClient", StringComparison.OrdinalIgnoreCase)) { _entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionString); provider = _entityConnectionStringBuilder.Provider; connectionString = _entityConnectionStringBuilder.ProviderConnectionString; } if (string.IsNullOrEmpty(provider) // per spec we try sql for unspecied provider || String.Equals(provider, "System.Data.SqlClient", StringComparison.OrdinalIgnoreCase)) { _sqlConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString); } if (!Initializing) { OnConnectionStringChanged(); } } } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ protected virtual void OnConnectionStringChanged() { } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public string DataSource { get { if (_sqlConnectionStringBuilder != null) { return _sqlConnectionStringBuilder.DataSource; } return null; } set { if (_sqlConnectionStringBuilder != null) { _sqlConnectionStringBuilder.DataSource = value; UpdateConnectionString(); } } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public string AttachDBFilename { get { if (_sqlConnectionStringBuilder != null) { return _sqlConnectionStringBuilder.AttachDBFilename; } return null; } set { if (_sqlConnectionStringBuilder != null) { if (value != null) { _sqlConnectionStringBuilder.AttachDBFilename = value; } else { _sqlConnectionStringBuilder.Remove("AttachDBFilename"); } // Update ConnectionString UpdateConnectionString(); } } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public string InitialCatalog { get { if (_sqlConnectionStringBuilder != null) { return _sqlConnectionStringBuilder.InitialCatalog; } return null; } set { if (_sqlConnectionStringBuilder != null) { _sqlConnectionStringBuilder.InitialCatalog = value; } else { _sqlConnectionStringBuilder.Remove("Initial Catalog"); } UpdateConnectionString(); } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public bool UserInstance { get { if (_sqlConnectionStringBuilder != null) { return _sqlConnectionStringBuilder.UserInstance; } return false; } set { if (_sqlConnectionStringBuilder != null) { if (value == true) { _sqlConnectionStringBuilder.UserInstance = value; } else { _sqlConnectionStringBuilder.Remove("User Instance"); } UpdateConnectionString(); } } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ private void UpdateConnectionString() { if (_sqlConnectionStringBuilder != null) { if (_entityConnectionStringBuilder != null) { _entityConnectionStringBuilder.ProviderConnectionString = _sqlConnectionStringBuilder.ConnectionString; ConnectionString = _entityConnectionStringBuilder.ConnectionString; } else { ConnectionString = _sqlConnectionStringBuilder.ConnectionString; } } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public bool IsSQLExpress { get { string dataSource = DataSource; if (!string.IsNullOrEmpty(dataSource) && dataSource.StartsWith(@".\SQLEXPRESS", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } } //------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ public bool ConvertToLocalDB() { if (IsSQLExpress) { DataSource = @"(LocalDB)\v11.0"; UserInstance = false; return true; } return false; } public bool UpdateConnStrToUseInitialCatalog(string projectName) { if (string.IsNullOrEmpty(InitialCatalog)) { AttachDBFilename = null; InitialCatalog = MVWUtilities.GetUniqueInitialCatalogName(projectName); //Remove UserIntance since it is Initial Catalog UserInstance = false; return true; } return false; } } private class DBConnectionList : List<DBConnection> { } private class ConfigConnection : DBConnection { private readonly ConnectionStringSettings _connectionStringSettings; //------------------------------------------------------------------------------ // Construct the config connection //------------------------------------------------------------------------------ public ConfigConnection(IServiceProvider serviceProvider, ConnectionStringSettings connectionStringSettings) { _connectionStringSettings = connectionStringSettings; Initialize(); } //------------------------------------------------------------------------------ // Initialize the config connection //------------------------------------------------------------------------------ protected override void OnInitialize() { ConnectionName = _connectionStringSettings.Name; ProviderName = _connectionStringSettings.ProviderName; ConnectionString = _connectionStringSettings.ConnectionString; } //------------------------------------------------------------------------------ // Notification that the provider name changed //------------------------------------------------------------------------------ protected override void OnProviderNameChanged() { // Update the provider name in config if (!String.Equals(ProviderName, _connectionStringSettings.ProviderName, StringComparison.Ordinal)) { _connectionStringSettings.ProviderName = ProviderName; } } //------------------------------------------------------------------------------ // Notification that the connection string changed //------------------------------------------------------------------------------ protected override void OnConnectionStringChanged() { // Update the connection string in config if (!String.Equals(ConnectionString, _connectionStringSettings.ConnectionString, StringComparison.Ordinal)) { _connectionStringSettings.ConnectionString = ConnectionString; } } } } // ported from $/DevDiv/PU/WPT/venus/mvw/Util/MVWUtilities.cs static class MVWUtilities { public static ValueType GetProjectProperty<ValueType>(EnvDTE.Project project, string propertyName, ValueType defaultValue) { ValueType returnValue = defaultValue; try { if (project != null) { EnvDTE.Properties properties = project.Properties; if (properties != null) { EnvDTE.Property property = properties.Item(propertyName); if (property != null) { object objValue = property.Value; if (objValue != null) { returnValue = (ValueType)objValue; } } } } } catch (Exception) { } return returnValue; } public static string GetUniqueInitialCatalogName(string projectName) { //Initial Catalog=aspnet-{ProjectName}-{Timestamp} //Where {Timestamp} is yyyyMMddhhmmss //Where if ProjectName is of the form http://localhost/WebSite1/ we will use "WebSite1" as ProjectName // Similarly for FTP Projects string siteName = projectName; if (projectName.Contains("://")) { string[] urlSplit = projectName.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (urlSplit[urlSplit.Length - 1] != null) { siteName = urlSplit[urlSplit.Length - 1]; } } string catalogName = "aspnet-" + siteName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss"); return catalogName; } public static bool GetLocalDBIsDefault(IServiceProvider serviceProvider) { bool defaultValue = true; string localreg = GetLocalRegRoot(serviceProvider); if (!string.IsNullOrEmpty(localreg)) { string regkey = "HKEY_CURRENT_USER\\" + EnsureTrailingBackSlash(localreg) + "WebProjects"; return GetRegValue<bool>(serviceProvider, regkey, "LocalDBIsDefault", defaultValue); } return defaultValue; } private static string GetLocalRegRoot(IServiceProvider serviceProvider) { IVsShell vsShell = TemplateUtilities.GetService<IVsShell, IVsShell>(serviceProvider); Object obj; vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_VirtualRegistryRoot, out obj); if (obj != null && obj is string) { return (string)obj; } return null; } private static string EnsureTrailingBackSlash(string str) { if (str != null && !str.EndsWith("\\", StringComparison.Ordinal)) { str += "\\"; } return str; } private static ValueType GetRegValue<ValueType>(IServiceProvider serviceProvider, string key, string valueName, ValueType defaultValue) { ValueType returnValue = defaultValue; if (!string.IsNullOrEmpty(key)) { try { object objValue = Registry.GetValue(key, valueName, (object)defaultValue); if (objValue != null) { object objConvert = Convert.ChangeType(objValue, typeof(ValueType), CultureInfo.InvariantCulture); if (objConvert != null) { returnValue = (ValueType)objConvert; } } } catch { } } return returnValue; } } } #endif
using System.Diagnostics.Contracts; // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //* File: Channel.cs //* //* <EMAIL>Author: Tarun Anand ([....])</EMAIL> //* //* Purpose: Defines the general purpose remoting proxy //* //* Date: May 27, 1999 //* namespace System.Runtime.Remoting.Channels { using System; using System.Collections; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Metadata; using System.Runtime.Remoting.Proxies; using System.Runtime.Versioning; using System.Threading; using System.Security; using System.Security.Permissions; using System.Globalization; // ChannelServices [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal struct Perf_Contexts { internal volatile int cRemoteCalls; internal volatile int cChannels; }; [System.Runtime.InteropServices.ComVisible(true)] public sealed class ChannelServices { // This gets refreshed when a channel is registered/unregistered. private static volatile Object[] s_currentChannelData = null; [System.Security.SecuritySafeCritical] // static constructors should be safe to call static ChannelServices() { } internal static Object[] CurrentChannelData { [System.Security.SecurityCritical] // auto-generated get { if (s_currentChannelData == null) RefreshChannelData(); return s_currentChannelData; } } // CurrentChannelData // hide the default constructor private ChannelServices() { } // list of registered channels and a lock to take when adding or removing channels // Note that the channel list is read outside of the lock, which is why it's marked volatile. private static Object s_channelLock = new Object(); private static volatile RegisteredChannelList s_registeredChannels = new RegisteredChannelList(); // Private member variables // These have all been converted to getters and setters to get the effect of // per-AppDomain statics (note: statics are per-AppDomain now, so these members // could just be declared as statics on ChannelServices). private static long remoteCalls { get { return Thread.GetDomain().RemotingData.ChannelServicesData.remoteCalls; } set { Thread.GetDomain().RemotingData.ChannelServicesData.remoteCalls = value; } } private static volatile IMessageSink xCtxChannel; [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] [ResourceExposure(ResourceScope.None)] static unsafe extern Perf_Contexts* GetPrivateContextsPerfCounters(); [SecurityCritical] unsafe private static volatile Perf_Contexts *perf_Contexts = GetPrivateContextsPerfCounters(); [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterChannel(IChannel chnl, bool ensureSecurity) { RegisterChannelInternal(chnl, ensureSecurity); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] [Obsolete("Use System.Runtime.Remoting.ChannelServices.RegisterChannel(IChannel chnl, bool ensureSecurity) instead.", false)] public static void RegisterChannel(IChannel chnl) { RegisterChannelInternal(chnl, false/*ensureSecurity*/); } static bool unloadHandlerRegistered = false; [System.Security.SecurityCritical] // auto-generated unsafe internal static void RegisterChannelInternal(IChannel chnl, bool ensureSecurity) { // Validate arguments if(null == chnl) { throw new ArgumentNullException("chnl"); } Contract.EndContractBlock(); bool fLocked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(s_channelLock, ref fLocked); String chnlName = chnl.ChannelName; RegisteredChannelList regChnlList = s_registeredChannels; // Check to make sure that the channel has not been registered if((chnlName == null) || (chnlName.Length == 0) || (-1 == regChnlList.FindChannelIndex(chnl.ChannelName))) { if (ensureSecurity) { ISecurableChannel securableChannel = chnl as ISecurableChannel; if (securableChannel != null) securableChannel.IsSecured = ensureSecurity; else throw new RemotingException(Environment.GetResourceString("Remoting_Channel_CannotBeSecured", chnl.ChannelName??chnl.ToString())); } RegisteredChannel[] oldList = regChnlList.RegisteredChannels; RegisteredChannel[] newList = null; if (oldList == null) { newList = new RegisteredChannel[1]; } else newList = new RegisteredChannel[oldList.Length + 1]; if (!unloadHandlerRegistered && !(chnl is CrossAppDomainChannel)) { // Register a unload handler only once and if the channel being registered // is not the x-domain channel. x-domain channel does nothing inside its // StopListening implementation AppDomain.CurrentDomain.DomainUnload += new EventHandler(UnloadHandler); unloadHandlerRegistered = true; } // Add the interface to the array in priority order int priority = chnl.ChannelPriority; int current = 0; // Find the place in the array to insert while (current < oldList.Length) { RegisteredChannel oldChannel = oldList[current]; if (priority > oldChannel.Channel.ChannelPriority) { newList[current] = new RegisteredChannel(chnl); break; } else { newList[current] = oldChannel; current++; } } if (current == oldList.Length) { // chnl has lower priority than all old channels, so we insert // it at the end of the list. newList[oldList.Length] = new RegisteredChannel(chnl); } else { // finish copying rest of the old channels while (current < oldList.Length) { newList[current + 1] = oldList[current]; current++; } } if (perf_Contexts != null) { perf_Contexts->cChannels++; } s_registeredChannels = new RegisteredChannelList(newList); } else { throw new RemotingException(Environment.GetResourceString("Remoting_ChannelNameAlreadyRegistered", chnl.ChannelName)); } RefreshChannelData(); } // lock (s_channelLock) finally { if (fLocked) { Monitor.Exit(s_channelLock); } } } // RegisterChannelInternal [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] unsafe public static void UnregisterChannel(IChannel chnl) { // we allow null to be passed in, so we can use this api to trigger the // refresh of the channel data < bool fLocked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(s_channelLock, ref fLocked); if (chnl != null) { RegisteredChannelList regChnlList = s_registeredChannels; // Check to make sure that the channel has been registered int matchingIdx = regChnlList.FindChannelIndex(chnl); if(-1 == matchingIdx) { throw new RemotingException(Environment.GetResourceString("Remoting_ChannelNotRegistered", chnl.ChannelName)); } RegisteredChannel[] oldList = regChnlList.RegisteredChannels; RegisteredChannel[] newList = null; Contract.Assert((oldList != null) && (oldList.Length != 0), "channel list should not be empty"); newList = new RegisteredChannel[oldList.Length - 1]; // Call stop listening on the channel if it is a receiver. IChannelReceiver srvChannel = chnl as IChannelReceiver; if (srvChannel != null) srvChannel.StopListening(null); int current = 0; int oldPos = 0; while (oldPos < oldList.Length) { if (oldPos == matchingIdx) { oldPos++; } else { newList[current] = oldList[oldPos]; current++; oldPos++; } } if (perf_Contexts != null) { perf_Contexts->cChannels--; } s_registeredChannels = new RegisteredChannelList(newList); } RefreshChannelData(); } // lock (s_channelLock) finally { if (fLocked) { Monitor.Exit(s_channelLock); } } } // UnregisterChannel public static IChannel[] RegisteredChannels { [System.Security.SecurityCritical] // auto-generated_required get { RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; if (0 == count) { return new IChannel[0]; } else { // we hide the CrossAppDomainChannel, so the number of visible // channels is one less than the number of registered channels. int visibleChannels = count - 1; // Copy the array of visible channels into a new array // and return int co = 0; IChannel[] temp = new IChannel[visibleChannels]; for (int i = 0; i < count; i++) { IChannel channel = regChnlList.GetChannel(i); // add the channel to the array if it is not the CrossAppDomainChannel if (!(channel is CrossAppDomainChannel)) temp[co++] = channel; } return temp; } } } // RegisteredChannels [System.Security.SecurityCritical] // auto-generated internal static IMessageSink CreateMessageSink(String url, Object data, out String objectURI) { BCLDebug.Trace("REMOTE", "ChannelServices::CreateMessageSink for url " + url + "\n"); IMessageSink msgSink = null; objectURI = null; RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; for(int i = 0; i < count; i++) { if(regChnlList.IsSender(i)) { IChannelSender chnl = (IChannelSender)regChnlList.GetChannel(i); msgSink = chnl.CreateMessageSink(url, data, out objectURI); if(msgSink != null) break; } } // If the object uri has not been set, set it to the url as // default value if(null == objectURI) { objectURI = url; } return msgSink; } // CreateMessageSink [System.Security.SecurityCritical] // auto-generated internal static IMessageSink CreateMessageSink(Object data) { String objectUri; return CreateMessageSink(null, data, out objectUri); } // CreateMessageSink [System.Security.SecurityCritical] // auto-generated_required public static IChannel GetChannel(String name) { RegisteredChannelList regChnlList = s_registeredChannels; int matchingIdx = regChnlList.FindChannelIndex(name); if(0 <= matchingIdx) { IChannel channel = regChnlList.GetChannel(matchingIdx); if ((channel is CrossAppDomainChannel) || (channel is CrossContextChannel)) return null; else return channel; } else { return null; } } // GetChannel [System.Security.SecurityCritical] // auto-generated_required public static String[] GetUrlsForObject(MarshalByRefObject obj) { if(null == obj) { return null; } RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; Hashtable table = new Hashtable(); bool fServer; Identity id = MarshalByRefObject.GetIdentity(obj, out fServer); if(null != id) { String uri = id.ObjURI; if (null != uri) { for(int i = 0; i < count; i++) { if(regChnlList.IsReceiver(i)) { try { String[] urls = ((IChannelReceiver)regChnlList.GetChannel(i)).GetUrlsForUri(uri); // Add the strings to the table for(int j = 0; j < urls.Length; j++) { table.Add(urls[j], urls[j]); } } catch(NotSupportedException ) { // We do not count the channels that do not // support this method } } } } } // copy url's into string array ICollection keys = table.Keys; String[] urlList = new String[keys.Count]; int co = 0; foreach (String key in keys) { urlList[co++] = key; } return urlList; } // Find the channel message sink associated with a given proxy // < [System.Security.SecurityCritical] // auto-generated internal static IMessageSink GetChannelSinkForProxy(Object obj) { IMessageSink sink = null; if (RemotingServices.IsTransparentProxy(obj)) { RealProxy rp = RemotingServices.GetRealProxy(obj); RemotingProxy remProxy = rp as RemotingProxy; if (null != remProxy) { Identity idObj = remProxy.IdentityObject; Contract.Assert(null != idObj,"null != idObj"); sink = idObj.ChannelSink; } } return sink; } // GetChannelSinkForProxy // Get the message sink dictionary of properties for a given proxy [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static IDictionary GetChannelSinkProperties(Object obj) { IMessageSink sink = GetChannelSinkForProxy(obj); IClientChannelSink chnlSink = sink as IClientChannelSink; if (null != chnlSink) { // collect dictionaries for all channel sinks and return // aggregate dictionary ArrayList dictionaries = new ArrayList(); do { IDictionary dict = chnlSink.Properties; if (dict != null) dictionaries.Add(dict); chnlSink = chnlSink.NextChannelSink; } while (chnlSink != null); return new AggregateDictionary(dictionaries); } else { IDictionary dict = sink as IDictionary; if(null != dict) { return dict; } else { return null; } } } // GetChannelSinkProperties internal static IMessageSink GetCrossContextChannelSink() { if(null == xCtxChannel) { xCtxChannel = CrossContextChannel.MessageSink; } return xCtxChannel; } // GetCrossContextChannelSink #if DEBUG // A few methods to count the number of calls made across appdomains, // processes and machines internal static long GetNumberOfRemoteCalls() { return remoteCalls; } // GetNumberOfRemoteCalls #endif //DEBUG [System.Security.SecurityCritical] // auto-generated unsafe internal static void IncrementRemoteCalls(long cCalls) { remoteCalls += cCalls; if (perf_Contexts != null) perf_Contexts->cRemoteCalls += (int)cCalls; } // IncrementRemoteCalls [System.Security.SecurityCritical] // auto-generated internal static void IncrementRemoteCalls() { IncrementRemoteCalls( 1 ); } // IncrementRemoteCalls [System.Security.SecurityCritical] // auto-generated internal static void RefreshChannelData() { bool fLocked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(s_channelLock, ref fLocked); s_currentChannelData = CollectChannelDataFromChannels(); } finally { if (fLocked) { Monitor.Exit(s_channelLock); } } } // RefreshChannelData [System.Security.SecurityCritical] // auto-generated private static Object[] CollectChannelDataFromChannels() { // Ensure that our native cross-context & cross-domain channels // are registered RemotingServices.RegisterWellKnownChannels(); RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; // Compute the number of channels that implement IChannelReceiver int numChnls = regChnlList.ReceiverCount; // Allocate array for channel data Object[] data = new Object[numChnls]; // we need to remove null entries int nonNullDataCount = 0; // Set the channel data, names and mime types for (int i = 0, j = 0; i < count; i++) { IChannel chnl = regChnlList.GetChannel(i); if (null == chnl) { throw new RemotingException(Environment.GetResourceString("Remoting_ChannelNotRegistered", "")); } if (regChnlList.IsReceiver(i)) { BCLDebug.Trace("REMOTE", "Setting info for receiver " + j.ToString(CultureInfo.InvariantCulture) + "\n"); // Extract the data Object channelData = ((IChannelReceiver)chnl).ChannelData; data[j] = channelData; if (channelData != null) nonNullDataCount++; // Increment the counter j++; } } if (nonNullDataCount != numChnls) { // there were null entries, so remove them. Object[] nonNullData = new Object[nonNullDataCount]; int nonNullCounter = 0; for (int co = 0; co < numChnls; co++) { Object channelData = data[co]; if (channelData != null) nonNullData[nonNullCounter++] = channelData; } data = nonNullData; } return data; } // CollectChannelDataFromChannels // Checks to make sure the remote method being invoked is callable static bool IsMethodReallyPublic(MethodInfo mi) { if (!mi.IsPublic || mi.IsStatic) return false; if (!mi.IsGenericMethod) return true; foreach (Type t in mi.GetGenericArguments()) if (!t.IsVisible) return false; return true; } //-------------------------------------------------------------------- //----------------------- Dispatch Support ------------------------ //-------------------------------------------------------------------- [System.Security.SecurityCritical] // auto-generated_required public static ServerProcessing DispatchMessage( IServerChannelSinkStack sinkStack, IMessage msg, out IMessage replyMsg) { ServerProcessing processing = ServerProcessing.Complete; replyMsg = null; try { if(null == msg) { throw new ArgumentNullException("msg"); } BCLDebug.Trace("REMOTE", "Dispatching for URI " + InternalSink.GetURI(msg)); // we must switch to the target context of the object and call the context chains etc... // Currenly XContextChannel does exactly so. So this method is just a wrapper.. // < // Make sure that incoming calls are counted as a remote call. This way it // makes more sense on a server. IncrementRemoteCalls(); // Check if the object has been disconnected or if it is // a well known object then we have to create it lazily. ServerIdentity srvId = CheckDisconnectedOrCreateWellKnownObject(msg); // Make sure that this isn't an AppDomain object since we don't allow // calls to the AppDomain from out of process (and x-process calls // are always dispatched through this method) if (srvId.ServerType == typeof(System.AppDomain)) { throw new RemotingException( Environment.GetResourceString( "Remoting_AppDomainsCantBeCalledRemotely")); } IMethodCallMessage mcm = msg as IMethodCallMessage; if (mcm == null) { // It's a plain IMessage, so just check to make sure that the // target object implements IMessageSink and dispatch synchronously. if (!typeof(IMessageSink).IsAssignableFrom(srvId.ServerType)) { throw new RemotingException( Environment.GetResourceString( "Remoting_AppDomainsCantBeCalledRemotely")); } processing = ServerProcessing.Complete; replyMsg = ChannelServices.GetCrossContextChannelSink().SyncProcessMessage(msg); } else { // It's an IMethodCallMessage. // Check if the method is one way. Dispatch one way calls in // an asynchronous manner MethodInfo method = (MethodInfo)mcm.MethodBase; // X-process / X-machine calls should be to non-static // public methods only! Non-public or static methods can't // be called remotely. if (!IsMethodReallyPublic(method) && !RemotingServices.IsMethodAllowedRemotely(method)) { throw new RemotingException( Environment.GetResourceString( "Remoting_NonPublicOrStaticCantBeCalledRemotely")); } RemotingMethodCachedData cache = (RemotingMethodCachedData) InternalRemotingServices.GetReflectionCachedData(method); /* */ if(RemotingServices.IsOneWay(method)) { processing = ServerProcessing.OneWay; ChannelServices.GetCrossContextChannelSink().AsyncProcessMessage(msg, null); } else { // regular processing processing = ServerProcessing.Complete; if (!srvId.ServerType.IsContextful) { Object[] args = new Object[]{msg, srvId.ServerContext}; replyMsg = (IMessage) CrossContextChannel.SyncProcessMessageCallback(args); } else replyMsg = ChannelServices.GetCrossContextChannelSink().SyncProcessMessage(msg); } } // end of case for IMethodCallMessage } catch(Exception e) { if(processing != ServerProcessing.OneWay) { try { IMethodCallMessage mcm = (IMethodCallMessage) ((msg!=null)?msg:new ErrorMessage()); replyMsg = (IMessage)new ReturnMessage(e, mcm); if (msg != null) { ((ReturnMessage)replyMsg).SetLogicalCallContext( (LogicalCallContext) msg.Properties[Message.CallContextKey]); } } catch(Exception ) { // Fatal exception .. ignore } } } return processing; } // DispatchMessage // This method is used by the channel to dispatch the incoming messages // to the server side chain(s) based on the URI embedded in the message. // The URI uniquely identifies the receiving object. // [System.Security.SecurityCritical] // auto-generated_required public static IMessage SyncDispatchMessage(IMessage msg) { IMessage msgRet = null; bool fIsOneWay = false; try { if(null == msg) { throw new ArgumentNullException("msg"); } // For ContextBoundObject's, // we must switch to the target context of the object and call the context chains etc... // Currenly XContextChannel does exactly so. So this method is just a wrapper.. // Make sure that incoming calls are counted as a remote call. This way it // makes more sense on a server. IncrementRemoteCalls(); // < if (!(msg is TransitionCall)) { // Check if the object has been disconnected or if it is // a well known object then we have to create it lazily. CheckDisconnectedOrCreateWellKnownObject(msg); MethodBase method = ((IMethodMessage)msg).MethodBase; // Check if the method is one way. Dispatch one way calls in // an asynchronous manner fIsOneWay = RemotingServices.IsOneWay(method); } // < IMessageSink nextSink = ChannelServices.GetCrossContextChannelSink(); if(!fIsOneWay) { msgRet = nextSink.SyncProcessMessage(msg); } else { nextSink.AsyncProcessMessage(msg, null); } } catch(Exception e) { if(!fIsOneWay) { try { IMethodCallMessage mcm = (IMethodCallMessage) ((msg!=null)?msg:new ErrorMessage()); msgRet = (IMessage)new ReturnMessage(e, mcm); if (msg!=null) { ((ReturnMessage)msgRet).SetLogicalCallContext( mcm.LogicalCallContext); } } catch(Exception ) { // Fatal exception .. ignore } } } return msgRet; } // This method is used by the channel to dispatch the incoming messages // to the server side chain(s) based on the URI embedded in the message. // The URI uniquely identifies the receiving object. // [System.Security.SecurityCritical] // auto-generated_required public static IMessageCtrl AsyncDispatchMessage(IMessage msg, IMessageSink replySink) { IMessageCtrl ctrl = null; try { if(null == msg) { throw new ArgumentNullException("msg"); } // we must switch to the target context of the object and call the context chains etc... // Currenly XContextChannel does exactly so. So this method is just a wrapper.. // Make sure that incoming calls are counted as a remote call. This way it // makes more sense on a server. IncrementRemoteCalls(); if (!(msg is TransitionCall)) { // Check if the object has been disconnected or if it is // a well known object then we have to create it lazily. CheckDisconnectedOrCreateWellKnownObject(msg); } // < ctrl = ChannelServices.GetCrossContextChannelSink().AsyncProcessMessage(msg, replySink); } catch(Exception e) { if(null != replySink) { try { IMethodCallMessage mcm = (IMethodCallMessage)msg; ReturnMessage retMsg = new ReturnMessage(e, (IMethodCallMessage)msg); if (msg!=null) { retMsg.SetLogicalCallContext(mcm.LogicalCallContext); } replySink.SyncProcessMessage(retMsg); } catch(Exception ) { // Fatal exception... ignore } } } return ctrl; } // AsyncDispatchMessage // Creates a channel sink chain (adds special dispatch sink to the end of the chain) [System.Security.SecurityCritical] // auto-generated_required public static IServerChannelSink CreateServerChannelSinkChain( IServerChannelSinkProvider provider, IChannelReceiver channel) { if (provider == null) return new DispatchChannelSink(); // add dispatch provider to end (first find last provider) IServerChannelSinkProvider lastProvider = provider; while (lastProvider.Next != null) lastProvider = lastProvider.Next; lastProvider.Next = new DispatchChannelSinkProvider(); IServerChannelSink sinkChain = provider.CreateSink(channel); // remove dispatch provider from end lastProvider.Next = null; return sinkChain; } // CreateServerChannelSinkChain // Check if the object has been disconnected or if it is // a well known object then we have to create it lazily. [System.Security.SecurityCritical] // auto-generated internal static ServerIdentity CheckDisconnectedOrCreateWellKnownObject(IMessage msg) { ServerIdentity ident = InternalSink.GetServerIdentity(msg); BCLDebug.Trace("REMOTE", "Identity found = " + (ident == null ? "null" : "ServerIdentity")); // If the identity is null, then we should check whether the // request if for a well known object. If yes, then we should // create the well known object lazily and marshal it. if ((ident == null) || ident.IsRemoteDisconnected()) { String uri = InternalSink.GetURI(msg); BCLDebug.Trace("REMOTE", "URI " + uri); if (uri != null) { ServerIdentity newIdent = RemotingConfigHandler.CreateWellKnownObject(uri); if (newIdent != null) { // The uri was a registered wellknown object. ident = newIdent; BCLDebug.Trace("REMOTE", "Identity created = " + (ident == null ? "null" : "ServerIdentity")); } } } if ((ident == null) || (ident.IsRemoteDisconnected())) { String uri = InternalSink.GetURI(msg); throw new RemotingException(Environment.GetResourceString("Remoting_Disconnected",uri)); } return ident; } // Channel Services AppDomain Unload Event Handler [System.Security.SecurityCritical] // auto-generated internal static void UnloadHandler(Object sender, EventArgs e) { StopListeningOnAllChannels(); } [System.Security.SecurityCritical] // auto-generated private static void StopListeningOnAllChannels() { try { RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; for(int i = 0; i < count; i++) { if(regChnlList.IsReceiver(i)) { IChannelReceiver chnl = (IChannelReceiver)regChnlList.GetChannel(i); chnl.StopListening(null); } } } catch (Exception) { // Ignore ... appdomain is shutting down.. } } // // INTERNAL PROFILER NOTIFICATION SERVICES // [System.Security.SecurityCritical] // auto-generated internal static void NotifyProfiler(IMessage msg, RemotingProfilerEvent profilerEvent) { switch (profilerEvent) { case RemotingProfilerEvent.ClientSend: { if (RemotingServices.CORProfilerTrackRemoting()) { Guid g; RemotingServices.CORProfilerRemotingClientSendingMessage(out g, false); if (RemotingServices.CORProfilerTrackRemotingCookie()) msg.Properties["CORProfilerCookie"] = g; } break; } // case RemotingProfilerEvent.ClientSend case RemotingProfilerEvent.ClientReceive: { if (RemotingServices.CORProfilerTrackRemoting()) { Guid g = Guid.Empty; if (RemotingServices.CORProfilerTrackRemotingCookie()) { Object obj = msg.Properties["CORProfilerCookie"]; if (obj != null) { g = (Guid) obj; } } RemotingServices.CORProfilerRemotingClientReceivingReply(g, false); } break; } // case RemotingProfilerEvent.ClientReceive } // switch (event) } // NotifyProfiler // This is a helper used by UrlObjRef's. // Finds an http channel and returns first url for this object. [System.Security.SecurityCritical] // auto-generated internal static String FindFirstHttpUrlForObject(String objectUri) { if (objectUri == null) return null; RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; for (int i = 0; i < count; i++) { if(regChnlList.IsReceiver(i)) { IChannelReceiver chnl = (IChannelReceiver)regChnlList.GetChannel(i); String chnlType = chnl.GetType().FullName; if ((String.CompareOrdinal(chnlType, "System.Runtime.Remoting.Channels.Http.HttpChannel") == 0) || (String.CompareOrdinal(chnlType, "System.Runtime.Remoting.Channels.Http.HttpServerChannel") == 0)) { String[] urls = chnl.GetUrlsForUri(objectUri); if ((urls != null) && (urls.Length > 0)) return urls[0]; } } } return null; } // FindFirstHttpUrlForObject // // DEBUG Helpers // Note: These methods should be included even in retail builds so that // they can be called from the debugger. // #if DEBUG internal static void DumpRegisteredChannels() { // To use from cordbg: // f System.Runtime.Remoting.Channels.ChannelServices::DumpRegisteredChannels RegisteredChannelList regChnlList = s_registeredChannels; int count = regChnlList.Count; Console.Error.WriteLine("Registered Channels:"); for (int i = 0; i < count; i++) { IChannel chnl = regChnlList.GetChannel(i); Console.Error.WriteLine(chnl); } } // DumpRegisteredChannels #endif // DEBUG } // class ChannelServices // used by ChannelServices.NotifyProfiler [Serializable] internal enum RemotingProfilerEvent { ClientSend, ClientReceive } // RemotingProfilerEvent internal class RegisteredChannel { // private member variables private IChannel channel; private byte flags; private const byte SENDER = 0x1; private const byte RECEIVER = 0x2; internal RegisteredChannel(IChannel chnl) { channel = chnl; flags = 0; if(chnl is IChannelSender) { flags |= SENDER; } if(chnl is IChannelReceiver) { flags |= RECEIVER; } } internal virtual IChannel Channel { get { return channel; } } internal virtual bool IsSender() { return ((flags & SENDER) != 0); } internal virtual bool IsReceiver() { return ((flags & RECEIVER) != 0); } }// class RegisteredChannel // This list should be considered immutable once created. // <STRIP>Ideally, this class would encapsulate more functionality, but // to help minimize the number of changes in the RTM tree, only // a small amount of code has been moved here.</STRIP> internal class RegisteredChannelList { private RegisteredChannel[] _channels; internal RegisteredChannelList() { _channels = new RegisteredChannel[0]; } // RegisteredChannelList internal RegisteredChannelList(RegisteredChannel[] channels) { _channels = channels; } // RegisteredChannelList internal RegisteredChannel[] RegisteredChannels { get { return _channels; } } // RegisteredChannels internal int Count { get { if (_channels == null) return 0; return _channels.Length; } } // Count internal IChannel GetChannel(int index) { return _channels[index].Channel; } // GetChannel internal bool IsSender(int index) { return _channels[index].IsSender(); } // IsSender internal bool IsReceiver(int index) { return _channels[index].IsReceiver(); } // IsReceiver internal int ReceiverCount { get { if (_channels == null) return 0; int total = 0; for (int i = 0; i < _channels.Length; i++) { if (IsReceiver(i)) total++; } return total; } } // ReceiverCount internal int FindChannelIndex(IChannel channel) { Object chnlAsObject = (Object)channel; for (int i = 0; i < _channels.Length; i++) { if (chnlAsObject == (Object)GetChannel(i)) return i; } return -1; } // FindChannelIndex [System.Security.SecurityCritical] // auto-generated internal int FindChannelIndex(String name) { for (int i = 0; i < _channels.Length; i++) { if(String.Compare(name, GetChannel(i).ChannelName, StringComparison.OrdinalIgnoreCase) == 0) return i; } return -1; } // FindChannelIndex } // class RegisteredChannelList internal class ChannelServicesData { internal long remoteCalls = 0; internal CrossContextChannel xctxmessageSink = null; internal CrossAppDomainChannel xadmessageSink = null; internal bool fRegisterWellKnownChannels = false; } // // Terminator sink used for profiling so that we can intercept asynchronous // replies on the server side. // /* package scope */ internal class ServerAsyncReplyTerminatorSink : IMessageSink { internal IMessageSink _nextSink; internal ServerAsyncReplyTerminatorSink(IMessageSink nextSink) { Contract.Assert(nextSink != null, "null IMessageSink passed to ServerAsyncReplyTerminatorSink ctor."); _nextSink = nextSink; } [System.Security.SecurityCritical] // auto-generated public virtual IMessage SyncProcessMessage(IMessage replyMsg) { // If this class has been brought into the picture, then the following must be true. Contract.Assert(RemotingServices.CORProfilerTrackRemoting(), "CORProfilerTrackRemoting returned false, but we're in AsyncProcessMessage!"); Contract.Assert(RemotingServices.CORProfilerTrackRemotingAsync(), "CORProfilerTrackRemoting returned false, but we're in AsyncProcessMessage!"); Guid g; // Notify the profiler that we are receiving an async reply from the server-side RemotingServices.CORProfilerRemotingServerSendingReply(out g, true); // If GUID cookies are active, then we save it for the other end of the channel if (RemotingServices.CORProfilerTrackRemotingCookie()) replyMsg.Properties["CORProfilerCookie"] = g; // Now that we've done the intercepting, pass the message on to the regular chain return _nextSink.SyncProcessMessage(replyMsg); } [System.Security.SecurityCritical] // auto-generated public virtual IMessageCtrl AsyncProcessMessage(IMessage replyMsg, IMessageSink replySink) { // Since this class is only used for intercepting async replies, this function should // never get called. (Async replies are synchronous, ironically) Contract.Assert(false, "ServerAsyncReplyTerminatorSink.AsyncProcessMessage called!"); return null; } public IMessageSink NextSink { [System.Security.SecurityCritical] // auto-generated get { return _nextSink; } } // Do I need a finalize here? } }
// ----------------------------------------------------------------------------------------- // <copyright file="MemberAssignmentAnalysis.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Table.Queryable { #region Namespaces. using Microsoft.WindowsAzure.Storage.Core; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; #endregion Namespaces. internal class MemberAssignmentAnalysis : ALinqExpressionVisitor { #region Fields. internal static readonly Expression[] EmptyExpressionArray = new Expression[0]; private readonly Expression entity; private Exception incompatibleAssignmentsException; private bool multiplePathsFound; private List<Expression> pathFromEntity; #endregion Fields. #region Constructor. private MemberAssignmentAnalysis(Expression entity) { Debug.Assert(entity != null, "entity != null"); this.entity = entity; this.pathFromEntity = new List<Expression>(); } #endregion Constructor. #region Properties. internal Exception IncompatibleAssignmentsException { get { return this.incompatibleAssignmentsException; } } internal bool MultiplePathsFound { get { return this.multiplePathsFound; } } #endregion Properites. #region Methods. internal static MemberAssignmentAnalysis Analyze(Expression entityInScope, Expression assignmentExpression) { Debug.Assert(entityInScope != null, "entityInScope != null"); Debug.Assert(assignmentExpression != null, "assignmentExpression != null"); MemberAssignmentAnalysis result = new MemberAssignmentAnalysis(entityInScope); result.Visit(assignmentExpression); return result; } internal Exception CheckCompatibleAssignments(Type targetType, ref MemberAssignmentAnalysis previous) { if (previous == null) { previous = this; return null; } Expression[] previousExpressions = previous.GetExpressionsToTargetEntity(); Expression[] candidateExpressions = this.GetExpressionsToTargetEntity(); return CheckCompatibleAssignments(targetType, previousExpressions, candidateExpressions); } internal override Expression Visit(Expression expression) { if (this.multiplePathsFound || this.incompatibleAssignmentsException != null) { return expression; } return base.Visit(expression); } internal override Expression VisitConditional(ConditionalExpression c) { Expression result; var nullCheck = ResourceBinder.PatternRules.MatchNullCheck(this.entity, c); if (nullCheck.Match) { this.Visit(nullCheck.AssignExpression); result = c; } else { result = base.VisitConditional(c); } return result; } internal override Expression VisitParameter(ParameterExpression p) { if (p == this.entity) { if (this.pathFromEntity.Count != 0) { this.multiplePathsFound = true; } else { this.pathFromEntity.Add(p); } } return p; } internal override Expression VisitMemberInit(MemberInitExpression init) { Expression result = init; MemberAssignmentAnalysis previousNested = null; foreach (var binding in init.Bindings) { MemberAssignment assignment = binding as MemberAssignment; if (assignment == null) { continue; } MemberAssignmentAnalysis nested = MemberAssignmentAnalysis.Analyze(this.entity, assignment.Expression); if (nested.MultiplePathsFound) { this.multiplePathsFound = true; break; } Exception incompatibleException = nested.CheckCompatibleAssignments(init.Type, ref previousNested); if (incompatibleException != null) { this.incompatibleAssignmentsException = incompatibleException; break; } if (this.pathFromEntity.Count == 0) { this.pathFromEntity.AddRange(nested.GetExpressionsToTargetEntity()); } } return result; } internal override Expression VisitMemberAccess(MemberExpression m) { Expression result = base.VisitMemberAccess(m); if (this.pathFromEntity.Contains(m.Expression)) { this.pathFromEntity.Add(m); } return result; } internal override Expression VisitMethodCall(MethodCallExpression call) { if (ReflectionUtil.IsSequenceMethod(call.Method, SequenceMethod.Select)) { this.Visit(call.Arguments[0]); return call; } return base.VisitMethodCall(call); } internal Expression[] GetExpressionsBeyondTargetEntity() { Debug.Assert(!this.multiplePathsFound, "this.multiplePathsFound -- otherwise GetExpressionsToTargetEntity won't return reliable (consistent) results"); if (this.pathFromEntity.Count <= 1) { return EmptyExpressionArray; } Expression[] result = new Expression[1]; result[0] = this.pathFromEntity[this.pathFromEntity.Count - 1]; return result; } internal Expression[] GetExpressionsToTargetEntity() { Debug.Assert(!this.multiplePathsFound, "this.multiplePathsFound -- otherwise GetExpressionsToTargetEntity won't return reliable (consistent) results"); if (this.pathFromEntity.Count <= 1) { return EmptyExpressionArray; } Expression[] result = new Expression[this.pathFromEntity.Count - 1]; for (int i = 0; i < result.Length; i++) { result[i] = this.pathFromEntity[i]; } return result; } private static Exception CheckCompatibleAssignments(Type targetType, Expression[] previous, Expression[] candidate) { Debug.Assert(targetType != null, "targetType != null"); Debug.Assert(previous != null, "previous != null"); Debug.Assert(candidate != null, "candidate != null"); if (previous.Length != candidate.Length) { throw CheckCompatibleAssignmentsFail(targetType, previous, candidate); } for (int i = 0; i < previous.Length; i++) { Expression p = previous[i]; Expression c = candidate[i]; if (p.NodeType != c.NodeType) { throw CheckCompatibleAssignmentsFail(targetType, previous, candidate); } if (p == c) { continue; } if (p.NodeType != ExpressionType.MemberAccess) { return CheckCompatibleAssignmentsFail(targetType, previous, candidate); } if (((MemberExpression)p).Member.Name != ((MemberExpression)c).Member.Name) { return CheckCompatibleAssignmentsFail(targetType, previous, candidate); } } return null; } private static Exception CheckCompatibleAssignmentsFail(Type targetType, Expression[] previous, Expression[] candidate) { Debug.Assert(targetType != null, "targetType != null"); Debug.Assert(previous != null, "previous != null"); Debug.Assert(candidate != null, "candidate != null"); return new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqProjectionMemberAssignmentMismatch, targetType.FullName, previous.LastOrDefault(), candidate.LastOrDefault())); } #endregion Methods. } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>MetadataStore</c> resource.</summary> public sealed partial class MetadataStoreName : gax::IResourceName, sys::IEquatable<MetadataStoreName> { /// <summary>The possible contents of <see cref="MetadataStoreName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c> /// . /// </summary> ProjectLocationMetadataStore = 1, } private static gax::PathTemplate s_projectLocationMetadataStore = new gax::PathTemplate("projects/{project}/locations/{location}/metadataStores/{metadata_store}"); /// <summary>Creates a <see cref="MetadataStoreName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="MetadataStoreName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static MetadataStoreName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new MetadataStoreName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="MetadataStoreName"/> with the pattern /// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MetadataStoreName"/> constructed from the provided ids.</returns> public static MetadataStoreName FromProjectLocationMetadataStore(string projectId, string locationId, string metadataStoreId) => new MetadataStoreName(ResourceNameType.ProjectLocationMetadataStore, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), metadataStoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MetadataStoreName"/> with pattern /// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MetadataStoreName"/> with pattern /// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c>. /// </returns> public static string Format(string projectId, string locationId, string metadataStoreId) => FormatProjectLocationMetadataStore(projectId, locationId, metadataStoreId); /// <summary> /// Formats the IDs into the string representation of this <see cref="MetadataStoreName"/> with pattern /// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MetadataStoreName"/> with pattern /// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c>. /// </returns> public static string FormatProjectLocationMetadataStore(string projectId, string locationId, string metadataStoreId) => s_projectLocationMetadataStore.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId))); /// <summary> /// Parses the given resource name string into a new <see cref="MetadataStoreName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c></description> /// </item> /// </list> /// </remarks> /// <param name="metadataStoreName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="MetadataStoreName"/> if successful.</returns> public static MetadataStoreName Parse(string metadataStoreName) => Parse(metadataStoreName, false); /// <summary> /// Parses the given resource name string into a new <see cref="MetadataStoreName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="metadataStoreName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="MetadataStoreName"/> if successful.</returns> public static MetadataStoreName Parse(string metadataStoreName, bool allowUnparsed) => TryParse(metadataStoreName, allowUnparsed, out MetadataStoreName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MetadataStoreName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c></description> /// </item> /// </list> /// </remarks> /// <param name="metadataStoreName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="MetadataStoreName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string metadataStoreName, out MetadataStoreName result) => TryParse(metadataStoreName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MetadataStoreName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="metadataStoreName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="MetadataStoreName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string metadataStoreName, bool allowUnparsed, out MetadataStoreName result) { gax::GaxPreconditions.CheckNotNull(metadataStoreName, nameof(metadataStoreName)); gax::TemplatedResourceName resourceName; if (s_projectLocationMetadataStore.TryParseName(metadataStoreName, out resourceName)) { result = FromProjectLocationMetadataStore(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(metadataStoreName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private MetadataStoreName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string metadataStoreId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; MetadataStoreId = metadataStoreId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="MetadataStoreName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param> public MetadataStoreName(string projectId, string locationId, string metadataStoreId) : this(ResourceNameType.ProjectLocationMetadataStore, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), metadataStoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>MetadataStore</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string MetadataStoreId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationMetadataStore: return s_projectLocationMetadataStore.Expand(ProjectId, LocationId, MetadataStoreId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as MetadataStoreName); /// <inheritdoc/> public bool Equals(MetadataStoreName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(MetadataStoreName a, MetadataStoreName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(MetadataStoreName a, MetadataStoreName b) => !(a == b); } public partial class MetadataStore { /// <summary> /// <see cref="gcav::MetadataStoreName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::MetadataStoreName MetadataStoreName { get => string.IsNullOrEmpty(Name) ? null : gcav::MetadataStoreName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; using System.Windows.Media.Imaging; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer; namespace NuGet.Dialog.Providers { internal class PackageItem : IVsExtension, INotifyPropertyChanged { private readonly PackagesProviderBase _provider; private readonly IPackage _packageIdentity; private readonly bool _isUpdateItem, _isPrerelease; private bool _isSelected; private readonly ObservableCollection<Project> _referenceProjectNames; private readonly SemanticVersion _oldPackageVersion; private IEnumerable<object> _displayDependencies; public PackageItem(PackagesProviderBase provider, IPackage package, SemanticVersion oldPackageVersion = null) : this(provider, package, new Project[0], oldPackageVersion) { } public PackageItem(PackagesProviderBase provider, IPackage package, IEnumerable<Project> referenceProjectNames, SemanticVersion oldPackageVersion = null) { _provider = provider; _packageIdentity = package; _isUpdateItem = oldPackageVersion != null; _oldPackageVersion = oldPackageVersion; _isPrerelease = !package.IsReleaseVersion(); _referenceProjectNames = new ObservableCollection<Project>(referenceProjectNames); } public event PropertyChangedEventHandler PropertyChanged = delegate { }; public IPackage PackageIdentity { get { return _packageIdentity; } } public string Id { get { return _packageIdentity.Id; } } public string Name { get { return String.IsNullOrEmpty(_packageIdentity.Title) ? _packageIdentity.Id : _packageIdentity.Title; } } public string Version { get { return _packageIdentity.Version.ToString(); } } public string OldVersion { get { return _oldPackageVersion != null ? _oldPackageVersion.ToString() : null; } } public bool IsUpdateItem { get { return _isUpdateItem; } } public FrameworkName TargetFramework { get; set; } public string Description { get { if (_isUpdateItem && !String.IsNullOrEmpty(_packageIdentity.ReleaseNotes)) { return _packageIdentity.ReleaseNotes; } return _packageIdentity.Description; } } public string Summary { get { return String.IsNullOrEmpty(_packageIdentity.Summary) ? _packageIdentity.Description : _packageIdentity.Summary; } } public IEnumerable<PackageDependency> Dependencies { get { return _packageIdentity.GetCompatiblePackageDependencies(TargetFramework); } } /// <summary> /// This property is for XAML data binding. /// </summary> public IEnumerable<object> DisplayDependencies { get { if (_displayDependencies == null) { if (TargetFramework == null) { var dependencySets = _packageIdentity.DependencySets; if (dependencySets.Any(d => d.TargetFramework != null)) { // if there is at least one dependeny set with non-null target framework, // we show the dependencies grouped by target framework. _displayDependencies = _packageIdentity.DependencySets; } } if (_displayDependencies == null) { // otherwise, just show the dependencies as pre 2.0 _displayDependencies = Dependencies; } } return _displayDependencies; } } public ICollection<Project> ReferenceProjects { get { return _referenceProjectNames; } } public bool IsPrerelease { get { return _isPrerelease; } } public string CommandName { get; set; } [SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This property is data-bound in XAML.")] public IEnumerable<string> Authors { get { return _packageIdentity.Authors; } } [SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This property is data-bound in XAML.")] public bool RequireLicenseAcceptance { get { return _packageIdentity.RequireLicenseAcceptance; } } public Uri LicenseUrl { get { return _packageIdentity.LicenseUrl; } } public bool IsSelected { get { return _isSelected; } set { _isSelected = value; OnNotifyPropertyChanged("IsSelected"); } } public bool IsEnabled { get { return _provider.CanExecute(this); } } internal void UpdateEnabledStatus() { OnNotifyPropertyChanged("IsEnabled"); } private void OnNotifyPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } // Not used but required by the interface IVsExtension. public float Priority { get { return 0; } } // Not used but required by the interface IVsExtension. public BitmapSource MediumThumbnailImage { get { return null; } } // Not used but required by the interface IVsExtension. public BitmapSource SmallThumbnailImage { get { return null; } } // Not used but required by the interface IVsExtension. public BitmapSource PreviewImage { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// Represents a block that contains a sequence of expressions where variables can be defined. /// </summary> [DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))] public class BlockExpression : Expression { /// <summary> /// Gets the expressions in this block. /// </summary> public ReadOnlyCollection<Expression> Expressions { get { return GetOrMakeExpressions(); } } /// <summary> /// Gets the variables defined in this block. /// </summary> public ReadOnlyCollection<ParameterExpression> Variables { get { return GetOrMakeVariables(); } } /// <summary> /// Gets the last expression in this block. /// </summary> public Expression Result { get { Debug.Assert(ExpressionCount > 0); return GetExpression(ExpressionCount - 1); } } internal BlockExpression() { } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitBlock(this); } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Block; } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public override Type Type { get { return GetExpression(ExpressionCount - 1).Type; } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="variables">The <see cref="Variables" /> property of the result.</param> /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { if (variables == Variables && expressions == Expressions) { return this; } return Expression.Block(Type, variables, expressions); } [ExcludeFromCodeCoverage] // Unreachable internal virtual Expression GetExpression(int index) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual int ExpressionCount { get { throw ContractUtils.Unreachable; } } [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions() { throw ContractUtils.Unreachable; } internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return EmptyReadOnlyCollection<ParameterExpression>.Instance; } /// <summary> /// Makes a copy of this node replacing the parameters/args with the provided values. The /// shape of the parameters/args needs to match the shape of the current block - in other /// words there should be the same # of parameters and args. /// /// parameters can be null in which case the existing parameters are used. /// /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized /// subclass of BlockExpression which is being used. /// </summary> [ExcludeFromCodeCoverage] // Unreachable internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { throw ContractUtils.Unreachable; } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly which only takes a single argument. This version /// supports nodes which hold onto 5 Expressions and puts all of the arguments into the /// ReadOnlyCollection. /// /// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll /// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything /// which would force the readonly collection to be created. /// /// This is used by BlockExpression5 and MethodCallExpression5. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection) { Expression tObj = collection as Expression; if (tObj != null) { // otherwise make sure only one readonly collection ever gets exposed Interlocked.CompareExchange( ref collection, new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)), tObj ); } // and return what is not guaranteed to be a readonly collection return (ReadOnlyCollection<Expression>)collection; } } #region Specialized Subclasses internal sealed class Block2 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument. internal Block2(Expression arg0, Expression arg1) { _arg0 = arg0; _arg1 = arg1; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override int ExpressionCount { get { return 2; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 2); Debug.Assert(variables == null || variables.Count == 0); return new Block2(args[0], args[1]); } } internal sealed class Block3 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments. internal Block3(Expression arg0, Expression arg1, Expression arg2) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override int ExpressionCount { get { return 3; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 3); Debug.Assert(variables == null || variables.Count == 0); return new Block3(args[0], args[1], args[2]); } } internal sealed class Block4 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments. internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override int ExpressionCount { get { return 4; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 4); Debug.Assert(variables == null || variables.Count == 0); return new Block4(args[0], args[1], args[2], args[3]); } } internal sealed class Block5 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args. internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; case 4: return _arg4; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override int ExpressionCount { get { return 5; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 5); Debug.Assert(variables == null || variables.Count == 0); return new Block5(args[0], args[1], args[2], args[3], args[4]); } } internal class BlockN : BlockExpression { private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it. internal BlockN(IList<Expression> expressions) { Debug.Assert(expressions.Count != 0); _expressions = expressions; } internal override Expression GetExpression(int index) { Debug.Assert(index >= 0 && index < _expressions.Count); return _expressions[index]; } internal override int ExpressionCount { get { return _expressions.Count; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnly(ref _expressions); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(variables == null || variables.Count == 0); Debug.Assert(args != null); return new BlockN(args); } } internal class ScopeExpression : BlockExpression { private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection internal ScopeExpression(IList<ParameterExpression> variables) { _variables = variables; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return ReturnReadOnly(ref _variables); } protected IList<ParameterExpression> VariablesList { get { return _variables; } } // Used for rewrite of the nodes to either reuse existing set of variables if not rewritten. internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables) { if (variables != null && variables != VariablesList) { // Need to validate the new variables (uniqueness, not byref) ValidateVariables(variables, nameof(variables)); return variables; } else { return VariablesList; } } } internal sealed class Scope1 : ScopeExpression { private object _body; internal Scope1(IList<ParameterExpression> variables, Expression body) : this(variables, (object)body) { } private Scope1(IList<ParameterExpression> variables, object body) : base(variables) { _body = body; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_body); default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override int ExpressionCount { get { return 1; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new Scope1(variables, _body); } Debug.Assert(args.Length == 1); Debug.Assert(variables == null || variables.Count == Variables.Count); return new Scope1(ReuseOrValidateVariables(variables), args[0]); } } internal class ScopeN : ScopeExpression { private IList<Expression> _body; internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body) : base(variables) { _body = body; } protected IList<Expression> Body { get { return _body; } } internal override Expression GetExpression(int index) { return _body[index]; } internal override int ExpressionCount { get { return _body.Count; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnly(ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new ScopeN(variables, _body); } Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == Variables.Count); return new ScopeN(ReuseOrValidateVariables(variables), args); } } internal class ScopeWithType : ScopeN { private readonly Type _type; internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type) : base(variables, expressions) { _type = type; } public sealed override Type Type { get { return _type; } } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new ScopeWithType(variables, Body, _type); } Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == Variables.Count); return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type); } } #endregion #region Block List Classes /// <summary> /// Provides a wrapper around an IArgumentProvider which exposes the argument providers /// members out as an IList of Expression. This is used to avoid allocating an array /// which needs to be stored inside of a ReadOnlyCollection. Instead this type has /// the same amount of overhead as an array without duplicating the storage of the /// elements. This ensures that internally we can avoid creating and copying arrays /// while users of the Expression trees also don't pay a size penalty for this internal /// optimization. See IArgumentProvider for more general information on the Expression /// tree optimizations being used here. /// </summary> internal class BlockExpressionList : IList<Expression> { private readonly BlockExpression _block; private readonly Expression _arg0; internal BlockExpressionList(BlockExpression provider, Expression arg0) { _block = provider; _arg0 = arg0; } #region IList<Expression> Members public int IndexOf(Expression item) { if (_arg0 == item) { return 0; } for (int i = 1; i < _block.ExpressionCount; i++) { if (_block.GetExpression(i) == item) { return i; } } return -1; } [ExcludeFromCodeCoverage] // Unreachable public void Insert(int index, Expression item) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable public void RemoveAt(int index) { throw ContractUtils.Unreachable; } public Expression this[int index] { get { if (index == 0) { return _arg0; } return _block.GetExpression(index); } [ExcludeFromCodeCoverage] // Unreachable set { throw ContractUtils.Unreachable; } } #endregion #region ICollection<Expression> Members [ExcludeFromCodeCoverage] // Unreachable public void Add(Expression item) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable public void Clear() { throw ContractUtils.Unreachable; } public bool Contains(Expression item) { return IndexOf(item) != -1; } public void CopyTo(Expression[] array, int arrayIndex) { array[arrayIndex++] = _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { array[arrayIndex++] = _block.GetExpression(i); } } public int Count { get { return _block.ExpressionCount; } } [ExcludeFromCodeCoverage] // Unreachable public bool IsReadOnly { get { throw ContractUtils.Unreachable; } } [ExcludeFromCodeCoverage] // Unreachable public bool Remove(Expression item) { throw ContractUtils.Unreachable; } #endregion #region IEnumerable<Expression> Members public IEnumerator<Expression> GetEnumerator() { yield return _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { yield return _block.GetExpression(i); } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #endregion public partial class Expression { /// <summary> /// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1) { RequiresCanRead(arg0, nameof(arg0)); RequiresCanRead(arg1, nameof(arg1)); return new Block2(arg0, arg1); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2) { RequiresCanRead(arg0, nameof(arg0)); RequiresCanRead(arg1, nameof(arg1)); RequiresCanRead(arg2, nameof(arg2)); return new Block3(arg0, arg1, arg2); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { RequiresCanRead(arg0, nameof(arg0)); RequiresCanRead(arg1, nameof(arg1)); RequiresCanRead(arg2, nameof(arg2)); RequiresCanRead(arg3, nameof(arg3)); return new Block4(arg0, arg1, arg2, arg3); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <param name="arg4">The fifth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { RequiresCanRead(arg0, nameof(arg0)); RequiresCanRead(arg1, nameof(arg1)); RequiresCanRead(arg2, nameof(arg2)); RequiresCanRead(arg3, nameof(arg3)); RequiresCanRead(arg4, nameof(arg4)); return new Block5(arg0, arg1, arg2, arg3, arg4); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, nameof(expressions)); return GetOptimizedBlockExpression(expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<Expression> expressions) { return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, nameof(expressions)); return Block(type, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<Expression> expressions) { return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(type, variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(expressions, nameof(expressions)); var variableList = variables.ToReadOnly(); if (variableList.Count == 0) { return GetOptimizedBlockExpression(expressions as IReadOnlyList<Expression> ?? expressions.ToReadOnly()); } var expressionList = expressions.ToReadOnly(); return BlockCore(null, variableList, expressionList); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(expressions, nameof(expressions)); var expressionList = expressions.ToReadOnly(); var variableList = variables.ToReadOnly(); if (variableList.Count == 0 && expressionList.Count != 0) { var expressionCount = expressionList.Count; if (expressionCount != 0) { var lastExpression = expressionList[expressionCount - 1]; ContractUtils.RequiresNotNull(lastExpression, nameof(expressions)); if (lastExpression.Type == type) { return GetOptimizedBlockExpression(expressionList); } } } return BlockCore(type, variableList, expressionList); } private static BlockExpression BlockCore(Type type, ReadOnlyCollection<ParameterExpression> variables, ReadOnlyCollection<Expression> expressions) { RequiresCanRead(expressions, nameof(expressions)); ValidateVariables(variables, nameof(variables)); if (type != null) { if (expressions.Count == 0) { if (type != typeof(void)) { throw Error.ArgumentTypesMustMatch(); } return new ScopeWithType(variables, expressions, type); } Expression last = expressions.Last(); if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, last.Type)) { throw Error.ArgumentTypesMustMatch(); } } if (!TypeUtils.AreEquivalent(type, last.Type)) { return new ScopeWithType(variables, expressions, type); } } switch (expressions.Count) { case 0: return new ScopeWithType(variables, expressions, typeof(void)); case 1: return new Scope1(variables, expressions[0]); default: return new ScopeN(variables, expressions); } } // Checks that all variables are non-null, not byref, and unique. internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName) { int count = varList.Count; if (count != 0) { var set = new HashSet<ParameterExpression>(); for (int i = 0; i < count; i++) { ParameterExpression v = varList[i]; if (v == null) { throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count)); } if (v.IsByRef) { throw Error.VariableMustNotBeByRef(v, v.Type); } if (!set.Add(v)) { throw Error.DuplicateVariable(v); } } } } private static BlockExpression GetOptimizedBlockExpression(IReadOnlyList<Expression> expressions) { RequiresCanRead(expressions, nameof(expressions)); switch (expressions.Count) { case 0: return BlockCore(typeof(void), EmptyReadOnlyCollection<ParameterExpression>.Instance, EmptyReadOnlyCollection<Expression>.Instance); case 2: return new Block2(expressions[0], expressions[1]); case 3: return new Block3(expressions[0], expressions[1], expressions[2]); case 4: return new Block4(expressions[0], expressions[1], expressions[2], expressions[3]); case 5: return new Block5(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]); default: return new BlockN(expressions as ReadOnlyCollection<Expression> ?? (IList<Expression>)expressions.ToArray()); } } } }
using System; using System.Drawing; using System.Runtime.CompilerServices; using System.Windows.Forms; namespace ICSharpCode.TextEditor.Gui.CompletionWindow { public class CodeCompletionListView : UserControl { private ICompletionData[] completionData; private int firstItem; private int selectedItem = -1; private ImageList imageList; public event EventHandler SelectedItemChanged; public event EventHandler FirstItemChanged; public ImageList ImageList { get { return this.imageList; } set { this.imageList = value; } } public int FirstItem { get { return this.firstItem; } set { if (this.firstItem != value) { this.firstItem = value; this.OnFirstItemChanged(EventArgs.Empty); } } } public ICompletionData SelectedCompletionData { get { if (this.selectedItem < 0) { return null; } return this.completionData[this.selectedItem]; } } public int ItemHeight { get { return Math.Max(this.imageList.ImageSize.Height, (int)((double)this.Font.Height * 1.25)); } } public int MaxVisibleItem { get { return base.Height / this.ItemHeight; } } public CodeCompletionListView(ICompletionData[] completionData) { Array.Sort<ICompletionData>(completionData, new Comparison<ICompletionData>(DefaultCompletionData.Compare)); this.completionData = completionData; } public void Close() { if (this.completionData != null) { Array.Clear(this.completionData, 0, this.completionData.Length); } base.Dispose(); } public void SelectIndex(int index) { int num = this.selectedItem; int num2 = this.firstItem; index = Math.Max(0, index); this.selectedItem = Math.Max(0, Math.Min(this.completionData.Length - 1, index)); if (this.selectedItem < this.firstItem) { this.FirstItem = this.selectedItem; } if (this.firstItem + this.MaxVisibleItem <= this.selectedItem) { this.FirstItem = this.selectedItem - this.MaxVisibleItem + 1; } if (num != this.selectedItem) { if (this.firstItem != num2) { base.Invalidate(); } else { int num3 = Math.Min(this.selectedItem, num) - this.firstItem; int num4 = Math.Max(this.selectedItem, num) - this.firstItem; base.Invalidate(new Rectangle(0, 1 + num3 * this.ItemHeight, base.Width, (num4 - num3 + 1) * this.ItemHeight)); } this.OnSelectedItemChanged(EventArgs.Empty); } } public void CenterViewOn(int index) { int num = this.FirstItem; int num2 = index - this.MaxVisibleItem / 2; if (num2 < 0) { this.FirstItem = 0; } else { if (num2 >= this.completionData.Length - this.MaxVisibleItem) { this.FirstItem = this.completionData.Length - this.MaxVisibleItem; } else { this.FirstItem = num2; } } if (this.FirstItem != num) { base.Invalidate(); } } public void ClearSelection() { if (this.selectedItem < 0) { return; } int num = this.selectedItem - this.firstItem; this.selectedItem = -1; base.Invalidate(new Rectangle(0, num * this.ItemHeight, base.Width, (num + 1) * this.ItemHeight + 1)); base.Update(); this.OnSelectedItemChanged(EventArgs.Empty); } public void PageDown() { this.SelectIndex(this.selectedItem + this.MaxVisibleItem); } public void PageUp() { this.SelectIndex(this.selectedItem - this.MaxVisibleItem); } public void SelectNextItem() { this.SelectIndex(this.selectedItem + 1); } public void SelectPrevItem() { this.SelectIndex(this.selectedItem - 1); } public void SelectItemWithStart(string startText) { if (startText == null || startText.Length == 0) { return; } string text = startText; startText = startText.ToLower(); int num = -1; int num2 = -1; double num3 = 0.0; for (int i = 0; i < this.completionData.Length; i++) { string text2 = this.completionData[i].Text; string text3 = text2.ToLower(); if (text3.StartsWith(startText)) { double priority = this.completionData[i].Priority; int num4; if (text3 == startText) { if (text2 == text) { num4 = 3; } else { num4 = 2; } } else { if (text2.StartsWith(text)) { num4 = 1; } else { num4 = 0; } } bool flag; if (num2 < num4) { flag = true; } else { if (num == this.selectedItem) { flag = false; } else { if (i == this.selectedItem) { flag = (num2 == num4); } else { flag = (num2 == num4 && num3 < priority); } } } if (flag) { num = i; num3 = priority; num2 = num4; } } } if (num < 0) { this.ClearSelection(); return; } if (num < this.firstItem || this.firstItem + this.MaxVisibleItem <= num) { this.SelectIndex(num); this.CenterViewOn(num); return; } this.SelectIndex(num); } protected override void OnPaint(PaintEventArgs pe) { float num = 1f; float num2 = (float)this.ItemHeight; int num3 = (int)(num2 * (float)this.imageList.ImageSize.Width / (float)this.imageList.ImageSize.Height); int num4 = this.firstItem; Graphics graphics = pe.Graphics; while (num4 < this.completionData.Length && num < (float)base.Height) { RectangleF rect = new RectangleF(1f, num, (float)(base.Width - 2), num2); if (rect.IntersectsWith(pe.ClipRectangle)) { if (num4 == this.selectedItem) { graphics.FillRectangle(SystemBrushes.Highlight, rect); } else { graphics.FillRectangle(SystemBrushes.Window, rect); } int num5 = 0; if (this.imageList != null && this.completionData[num4].ImageIndex < this.imageList.Images.Count) { graphics.DrawImage(this.imageList.Images[this.completionData[num4].ImageIndex], new RectangleF(1f, num, (float)num3, num2)); num5 = num3; } if (num4 == this.selectedItem) { graphics.DrawString(this.completionData[num4].Text, this.Font, SystemBrushes.HighlightText, (float)num5, num); } else { graphics.DrawString(this.completionData[num4].Text, this.Font, SystemBrushes.WindowText, (float)num5, num); } } num += num2; num4++; } graphics.DrawRectangle(SystemPens.Control, new Rectangle(0, 0, base.Width - 1, base.Height - 1)); } protected override void OnMouseDown(MouseEventArgs e) { float num = 1f; int num2 = this.firstItem; float num3 = (float)this.ItemHeight; while (num2 < this.completionData.Length && num < (float)base.Height) { RectangleF rectangleF = new RectangleF(1f, num, (float)(base.Width - 2), num3); if (rectangleF.Contains((float)e.X, (float)e.Y)) { this.SelectIndex(num2); return; } num += num3; num2++; } } protected override void OnPaintBackground(PaintEventArgs pe) { } protected virtual void OnSelectedItemChanged(EventArgs e) { if (this.SelectedItemChanged != null) { this.SelectedItemChanged(this, e); } } protected virtual void OnFirstItemChanged(EventArgs e) { if (this.FirstItemChanged != null) { this.FirstItemChanged(this, e); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace LabSwparkWs1.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using GroupDocs.Viewer.Config; using GroupDocs.Viewer.Converter.Options; using GroupDocs.Viewer.Domain; using GroupDocs.Viewer.Domain.Html; using GroupDocs.Viewer.Domain.Options; using GroupDocs.Viewer.Handler; using MvcSample.Helpers; using MvcSample.Models; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mime; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using GroupDocs.Viewer.Domain.Containers; using GroupDocs.Viewer.Domain.Image; using WatermarkPosition = MvcSample.Models.WatermarkPosition; namespace MvcSample.Controllers { public class ViewerController : Controller { private readonly ViewerHtmlHandler _htmlHandler; private readonly ViewerImageHandler _imageHandler; // App_Data folder path private readonly string _storagePath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString(); private readonly string _tempPath = AppDomain.CurrentDomain.GetData("DataDirectory") + "\\temp"; private readonly ConvertImageFileType _convertImageFileType = ConvertImageFileType.JPG; private readonly bool _usePdfInImageEngine = true; private readonly Dictionary<string, Stream> _streams = new Dictionary<string, Stream>(); public ViewerController() { var htmlConfig = new ViewerConfig { StoragePath = _storagePath, TempPath = _tempPath, UseCache = true }; _htmlHandler = new ViewerHtmlHandler(htmlConfig); var imageConfig = new ViewerConfig { StoragePath = _storagePath, TempPath = _tempPath, UseCache = true, UsePdf = _usePdfInImageEngine }; _imageHandler = new ViewerImageHandler(imageConfig); // _streams.Add("ProcessFileFromStreamExample_1.pdf", HttpWebRequest.Create("http://unfccc.int/resource/docs/convkp/kpeng.pdf").GetResponse().GetResponseStream()); // _streams.Add("ProcessFileFromStreamExample_2.doc", HttpWebRequest.Create("http://www.acm.org/sigs/publications/pubform.doc").GetResponse().GetResponseStream()); } [HttpPost] public ActionResult ViewDocument(ViewDocumentParameters request) { if (Utils.IsValidUrl(request.Path)) request.Path = DownloadToStorage(request.Path); else if (_streams.ContainsKey(request.Path)) request.Path = SaveStreamToStorage(request.Path); var fileName = Path.GetFileName(request.Path); var result = new ViewDocumentResponse { pageCss = new string[] { }, lic = true, pdfDownloadUrl = GetPdfDownloadUrl(request), pdfPrintUrl = GetPdfPrintUrl(request), url = GetFileUrl(request), path = request.Path, name = fileName }; if (request.UseHtmlBasedEngine) ViewDocumentAsHtml(request, result, fileName); else ViewDocumentAsImage(request, result, fileName); return ToJsonResult(result); } public ActionResult LoadFileBrowserTreeData(LoadFileBrowserTreeDataParameters parameters) { var path = _storagePath; if (!string.IsNullOrEmpty(parameters.Path)) path = Path.Combine(path, parameters.Path); var request = new FileTreeOptions(path); var tree = _htmlHandler.LoadFileTree(request); var result = new FileBrowserTreeDataResponse { nodes = Utils.ToFileTreeNodes(parameters.Path, tree.FileTree).ToArray(), count = tree.FileTree.Count }; return ToJsonResult(result); } public ActionResult GetImageUrls(GetImageUrlsParameters parameters) { var docPath = parameters.Path; if (string.IsNullOrEmpty(parameters.Path)) { var empty = new GetImageUrlsResponse { imageUrls = new string[0] }; return ToJsonResult(empty); } DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(parameters.Path); int[] pageNumbers = new int[documentInfoContainer.Pages.Count]; for (int i = 0; i < documentInfoContainer.Pages.Count; i++) { pageNumbers[i] = documentInfoContainer.Pages[i].Number; } var applicationHost = GetApplicationHost(); string[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters); string[] attachmentUrls = new string[0]; foreach (AttachmentBase attachment in documentInfoContainer.Attachments) { List<PageImage> pages = _imageHandler.GetPages(attachment); var attachmentInfo = _imageHandler.GetDocumentInfo(_tempPath + "\\" + Path.GetFileNameWithoutExtension(docPath) + Path.GetExtension(docPath).Replace(".", "_") + "\\attachments\\" + attachment.Name); GetImageUrlsParameters attachmentResponse = parameters; attachmentResponse.Path = attachmentInfo.Guid; int[] attachmentPageNumbers = new int[pages.Count]; for (int i = 0; i < pages.Count; i++) { attachmentPageNumbers[i] = pages[i].PageNumber; } Array.Resize<string>(ref attachmentUrls, (attachmentUrls.Length + pages.Count)); string[] attachmentImagesUrls = new string[pages.Count]; attachmentImagesUrls = ImageUrlHelper.GetImageUrls(applicationHost, attachmentPageNumbers, attachmentResponse); attachmentImagesUrls.CopyTo(attachmentUrls, (attachmentUrls.Length - pages.Count)); } if (documentInfoContainer.Attachments.Count > 0) { var imagesUrls = new string[attachmentUrls.Length + imageUrls.Length]; imageUrls.CopyTo(imagesUrls, 0); attachmentUrls.CopyTo(imagesUrls, imageUrls.Length); var result = new GetImageUrlsResponse { imageUrls = imagesUrls }; return ToJsonResult(result); } else { var result = new GetImageUrlsResponse { imageUrls = imageUrls }; return ToJsonResult(result); } } public ActionResult GetFile(GetFileParameters parameters) { var displayName = string.IsNullOrEmpty(parameters.DisplayName) ? Path.GetFileName(parameters.Path) : Uri.EscapeDataString(parameters.DisplayName); Stream fileStream; if (parameters.GetPdf) { displayName = Path.ChangeExtension(displayName, "pdf"); var options = new PdfFileOptions { Guid = parameters.Path, Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth,parameters.WatermarkOpacity), }; if (parameters.IsPrintable) options.Transformations |= Transformation.AddPrintAction; if (parameters.SupportPageRotation) options.Transformations |= Transformation.Rotate; options.Transformations |= Transformation.Reorder; var pdfFileResponse = _htmlHandler.GetPdfFile(options); fileStream = pdfFileResponse.Stream; } else { var fileResponse = _htmlHandler.GetFile(parameters.Path); fileStream = fileResponse.Stream; } //jquery.fileDownload uses this cookie to determine that a file download has completed successfully Response.SetCookie(new HttpCookie("jqueryFileDownloadJSForGD", "true") { Path = "/" }); fileStream.Position = 0; using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); return File(ms.ToArray(), "application/octet-stream", displayName); } } public ActionResult GetPdfWithPrintDialog(GetFileParameters parameters) { var displayName = string.IsNullOrEmpty(parameters.DisplayName) ? Path.GetFileName(parameters.Path) : Uri.EscapeDataString(parameters.DisplayName); var options = new PdfFileOptions { Guid = parameters.Path, Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth,parameters.WatermarkOpacity) }; if (parameters.IsPrintable) options.Transformations |= Transformation.AddPrintAction; if (parameters.SupportPageRotation) options.Transformations |= Transformation.Rotate; options.Transformations |= Transformation.Reorder; var response = _htmlHandler.GetPdfFile(options); var contentDispositionString = new ContentDisposition { FileName = displayName, Inline = true }.ToString(); Response.AddHeader("Content-Disposition", contentDispositionString); return File(((MemoryStream)response.Stream).ToArray(), "application/pdf"); } public string GetFileUrl(string path, bool getPdf, bool isPrintable, string fileDisplayName = null, string watermarkText = null, int? watermarkColor = null, WatermarkPosition? watermarkPosition = WatermarkPosition.Diagonal, float? watermarkWidth = 0,byte? watermarkOpacity=255, bool ignoreDocumentAbsence = false, bool useHtmlBasedEngine = false, bool supportPageRotation = false) { var queryString = HttpUtility.ParseQueryString(string.Empty); queryString["path"] = path; if (!isPrintable) { queryString["getPdf"] = getPdf.ToString().ToLower(); if (fileDisplayName != null) queryString["displayName"] = fileDisplayName; } if (watermarkText != null) { queryString["watermarkText"] = watermarkText; queryString["watermarkColor"] = watermarkColor.ToString(); queryString["watermarkOpacity"] = watermarkOpacity.ToString(); if (watermarkPosition.HasValue) queryString["watermarkPosition"] = watermarkPosition.ToString(); if (watermarkWidth.HasValue) queryString["watermarkWidth"] = ((float)watermarkWidth).ToString(CultureInfo.InvariantCulture); } if (ignoreDocumentAbsence) { queryString["ignoreDocumentAbsence"] = ignoreDocumentAbsence.ToString().ToLower(); } queryString["useHtmlBasedEngine"] = useHtmlBasedEngine.ToString().ToLower(); queryString["supportPageRotation"] = supportPageRotation.ToString().ToLower(); var handlerName = isPrintable ? "GetPdfWithPrintDialog" : "GetFile"; var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/document-viewer/"; var fileUrl = string.Format("{0}{1}?{2}", baseUrl, handlerName, queryString); return fileUrl; } public ActionResult GetDocumentPageHtml(GetDocumentPageHtmlParameters parameters) { if (Utils.IsValidUrl(parameters.Path)) parameters.Path = Utils.GetFilenameFromUrl(parameters.Path); if (String.IsNullOrWhiteSpace(parameters.Path)) throw new ArgumentException("A document path must be specified", "path"); List<string> cssList; int pageNumber = parameters.PageIndex + 1; var htmlOptions = new HtmlOptions { PageNumber = parameters.PageIndex + 1, CountPagesToConvert = 1, IsResourcesEmbedded = false, HtmlResourcePrefix = string.Format( "/document-viewer/GetResourceForHtml?documentPath={0}", parameters.Path) + "&pageNumber={page-number}&resourceName=", }; var htmlPages = GetHtmlPages(parameters.Path, htmlOptions, out cssList); var pageHtml = htmlPages.Count > 0 ? htmlPages[0].HtmlContent : null; var pageCss = cssList.Count > 0 ? new[] { string.Join(" ", cssList) } : null; var result = new { pageHtml, pageCss }; return ToJsonResult(result); } public ActionResult GetDocumentPageImage(GetDocumentPageImageParameters parameters) { //parameters.IgnoreDocumentAbsence - not supported //parameters.InstanceIdToken - not supported string guid = parameters.Path; int pageIndex = parameters.PageIndex; int pageNumber = pageIndex + 1; /* //NOTE: This feature is supported starting from version 3.2.0 CultureInfo cultureInfo = string.IsNullOrEmpty(parameters.Locale) ? new CultureInfo("en-Us") : new CultureInfo(parameters.Locale); ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig, cultureInfo); */ var imageOptions = new ImageOptions { ConvertImageFileType = _convertImageFileType, Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth,parameters.WatermarkOpacity), Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None, CountPagesToConvert = 1, PageNumber = pageNumber, JpegQuality = parameters.Quality.GetValueOrDefault(), }; if (parameters.Rotate && parameters.Width.HasValue) { DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid); int side = parameters.Width.Value; int pageAngle = documentInfoContainer.Pages[pageIndex].Angle; if (pageAngle == 90 || pageAngle == 270) imageOptions.Height = side; else imageOptions.Width = side; } /* //NOTE: This feature is supported starting from version 3.2.0 if (parameters.Quality.HasValue) imageOptions.JpegQuality = parameters.Quality.Value; */ using (new InterProcessLock(guid)) { List<PageImage> pageImages = _imageHandler.GetPages(guid, imageOptions); PageImage pageImage = pageImages.Single(_ => _.PageNumber == pageNumber); return File(pageImage.Stream, GetContentType(_convertImageFileType)); } } public ActionResult GetResourceForHtml(GetResourceForHtmlParameters parameters) { if (!string.IsNullOrEmpty(parameters.ResourceName) && parameters.ResourceName.IndexOf("/", StringComparison.Ordinal) >= 0) parameters.ResourceName = parameters.ResourceName.Replace("/", ""); var resource = new HtmlResource { ResourceName = parameters.ResourceName, ResourceType = Utils.GetResourceType(parameters.ResourceName), DocumentPageNumber = parameters.PageNumber }; var stream = _htmlHandler.GetResource(parameters.DocumentPath, resource); if (stream == null || stream.Length == 0) return new HttpStatusCodeResult((int)HttpStatusCode.Gone); return File(stream, Utils.GetMimeType(parameters.ResourceName)); } public ActionResult RotatePage(RotatePageParameters parameters) { string guid = parameters.Path; int pageIndex = parameters.PageNumber; DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid); int pageNumber = documentInfoContainer.Pages[pageIndex].Number; RotatePageOptions rotatePageOptions = new RotatePageOptions(guid, pageNumber, parameters.RotationAmount); RotatePageContainer rotatePageContainer = _imageHandler.RotatePage(rotatePageOptions); RotatePageResponse response = new RotatePageResponse { resultAngle = rotatePageContainer.CurrentRotationAngle }; return ToJsonResult(response); } public ActionResult ReorderPage(ReorderPageParameters parameters) { string guid = parameters.Path; DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid); int pageNumber = documentInfoContainer.Pages[parameters.OldPosition].Number; int newPosition = parameters.NewPosition + 1; ReorderPageOptions reorderPageOptions = new ReorderPageOptions(guid, pageNumber, newPosition); _imageHandler.ReorderPage(reorderPageOptions); return ToJsonResult(new ReorderPageResponse()); } private List<PageHtml> GetHtmlPages(string filePath, HtmlOptions htmlOptions, out List<string> cssList) { var htmlPages = _htmlHandler.GetPages(filePath, htmlOptions); cssList = new List<string>(); foreach (var page in htmlPages) { var test = page.HtmlResources; var indexOfBodyOpenTag = page.HtmlContent.IndexOf("<body>", StringComparison.InvariantCultureIgnoreCase); if (indexOfBodyOpenTag > 0) page.HtmlContent = page.HtmlContent.Substring(indexOfBodyOpenTag + "<body>".Length); var indexOfBodyCloseTag = page.HtmlContent.IndexOf("</body>", StringComparison.InvariantCultureIgnoreCase); if (indexOfBodyCloseTag > 0) page.HtmlContent = page.HtmlContent.Substring(0, indexOfBodyCloseTag); foreach (var resource in page.HtmlResources.Where(_ => _.ResourceType == HtmlResourceType.Style)) { var cssStream = _htmlHandler.GetResource(filePath, resource); var text = new StreamReader(cssStream).ReadToEnd(); var needResave = false; if (text.IndexOf("url(\"", StringComparison.Ordinal) >= 0 && text.IndexOf("url(\"/document-viewer/GetResourceForHtml?documentPath=", StringComparison.Ordinal) < 0) { needResave = true; text = text.Replace("url(\"", string.Format("url(\"/document-viewer/GetResourceForHtml?documentPath={0}&pageNumber={1}&resourceName=", filePath, page.PageNumber)); } if (text.IndexOf("url('", StringComparison.Ordinal) >= 0 && text.IndexOf("url('/document-viewer/GetResourceForHtml?documentPath=", StringComparison.Ordinal) < 0) { needResave = true; text = text.Replace("url('", string.Format( "url('/document-viewer/GetResourceForHtml?documentPath={0}&pageNumber={1}&resourceName=", filePath, page.PageNumber)); } cssList.Add(text); if (needResave) { var fullPath = Path.Combine(_tempPath, filePath, "html", "resources", string.Format("page{0}", page.PageNumber), resource.ResourceName); System.IO.File.WriteAllText(fullPath, text); } } List<string> cssClasses = Utils.GetCssClasses(page.HtmlContent); foreach (var cssClass in cssClasses) { var newCssClass = string.Format("page-{0}-{1}", page.PageNumber, cssClass); page.HtmlContent = page.HtmlContent.Replace(cssClass, newCssClass); for (int i = 0; i < cssList.Count; i++) cssList[i] = cssList[i].Replace(cssClass, newCssClass); } } return htmlPages; } private ActionResult ToJsonResult(object result) { var serializer = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var serializedData = serializer.Serialize(result); return Content(serializedData, "application/json"); } private string DownloadToStorage(string url) { var fileNameFromUrl = Utils.GetFilenameFromUrl(url); var filePath = Path.Combine(_storagePath, fileNameFromUrl); using (new InterProcessLock(filePath)) Utils.DownloadFile(url, filePath); return fileNameFromUrl; } private string SaveStreamToStorage(string key) { var stream = _streams[key]; var savePath = Path.Combine(_storagePath, key); using (new InterProcessLock(savePath)) { using (var fileStream = System.IO.File.Create(savePath)) { if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } return savePath; } } private void ViewDocumentAsImage(ViewDocumentParameters request, ViewDocumentResponse result, string fileName) { var docInfo = _imageHandler.GetDocumentInfo(request.Path); var maxWidth = 0; var maxHeight = 0; foreach (var pageData in docInfo.Pages) { if (pageData.Height > maxHeight) { maxHeight = pageData.Height; maxWidth = pageData.Width; } } var fileData = new FileData { DateCreated = DateTime.Now, DateModified = docInfo.LastModificationDate, PageCount = docInfo.Pages.Count, Pages = docInfo.Pages, MaxWidth = maxWidth, MaxHeight = maxHeight }; DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(request.Path); int[] pageNumbers = new int[documentInfoContainer.Pages.Count]; for (int i = 0; i < documentInfoContainer.Pages.Count; i++) { pageNumbers[i] = documentInfoContainer.Pages[i].Number; } string applicationHost = GetApplicationHost(); var documentUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, request); string[] attachmentUrls = new string[0]; foreach (AttachmentBase attachment in docInfo.Attachments) { List<PageImage> pages = _imageHandler.GetPages(attachment); var attachmentInfo = _imageHandler.GetDocumentInfo(_tempPath + "\\" + Path.GetFileNameWithoutExtension(docInfo.Guid) + Path.GetExtension(docInfo.Guid).Replace(".", "_") + "\\attachments\\" + attachment.Name); fileData.PageCount += pages.Count; fileData.Pages.AddRange(attachmentInfo.Pages); ViewDocumentParameters attachmentResponse = request; attachmentResponse.Path = attachmentInfo.Guid; int[] attachmentPageNumbers = new int[pages.Count]; for (int i = 0; i < pages.Count; i++) { attachmentPageNumbers[i] = pages[i].PageNumber; } Array.Resize<string>(ref attachmentUrls, (attachmentUrls.Length + pages.Count)); string[] attachmentImagesUrls = new string[pages.Count]; attachmentImagesUrls = ImageUrlHelper.GetImageUrls(applicationHost, attachmentPageNumbers, attachmentResponse); attachmentImagesUrls.CopyTo(attachmentUrls, (attachmentUrls.Length - pages.Count)); } SerializationOptions serializationOptions = new SerializationOptions { UsePdf = request.UsePdf, SupportListOfBookmarks = request.SupportListOfBookmarks, SupportListOfContentControls = request.SupportListOfContentControls }; var documentInfoJson = new DocumentInfoJsonSerializer(docInfo, serializationOptions).Serialize(); result.documentDescription = documentInfoJson; result.docType = docInfo.DocumentType; result.fileType = docInfo.FileType; if (docInfo.Attachments.Count > 0) { var imagesUrls = new string[attachmentUrls.Length + documentUrls.Length]; documentUrls.CopyTo(imagesUrls, 0); attachmentUrls.CopyTo(imagesUrls, documentUrls.Length); result.imageUrls = imagesUrls; } else { result.imageUrls = documentUrls; } } private void ViewDocumentAsHtml(ViewDocumentParameters request, ViewDocumentResponse result, string fileName) { var docInfo = _htmlHandler.GetDocumentInfo(request.Path); var maxWidth = 0; var maxHeight = 0; foreach (var pageData in docInfo.Pages) { if (pageData.Height > maxHeight) { maxHeight = pageData.Height; maxWidth = pageData.Width; } } var fileData = new FileData { DateCreated = DateTime.Now, DateModified = docInfo.LastModificationDate, PageCount = docInfo.Pages.Count, Pages = docInfo.Pages, MaxWidth = maxWidth, MaxHeight = maxHeight }; var htmlOptions = new HtmlOptions() { IsResourcesEmbedded = false, HtmlResourcePrefix = string.Format( "/document-viewer/GetResourceForHtml?documentPath={0}", fileName) + "&pageNumber={page-number}&resourceName=", }; if (request.PreloadPagesCount.HasValue && request.PreloadPagesCount.Value > 0) { htmlOptions.PageNumber = 1; htmlOptions.CountPagesToConvert = request.PreloadPagesCount.Value; } ///// List<string> cssList; var htmlPages = GetHtmlPages(fileName, htmlOptions, out cssList); foreach (AttachmentBase attachment in docInfo.Attachments) { var attachmentPath = _tempPath + "\\" + Path.GetFileNameWithoutExtension(docInfo.Guid) + Path.GetExtension(docInfo.Guid).Replace(".", "_") + "\\attachments\\" + attachment.Name; var attachmentHtmlOptions = new HtmlOptions() { IsResourcesEmbedded = Utils.IsImage(fileName), HtmlResourcePrefix = string.Format("/document-viewer/GetResourceForHtml?documentPath={0}", HttpUtility.UrlEncode(attachmentPath)) + "&pageNumber={page-number}&resourceName=", }; List<PageHtml> pages = _htmlHandler.GetPages(attachment, attachmentHtmlOptions); var attachmentInfo = _htmlHandler.GetDocumentInfo(attachmentPath); fileData.PageCount += attachmentInfo.Pages.Count; fileData.Pages.AddRange(attachmentInfo.Pages); List<string> attachmentCSSList; var attachmentPages = GetHtmlPages(attachmentInfo.Guid, attachmentHtmlOptions, out attachmentCSSList); cssList.AddRange(attachmentCSSList); htmlPages.AddRange(attachmentPages); } ///// result.documentDescription = new FileDataJsonSerializer(fileData, new FileDataOptions()).Serialize(false); result.docType = docInfo.DocumentType; result.fileType = docInfo.FileType; result.pageHtml = htmlPages.Select(_ => _.HtmlContent).ToArray(); result.pageCss = new[] { string.Join(" ", cssList) }; } private string GetFileUrl(ViewDocumentParameters request) { return GetFileUrl(request.Path, false, false, request.FileDisplayName); } private string GetPdfPrintUrl(ViewDocumentParameters request) { return GetFileUrl(request.Path, true, true, request.FileDisplayName, request.WatermarkText, request.WatermarkColor, request.WatermarkPosition, request.WatermarkWidth,request.WatermarkOpacity, request.IgnoreDocumentAbsence, request.UseHtmlBasedEngine, request.SupportPageRotation); } private string GetPdfDownloadUrl(ViewDocumentParameters request) { return GetFileUrl(request.Path, true, false, request.FileDisplayName, request.WatermarkText, request.WatermarkColor, request.WatermarkPosition, request.WatermarkWidth,request.WatermarkOpacity, request.IgnoreDocumentAbsence, request.UseHtmlBasedEngine, request.SupportPageRotation); } private string GetApplicationHost() { return Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/'); } private string GetContentType(ConvertImageFileType convertImageFileType) { string contentType; switch (convertImageFileType) { case ConvertImageFileType.JPG: contentType = "image/jpeg"; break; case ConvertImageFileType.BMP: contentType = "image/bmp"; break; case ConvertImageFileType.PNG: contentType = "image/png"; ; break; default: throw new ArgumentOutOfRangeException(); } return contentType; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Infrastructure; using Microsoft.Extensions.Logging; namespace Microsoft.AspNet.SignalR.Messaging { internal class ScaleoutStream { private TaskCompletionSource<object> _taskCompletionSource; private static Task _initializeDrainTask; private TaskQueue _queue; private StreamState _state; private Exception _error; private readonly int _size; private readonly QueuingBehavior _queueBehavior; private readonly ILogger _logger; private readonly string _loggerPrefix; private readonly IPerformanceCounterManager _perfCounters; private readonly object _lockObj = new object(); public ScaleoutStream(ILogger logger, string loggerPrefix, QueuingBehavior queueBehavior, int size, IPerformanceCounterManager performanceCounters) { if (logger == null) { throw new ArgumentNullException("logger"); } _logger = logger; _loggerPrefix = loggerPrefix; _size = size; _perfCounters = performanceCounters; _queueBehavior = queueBehavior; InitializeCore(); } private bool UsingTaskQueue { get { // Either you're always queuing or you're only queuing initially and you're in the initial state return _queueBehavior == QueuingBehavior.Always || (_queueBehavior == QueuingBehavior.InitialOnly && _state == StreamState.Initial); } } public void Open() { lock (_lockObj) { bool usingTaskQueue = UsingTaskQueue; StreamState previousState; if (ChangeState(StreamState.Open, out previousState)) { _perfCounters.ScaleoutStreamCountOpen.Increment(); _perfCounters.ScaleoutStreamCountBuffering.Decrement(); _error = null; if (usingTaskQueue) { EnsureQueueStarted(); if (previousState == StreamState.Initial && _queueBehavior == QueuingBehavior.InitialOnly) { _initializeDrainTask = Drain(_queue, _logger); } } } } } public Task Send(Func<object, Task> send, object state) { lock (_lockObj) { if (_error != null) { throw _error; } // If the queue is closed then stop sending if (_state == StreamState.Closed) { throw new InvalidOperationException(Resources.Error_StreamClosed); } var context = new SendContext(this, send, state); if (_initializeDrainTask != null && !_initializeDrainTask.IsCompleted) { // Wait on the draining of the queue before proceeding with the send // NOTE: Calling .Wait() here is safe because the task wasn't created on an ASP.NET request thread // and thus has no captured sync context _initializeDrainTask.Wait(); } if (UsingTaskQueue) { Task task = _queue.Enqueue(Send, context); if (task == null) { // The task is null if the queue is full throw new InvalidOperationException(Resources.Error_TaskQueueFull); } // Always observe the task in case the user doesn't handle it return task.Catch(_logger); } return Send(context); } } public void SetError(Exception error) { Log(LogLevel.Error, "Error has happened with the following exception: {0}.", error); lock (_lockObj) { _perfCounters.ScaleoutErrorsTotal.Increment(); _perfCounters.ScaleoutErrorsPerSec.Increment(); Buffer(); _error = error; } } public void Close() { Task task = TaskAsyncHelper.Empty; lock (_lockObj) { if (ChangeState(StreamState.Closed)) { _perfCounters.ScaleoutStreamCountOpen.RawValue = 0; _perfCounters.ScaleoutStreamCountBuffering.RawValue = 0; if (UsingTaskQueue) { // Ensure the queue is started EnsureQueueStarted(); // Drain the queue to stop all sends task = Drain(_queue, _logger); } } } if (UsingTaskQueue) { // Block until the queue is drained so no new work can be done task.Wait(); } } private static Task Send(object state) { var context = (SendContext)state; context.InvokeSend().Then(tcs => { // Complete the task if the send is successful tcs.TrySetResult(null); }, context.TaskCompletionSource) .Catch((ex, obj) => { var ctx = (SendContext)obj; ctx.Stream.Log(LogLevel.Error, "Send failed: {0}", ex); lock (ctx.Stream._lockObj) { // Set the queue into buffering state ctx.Stream.SetError(ex.InnerException); // Otherwise just set this task as failed ctx.TaskCompletionSource.TrySetUnwrappedException(ex); } }, context, context.Stream._logger); return context.TaskCompletionSource.Task; } private void Buffer() { lock (_lockObj) { if (ChangeState(StreamState.Buffering)) { _perfCounters.ScaleoutStreamCountOpen.Decrement(); _perfCounters.ScaleoutStreamCountBuffering.Increment(); InitializeCore(); } } } private void InitializeCore() { if (UsingTaskQueue) { Task task = DrainPreviousQueue(); _queue = new TaskQueue(task, _size); _queue.QueueSizeCounter = _perfCounters.ScaleoutSendQueueLength; } } private Task DrainPreviousQueue() { // If the tcs is null or complete then create a new one if (_taskCompletionSource == null || _taskCompletionSource.Task.IsCompleted) { _taskCompletionSource = new TaskCompletionSource<object>(); } if (_queue != null) { // Drain the queue when the new queue is open return _taskCompletionSource.Task.Then((q, t) => Drain(q, t), _queue, _logger); } // Nothing to drain return _taskCompletionSource.Task; } private void EnsureQueueStarted() { if (_taskCompletionSource != null) { _taskCompletionSource.TrySetResult(null); } } private bool ChangeState(StreamState newState) { StreamState oldState; return ChangeState(newState, out oldState); } private bool ChangeState(StreamState newState, out StreamState previousState) { previousState = _state; // Do nothing if the state is closed if (_state == StreamState.Closed) { return false; } if (_state != newState) { Log(LogLevel.Information, "Changed state from {0} to {1}", _state, newState); _state = newState; return true; } return false; } private static Task Drain(TaskQueue queue, ILogger logger) { if (queue == null) { return TaskAsyncHelper.Empty; } var tcs = new TaskCompletionSource<object>(); queue.Drain().Catch(logger).ContinueWith(task => { tcs.SetResult(null); }); return tcs.Task; } private void Log(LogLevel logLevel, string value, params object[] args) { switch (logLevel) { case LogLevel.Critical: _logger.LogCritical(String.Format(value, args)); break; case LogLevel.Error: _logger.LogError(String.Format(value, args)); break; case LogLevel.Information: _logger.LogInformation(String.Format(value, args)); break; case LogLevel.Verbose: _logger.LogVerbose(String.Format(value, args)); break; case LogLevel.Warning: _logger.LogWarning(String.Format(value, args)); break; default: break; } } private class SendContext { private readonly Func<object, Task> _send; private readonly object _state; public readonly ScaleoutStream Stream; public readonly TaskCompletionSource<object> TaskCompletionSource; public SendContext(ScaleoutStream stream, Func<object, Task> send, object state) { Stream = stream; TaskCompletionSource = new TaskCompletionSource<object>(); _send = send; _state = state; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception flows to the caller")] public Task InvokeSend() { try { return _send(_state); } catch (Exception ex) { return TaskAsyncHelper.FromError(ex); } } } private enum StreamState { Initial, Open, Buffering, Closed } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.IO; using System.Text; using System.Collections.Generic; using Thrift.Transport; using System.Globalization; namespace Thrift.Protocol { /// <summary> /// JSON protocol implementation for thrift. /// /// This is a full-featured protocol supporting Write and Read. /// /// Please see the C++ class header for a detailed description of the /// protocol's wire format. /// /// Adapted from the Java version. /// </summary> public class TJSONProtocol : TProtocol { /// <summary> /// Factory for JSON protocol objects /// </summary> public class Factory : TProtocolFactory { public TProtocol GetProtocol(TTransport trans) { return new TJSONProtocol(trans); } } private static byte[] COMMA = new byte[] { (byte)',' }; private static byte[] COLON = new byte[] { (byte)':' }; private static byte[] LBRACE = new byte[] { (byte)'{' }; private static byte[] RBRACE = new byte[] { (byte)'}' }; private static byte[] LBRACKET = new byte[] { (byte)'[' }; private static byte[] RBRACKET = new byte[] { (byte)']' }; private static byte[] QUOTE = new byte[] { (byte)'"' }; private static byte[] BACKSLASH = new byte[] { (byte)'\\' }; private static byte[] ZERO = new byte[] { (byte)'0' }; private byte[] ESCSEQ = new byte[] { (byte)'\\', (byte)'u', (byte)'0', (byte)'0' }; private const long VERSION = 1; private byte[] JSON_CHAR_TABLE = { 0, 0, 0, 0, 0, 0, 0, 0,(byte)'b',(byte)'t',(byte)'n', 0,(byte)'f',(byte)'r', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,(byte)'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; private char[] ESCAPE_CHARS = "\"\\bfnrt".ToCharArray(); private byte[] ESCAPE_CHAR_VALS = { (byte)'"', (byte)'\\', (byte)'\b', (byte)'\f', (byte)'\n', (byte)'\r', (byte)'\t', }; private const int DEF_STRING_SIZE = 16; private static byte[] NAME_BOOL = new byte[] { (byte)'t', (byte)'f' }; private static byte[] NAME_BYTE = new byte[] { (byte)'i', (byte)'8' }; private static byte[] NAME_I16 = new byte[] { (byte)'i', (byte)'1', (byte)'6' }; private static byte[] NAME_I32 = new byte[] { (byte)'i', (byte)'3', (byte)'2' }; private static byte[] NAME_I64 = new byte[] { (byte)'i', (byte)'6', (byte)'4' }; private static byte[] NAME_DOUBLE = new byte[] { (byte)'d', (byte)'b', (byte)'l' }; private static byte[] NAME_STRUCT = new byte[] { (byte)'r', (byte)'e', (byte)'c' }; private static byte[] NAME_STRING = new byte[] { (byte)'s', (byte)'t', (byte)'r' }; private static byte[] NAME_MAP = new byte[] { (byte)'m', (byte)'a', (byte)'p' }; private static byte[] NAME_LIST = new byte[] { (byte)'l', (byte)'s', (byte)'t' }; private static byte[] NAME_SET = new byte[] { (byte)'s', (byte)'e', (byte)'t' }; private static byte[] GetTypeNameForTypeID(TType typeID) { switch (typeID) { case TType.Bool: return NAME_BOOL; case TType.Byte: return NAME_BYTE; case TType.I16: return NAME_I16; case TType.I32: return NAME_I32; case TType.I64: return NAME_I64; case TType.Double: return NAME_DOUBLE; case TType.String: return NAME_STRING; case TType.Struct: return NAME_STRUCT; case TType.Map: return NAME_MAP; case TType.Set: return NAME_SET; case TType.List: return NAME_LIST; default: throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); } } private static TType GetTypeIDForTypeName(byte[] name) { TType result = TType.Stop; if (name.Length > 1) { switch (name[0]) { case (byte)'d': result = TType.Double; break; case (byte)'i': switch (name[1]) { case (byte)'8': result = TType.Byte; break; case (byte)'1': result = TType.I16; break; case (byte)'3': result = TType.I32; break; case (byte)'6': result = TType.I64; break; } break; case (byte)'l': result = TType.List; break; case (byte)'m': result = TType.Map; break; case (byte)'r': result = TType.Struct; break; case (byte)'s': if (name[1] == (byte)'t') { result = TType.String; } else if (name[1] == (byte)'e') { result = TType.Set; } break; case (byte)'t': result = TType.Bool; break; } } if (result == TType.Stop) { throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); } return result; } ///<summary> /// Base class for tracking JSON contexts that may require /// inserting/Reading additional JSON syntax characters /// This base context does nothing. ///</summary> protected class JSONBaseContext { protected TJSONProtocol proto; public JSONBaseContext(TJSONProtocol proto) { this.proto = proto; } public virtual void Write() { } public virtual void Read() { } public virtual bool EscapeNumbers() { return false; } } ///<summary> /// Context for JSON lists. Will insert/Read commas before each item except /// for the first one ///</summary> protected class JSONListContext : JSONBaseContext { public JSONListContext(TJSONProtocol protocol) : base(protocol) { } private bool first = true; public override void Write() { if (first) { first = false; } else { proto.trans.Write(COMMA); } } public override void Read() { if (first) { first = false; } else { proto.ReadJSONSyntaxChar(COMMA); } } } ///<summary> /// Context for JSON records. Will insert/Read colons before the value portion /// of each record pair, and commas before each key except the first. In /// addition, will indicate that numbers in the key position need to be /// escaped in quotes (since JSON keys must be strings). ///</summary> protected class JSONPairContext : JSONBaseContext { public JSONPairContext(TJSONProtocol proto) : base(proto) { } private bool first = true; private bool colon = true; public override void Write() { if (first) { first = false; colon = true; } else { proto.trans.Write(colon ? COLON : COMMA); colon = !colon; } } public override void Read() { if (first) { first = false; colon = true; } else { proto.ReadJSONSyntaxChar(colon ? COLON : COMMA); colon = !colon; } } public override bool EscapeNumbers() { return colon; } } ///<summary> /// Holds up to one byte from the transport ///</summary> protected class LookaheadReader { protected TJSONProtocol proto; public LookaheadReader(TJSONProtocol proto) { this.proto = proto; } private bool hasData; private byte[] data = new byte[1]; ///<summary> /// Return and consume the next byte to be Read, either taking it from the /// data buffer if present or getting it from the transport otherwise. ///</summary> public byte Read() { if (hasData) { hasData = false; } else { proto.trans.ReadAll(data, 0, 1); } return data[0]; } ///<summary> /// Return the next byte to be Read without consuming, filling the data /// buffer if it has not been filled alReady. ///</summary> public byte Peek() { if (!hasData) { proto.trans.ReadAll(data, 0, 1); } hasData = true; return data[0]; } } // Default encoding protected Encoding utf8Encoding = UTF8Encoding.UTF8; // Stack of nested contexts that we may be in protected Stack<JSONBaseContext> contextStack = new Stack<JSONBaseContext>(); // Current context that we are in protected JSONBaseContext context; // Reader that manages a 1-byte buffer protected LookaheadReader reader; ///<summary> /// Push a new JSON context onto the stack. ///</summary> protected void PushContext(JSONBaseContext c) { contextStack.Push(context); context = c; } ///<summary> /// Pop the last JSON context off the stack ///</summary> protected void PopContext() { context = contextStack.Pop(); } ///<summary> /// TJSONProtocol Constructor ///</summary> public TJSONProtocol(TTransport trans) : base(trans) { context = new JSONBaseContext(this); reader = new LookaheadReader(this); } // Temporary buffer used by several methods private byte[] tempBuffer = new byte[4]; ///<summary> /// Read a byte that must match b[0]; otherwise an exception is thrown. /// Marked protected to avoid synthetic accessor in JSONListContext.Read /// and JSONPairContext.Read ///</summary> protected void ReadJSONSyntaxChar(byte[] b) { byte ch = reader.Read(); if (ch != b[0]) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Unexpected character:" + (char)ch); } } ///<summary> /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its /// corresponding hex value ///</summary> private static byte HexVal(byte ch) { if ((ch >= '0') && (ch <= '9')) { return (byte)((char)ch - '0'); } else if ((ch >= 'a') && (ch <= 'f')) { return (byte)((char)ch - 'a'); } else { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character"); } } ///<summary> /// Convert a byte containing a hex value to its corresponding hex character ///</summary> private static byte HexChar(byte val) { val &= 0x0F; if (val < 10) { return (byte)((char)val + '0'); } else { return (byte)((char)val + 'a'); } } ///<summary> /// Write the bytes in array buf as a JSON characters, escaping as needed ///</summary> private void WriteJSONString(byte[] b) { context.Write(); trans.Write(QUOTE); int len = b.Length; for (int i = 0; i < len; i++) { if ((b[i] & 0x00FF) >= 0x30) { if (b[i] == BACKSLASH[0]) { trans.Write(BACKSLASH); trans.Write(BACKSLASH); } else { trans.Write(b, i, 1); } } else { tempBuffer[0] = JSON_CHAR_TABLE[b[i]]; if (tempBuffer[0] == 1) { trans.Write(b, i, 1); } else if (tempBuffer[0] > 1) { trans.Write(BACKSLASH); trans.Write(tempBuffer, 0, 1); } else { trans.Write(ESCSEQ); tempBuffer[0] = HexChar((byte)(b[i] >> 4)); tempBuffer[1] = HexChar(b[i]); trans.Write(tempBuffer, 0, 2); } } } trans.Write(QUOTE); } ///<summary> /// Write out number as a JSON value. If the context dictates so, it will be /// wrapped in quotes to output as a JSON string. ///</summary> private void WriteJSONInteger(long num) { context.Write(); String str = num.ToString(); bool escapeNum = context.EscapeNumbers(); if (escapeNum) trans.Write(QUOTE); trans.Write(utf8Encoding.GetBytes(str)); if (escapeNum) trans.Write(QUOTE); } ///<summary> /// Write out a double as a JSON value. If it is NaN or infinity or if the /// context dictates escaping, Write out as JSON string. ///</summary> private void WriteJSONDouble(double num) { context.Write(); String str = num.ToString(CultureInfo.InvariantCulture); bool special = false; switch (str[0]) { case 'N': // NaN case 'I': // Infinity special = true; break; case '-': if (str[1] == 'I') { // -Infinity special = true; } break; } bool escapeNum = special || context.EscapeNumbers(); if (escapeNum) trans.Write(QUOTE); trans.Write(utf8Encoding.GetBytes(str)); if (escapeNum) trans.Write(QUOTE); } ///<summary> /// Write out contents of byte array b as a JSON string with base-64 encoded /// data ///</summary> private void WriteJSONBase64(byte[] b) { context.Write(); trans.Write(QUOTE); int len = b.Length; int off = 0; while (len >= 3) { // Encode 3 bytes at a time TBase64Utils.encode(b, off, 3, tempBuffer, 0); trans.Write(tempBuffer, 0, 4); off += 3; len -= 3; } if (len > 0) { // Encode remainder TBase64Utils.encode(b, off, len, tempBuffer, 0); trans.Write(tempBuffer, 0, len + 1); } trans.Write(QUOTE); } private void WriteJSONObjectStart() { context.Write(); trans.Write(LBRACE); PushContext(new JSONPairContext(this)); } private void WriteJSONObjectEnd() { PopContext(); trans.Write(RBRACE); } private void WriteJSONArrayStart() { context.Write(); trans.Write(LBRACKET); PushContext(new JSONListContext(this)); } private void WriteJSONArrayEnd() { PopContext(); trans.Write(RBRACKET); } public override void WriteMessageBegin(TMessage message) { WriteJSONArrayStart(); WriteJSONInteger(VERSION); byte[] b = utf8Encoding.GetBytes(message.Name); WriteJSONString(b); WriteJSONInteger((long)message.Type); WriteJSONInteger(message.SeqID); } public override void WriteMessageEnd() { WriteJSONArrayEnd(); } public override void WriteStructBegin(TStruct str) { WriteJSONObjectStart(); } public override void WriteStructEnd() { WriteJSONObjectEnd(); } public override void WriteFieldBegin(TField field) { WriteJSONInteger(field.ID); WriteJSONObjectStart(); WriteJSONString(GetTypeNameForTypeID(field.Type)); } public override void WriteFieldEnd() { WriteJSONObjectEnd(); } public override void WriteFieldStop() { } public override void WriteMapBegin(TMap map) { WriteJSONArrayStart(); WriteJSONString(GetTypeNameForTypeID(map.KeyType)); WriteJSONString(GetTypeNameForTypeID(map.ValueType)); WriteJSONInteger(map.Count); WriteJSONObjectStart(); } public override void WriteMapEnd() { WriteJSONObjectEnd(); WriteJSONArrayEnd(); } public override void WriteListBegin(TList list) { WriteJSONArrayStart(); WriteJSONString(GetTypeNameForTypeID(list.ElementType)); WriteJSONInteger(list.Count); } public override void WriteListEnd() { WriteJSONArrayEnd(); } public override void WriteSetBegin(TSet set) { WriteJSONArrayStart(); WriteJSONString(GetTypeNameForTypeID(set.ElementType)); WriteJSONInteger(set.Count); } public override void WriteSetEnd() { WriteJSONArrayEnd(); } public override void WriteBool(bool b) { WriteJSONInteger(b ? (long)1 : (long)0); } public override void WriteByte(sbyte b) { WriteJSONInteger((long)b); } public override void WriteI16(short i16) { WriteJSONInteger((long)i16); } public override void WriteI32(int i32) { WriteJSONInteger((long)i32); } public override void WriteI64(long i64) { WriteJSONInteger(i64); } public override void WriteDouble(double dub) { WriteJSONDouble(dub); } public override void WriteString(String str) { byte[] b = utf8Encoding.GetBytes(str); WriteJSONString(b); } public override void WriteBinary(byte[] bin) { WriteJSONBase64(bin); } /** * Reading methods. */ ///<summary> /// Read in a JSON string, unescaping as appropriate.. Skip Reading from the /// context if skipContext is true. ///</summary> private byte[] ReadJSONString(bool skipContext) { MemoryStream buffer = new MemoryStream(); if (!skipContext) { context.Read(); } ReadJSONSyntaxChar(QUOTE); while (true) { byte ch = reader.Read(); if (ch == QUOTE[0]) { break; } if (ch == ESCSEQ[0]) { ch = reader.Read(); if (ch == ESCSEQ[1]) { ReadJSONSyntaxChar(ZERO); ReadJSONSyntaxChar(ZERO); trans.ReadAll(tempBuffer, 0, 2); ch = (byte)((HexVal((byte)tempBuffer[0]) << 4) + HexVal(tempBuffer[1])); } else { int off = Array.IndexOf(ESCAPE_CHARS, (char)ch); if (off == -1) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char"); } ch = ESCAPE_CHAR_VALS[off]; } } buffer.Write(new byte[] { (byte)ch }, 0, 1); } return buffer.ToArray(); } ///<summary> /// Return true if the given byte could be a valid part of a JSON number. ///</summary> private bool IsJSONNumeric(byte b) { switch (b) { case (byte)'+': case (byte)'-': case (byte)'.': case (byte)'0': case (byte)'1': case (byte)'2': case (byte)'3': case (byte)'4': case (byte)'5': case (byte)'6': case (byte)'7': case (byte)'8': case (byte)'9': case (byte)'E': case (byte)'e': return true; } return false; } ///<summary> /// Read in a sequence of characters that are all valid in JSON numbers. Does /// not do a complete regex check to validate that this is actually a number. ////</summary> private String ReadJSONNumericChars() { StringBuilder strbld = new StringBuilder(); while (true) { byte ch = reader.Peek(); if (!IsJSONNumeric(ch)) { break; } strbld.Append((char)reader.Read()); } return strbld.ToString(); } ///<summary> /// Read in a JSON number. If the context dictates, Read in enclosing quotes. ///</summary> private long ReadJSONInteger() { context.Read(); if (context.EscapeNumbers()) { ReadJSONSyntaxChar(QUOTE); } String str = ReadJSONNumericChars(); if (context.EscapeNumbers()) { ReadJSONSyntaxChar(QUOTE); } try { return Int64.Parse(str); } catch (FormatException) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } ///<summary> /// Read in a JSON double value. Throw if the value is not wrapped in quotes /// when expected or if wrapped in quotes when not expected. ///</summary> private double ReadJSONDouble() { context.Read(); if (reader.Peek() == QUOTE[0]) { byte[] arr = ReadJSONString(true); double dub = Double.Parse(utf8Encoding.GetString(arr,0,arr.Length), CultureInfo.InvariantCulture); if (!context.EscapeNumbers() && !Double.IsNaN(dub) && !Double.IsInfinity(dub)) { // Throw exception -- we should not be in a string in this case throw new TProtocolException(TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted"); } return dub; } else { if (context.EscapeNumbers()) { // This will throw - we should have had a quote if escapeNum == true ReadJSONSyntaxChar(QUOTE); } try { return Double.Parse(ReadJSONNumericChars()); } catch (FormatException) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } } //<summary> /// Read in a JSON string containing base-64 encoded data and decode it. ///</summary> private byte[] ReadJSONBase64() { byte[] b = ReadJSONString(false); int len = b.Length; int off = 0; int size = 0; while (len >= 4) { // Decode 4 bytes at a time TBase64Utils.decode(b, off, 4, b, size); // NB: decoded in place off += 4; len -= 4; size += 3; } // Don't decode if we hit the end or got a single leftover byte (invalid // base64 but legal for skip of regular string type) if (len > 1) { // Decode remainder TBase64Utils.decode(b, off, len, b, size); // NB: decoded in place size += len - 1; } // Sadly we must copy the byte[] (any way around this?) byte[] result = new byte[size]; Array.Copy(b, 0, result, 0, size); return result; } private void ReadJSONObjectStart() { context.Read(); ReadJSONSyntaxChar(LBRACE); PushContext(new JSONPairContext(this)); } private void ReadJSONObjectEnd() { ReadJSONSyntaxChar(RBRACE); PopContext(); } private void ReadJSONArrayStart() { context.Read(); ReadJSONSyntaxChar(LBRACKET); PushContext(new JSONListContext(this)); } private void ReadJSONArrayEnd() { ReadJSONSyntaxChar(RBRACKET); PopContext(); } public override TMessage ReadMessageBegin() { TMessage message = new TMessage(); ReadJSONArrayStart(); if (ReadJSONInteger() != VERSION) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Message contained bad version."); } var buf = ReadJSONString(false); message.Name = utf8Encoding.GetString(buf,0,buf.Length); message.Type = (TMessageType)ReadJSONInteger(); message.SeqID = (int)ReadJSONInteger(); return message; } public override void ReadMessageEnd() { ReadJSONArrayEnd(); } public override TStruct ReadStructBegin() { ReadJSONObjectStart(); return new TStruct(); } public override void ReadStructEnd() { ReadJSONObjectEnd(); } public override TField ReadFieldBegin() { TField field = new TField(); byte ch = reader.Peek(); if (ch == RBRACE[0]) { field.Type = TType.Stop; } else { field.ID = (short)ReadJSONInteger(); ReadJSONObjectStart(); field.Type = GetTypeIDForTypeName(ReadJSONString(false)); } return field; } public override void ReadFieldEnd() { ReadJSONObjectEnd(); } public override TMap ReadMapBegin() { TMap map = new TMap(); ReadJSONArrayStart(); map.KeyType = GetTypeIDForTypeName(ReadJSONString(false)); map.ValueType = GetTypeIDForTypeName(ReadJSONString(false)); map.Count = (int)ReadJSONInteger(); ReadJSONObjectStart(); return map; } public override void ReadMapEnd() { ReadJSONObjectEnd(); ReadJSONArrayEnd(); } public override TList ReadListBegin() { TList list = new TList(); ReadJSONArrayStart(); list.ElementType = GetTypeIDForTypeName(ReadJSONString(false)); list.Count = (int)ReadJSONInteger(); return list; } public override void ReadListEnd() { ReadJSONArrayEnd(); } public override TSet ReadSetBegin() { TSet set = new TSet(); ReadJSONArrayStart(); set.ElementType = GetTypeIDForTypeName(ReadJSONString(false)); set.Count = (int)ReadJSONInteger(); return set; } public override void ReadSetEnd() { ReadJSONArrayEnd(); } public override bool ReadBool() { return (ReadJSONInteger() == 0 ? false : true); } public override sbyte ReadByte() { return (sbyte)ReadJSONInteger(); } public override short ReadI16() { return (short)ReadJSONInteger(); } public override int ReadI32() { return (int)ReadJSONInteger(); } public override long ReadI64() { return (long)ReadJSONInteger(); } public override double ReadDouble() { return ReadJSONDouble(); } public override String ReadString() { var buf = ReadJSONString(false); return utf8Encoding.GetString(buf,0,buf.Length); } public override byte[] ReadBinary() { return ReadJSONBase64(); } } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using Microsoft.Win32; using NHibernate; using NHibernate.Engine; using NHibernate.Tool.hbm2ddl; using Rhino.Commons.Helpers; using Environment=NHibernate.Cfg.Environment; namespace Rhino.Commons.ForTesting { /// <summary> /// A strategy class that parameterizes a <see /// cref="UnitOfWorkTestContext"/> with database specific implementations /// </summary> /// <remarks> /// This class is a companion to <see cref="UnitOfWorkTestContext"/>. Its /// purpose is to encapsulate behind a common interface the database /// specific implementations of behaviour required to construct and manage /// the test context /// </remarks> public abstract class UnitOfWorkTestContextDbStrategy { public static string SQLiteDbName = ":memory:"; /// <summary> /// Creates the physical database named <paramref name="databaseName"/>. /// </summary> /// <remarks> /// Use this method to create the physical database file. /// <para> /// For MsSqlCe this will create a database file in the file system /// named <paramref name="databaseName"/>.sdf /// </para> /// <para> /// For MsSql2005 this will create a database named <paramref /// name="databaseName"/> in the (local) instance of Sql Server 2005 on /// this machine /// </para> /// </remarks> public static void CreatePhysicalDatabaseMediaFor(DatabaseEngine databaseEngine, string databaseName) { For(databaseEngine, databaseName, null).CreateDatabaseMedia(); } public static UnitOfWorkTestContextDbStrategy For(DatabaseEngine databaseEngine, string databaseName) { return For(databaseEngine, databaseName, null); } public static UnitOfWorkTestContextDbStrategy For(DatabaseEngine databaseEngine, string databaseName, IDictionary<string, string> properties) { UnitOfWorkTestContextDbStrategy strategy; switch (databaseEngine) { case DatabaseEngine.SQLite: strategy = new SQlLiteUnitOfWorkTestContextDbStrategy(); break; case DatabaseEngine.MsSqlCe: strategy = new MsSqlCeUnitOfWorkTestContextDbStrategy(databaseName); break; case DatabaseEngine.MsSql2005: strategy = new MsSql2005UnitOfWorkTestContextDbStrategy(databaseName); break; case DatabaseEngine.MsSql2005Express: strategy = new MsSql2005ExpressUnitOfWorkTestContextDbStrategy(databaseName); break; default: throw new ArgumentOutOfRangeException("databaseEngine"); } if (properties != null) foreach (KeyValuePair<string,string> property in properties) strategy.NHibernateProperties[property.Key] = property.Value; return strategy; } public static bool IsSqlServer2005OrAboveInstalled() { string sqlServerCurrentVsRegKey = @"SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion"; RegistryKey regKey = Registry.LocalMachine.OpenSubKey(sqlServerCurrentVsRegKey); if (regKey == null) return false; string currentVersion = (string)regKey.GetValue("CurrentVersion"); string[] versionNumbers = currentVersion.Split('.'); return Int32.Parse(versionNumbers[0]) >= 9; } private UnitOfWorkTestContext testContext; private readonly string databaseName; public UnitOfWorkTestContextDbStrategy(string databaseName) { this.databaseName = databaseName; } public abstract DatabaseEngine DatabaseEngine { get; } public string DatabaseName { get { return databaseName; } } private IDictionary<string,string> properties = new Dictionary<string,string>(); public IDictionary<string,string> NHibernateProperties { get { return properties; } } public UnitOfWorkTestContext TestContext { get { return testContext; } set { testContext = value; } } public virtual ISession CreateSession() { ISession session = TestContext.SessionFactory.OpenSession(); return session; } public virtual void SetupDatabase(ISession currentSession) { CreateDatabaseMedia(); CreateDatabaseSchema(currentSession); } protected abstract void CreateDatabaseMedia(); protected virtual void CreateDatabaseSchema(ISession currentSession) { new SchemaExport(TestContext.Configuration).Execute(false, true, false); } private class MsSqlCeUnitOfWorkTestContextDbStrategy : UnitOfWorkTestContextDbStrategy { public MsSqlCeUnitOfWorkTestContextDbStrategy(string databaseName) : base(databaseName) { properties.Add(Environment.ConnectionDriver, "NHibernate.Driver.SqlServerCeDriver"); properties.Add(Environment.Dialect, "NHibernate.Dialect.MsSqlCeDialect"); properties.Add(Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider"); string connectionString = string.Format("Data Source={0};", DatabaseName); properties.Add(Environment.ConnectionString, connectionString); properties.Add(Environment.ShowSql, "true"); properties.Add(Environment.ReleaseConnections, "on_close"); } public override DatabaseEngine DatabaseEngine { get { return DatabaseEngine.MsSqlCe; } } protected override void CreateDatabaseMedia() { string filename; if (!databaseName.EndsWith(".sdf")) filename = string.Format("{0}.sdf", databaseName); else filename = databaseName; SqlCEDbHelper.CreateDatabaseFile(filename); } } private class MsSql2005UnitOfWorkTestContextDbStrategy : UnitOfWorkTestContextDbStrategy { public MsSql2005UnitOfWorkTestContextDbStrategy(string databaseName) : base(databaseName) { properties.Add(Environment.ConnectionDriver, "NHibernate.Driver.SqlClientDriver"); properties.Add(Environment.Dialect, "NHibernate.Dialect.MsSql2005Dialect"); properties.Add(Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider"); properties.Add(Environment.ConnectionString, ConnectionStringFor(DatabaseName)); properties.Add(Environment.ShowSql, "true"); properties.Add(Environment.ReleaseConnections, "on_close"); //by specifying a default schema, nhibernate's dynamic sql queries benefit from caching properties.Add(Environment.DefaultSchema, string.Format("{0}.dbo", DatabaseName)); } public override DatabaseEngine DatabaseEngine { get { return DatabaseEngine.MsSql2005; } } protected override void CreateDatabaseMedia() { string sqlServerDataDirectory = GetSqlServerDataDirectory(); string createDatabaseScript = "IF (SELECT DB_ID('" + DatabaseName + "')) IS NULL " + " CREATE DATABASE " + DatabaseName + " ON PRIMARY " + " (NAME = " + DatabaseName + "_Data, " + @" FILENAME = '" + sqlServerDataDirectory + DatabaseName + ".mdf', " + " SIZE = 5MB," + " FILEGROWTH =" + 10 + ") " + " LOG ON (NAME =" + DatabaseName + "_Log, " + @" FILENAME = '" + sqlServerDataDirectory + DatabaseName + ".ldf', " + " SIZE = 1MB, " + " FILEGROWTH =" + 5 + ")"; ExecuteDbScript(createDatabaseScript, ConnectionStringFor("master")); } protected virtual string ConnectionStringFor(string databaseName) { return string.Format("Server=(local);initial catalog={0};Integrated Security=SSPI", databaseName); } private void ExecuteDbScript(string sqlScript, string connectionString) { using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(sqlScript, conn)) { conn.Open(); command.ExecuteNonQuery(); } } } protected virtual string GetSqlServerDataDirectory() { string sqlServerRegKey = @"SOFTWARE\Microsoft\Microsoft SQL Server\"; string sqlServerInstanceName = Registry64.LocalMachine.GetValue(sqlServerRegKey + @"Instance Names\SQL", "MSSQLSERVER"); string sqlServerInstanceSetupRegKey = sqlServerRegKey + sqlServerInstanceName + @"\Setup"; return Registry64.LocalMachine.GetValue(sqlServerInstanceSetupRegKey, "SQLDataRoot") + @"\Data\"; } } private class MsSql2005ExpressUnitOfWorkTestContextDbStrategy : MsSql2005UnitOfWorkTestContextDbStrategy { public MsSql2005ExpressUnitOfWorkTestContextDbStrategy(string databaseName) : base(databaseName) { } public override DatabaseEngine DatabaseEngine { get { return DatabaseEngine.MsSql2005Express; } } protected override string ConnectionStringFor(string databaseName) { return string.Format(@"Server=(local)\SqlExpress;initial catalog={0};Integrated Security=SSPI", databaseName); } protected override string GetSqlServerDataDirectory() { string sqlServerRegKey = @"SOFTWARE\Microsoft\Microsoft SQL Server\"; string sqlServerInstanceName = (string)Registry.LocalMachine .OpenSubKey(sqlServerRegKey + @"Instance Names\SQL") .GetValue("SQLEXPRESS"); string sqlServerInstanceSetupRegKey = sqlServerRegKey + sqlServerInstanceName + @"\Setup"; return (string)Registry.LocalMachine .OpenSubKey(sqlServerInstanceSetupRegKey) .GetValue("SQLDataRoot") + @"\Data\"; } } private class SQlLiteUnitOfWorkTestContextDbStrategy : UnitOfWorkTestContextDbStrategy { public SQlLiteUnitOfWorkTestContextDbStrategy() : base(SQLiteDbName) { properties.Add(Environment.ConnectionDriver, "NHibernate.Driver.SQLite20Driver"); properties.Add(Environment.Dialect, "NHibernate.Dialect.SQLiteDialect"); properties.Add(Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider"); string connectionString = string.Format("Data Source={0};Version=3;New=True;", DatabaseName); properties.Add(Environment.ConnectionString, connectionString); properties.Add(Environment.ShowSql, "true"); properties.Add(Environment.ReleaseConnections, "on_close"); } public override DatabaseEngine DatabaseEngine { get { return DatabaseEngine.SQLite; } } protected override void CreateDatabaseMedia() { // nothing to do } protected override void CreateDatabaseSchema(ISession currentSession) { new SchemaExport(TestContext.Configuration).Execute(false, true, false, currentSession.Connection, null); } public override ISession CreateSession() { //need to get our own connection, because NH will try to close it //as soon as possible, and we will lose the changes. IDbConnection dbConnection = ((ISessionFactoryImplementor)TestContext.SessionFactory).ConnectionProvider.GetConnection(); ISession openSession = TestContext.SessionFactory.OpenSession(dbConnection); return openSession; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCampaignServiceClientTest { [Category("Autogenerated")][Test] public void GetCampaignRequestObject() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); GetCampaignRequest request = new GetCampaignRequest { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::Campaign expectedResponse = new gagvr::Campaign { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::CampaignStatusEnum.Types.CampaignStatus.Removed, AdServingOptimizationStatus = gagve::AdServingOptimizationStatusEnum.Types.AdServingOptimizationStatus.ConversionOptimize, AdvertisingChannelType = gagve::AdvertisingChannelTypeEnum.Types.AdvertisingChannelType.MultiChannel, AdvertisingChannelSubType = gagve::AdvertisingChannelSubTypeEnum.Types.AdvertisingChannelSubType.AppCampaign, UrlCustomParameters = { new gagvc::CustomParameter(), }, NetworkSettings = new gagvr::Campaign.Types.NetworkSettings(), ExperimentType = gagve::CampaignExperimentTypeEnum.Types.CampaignExperimentType.Unknown, ServingStatus = gagve::CampaignServingStatusEnum.Types.CampaignServingStatus.Ended, BiddingStrategyType = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.PercentCpc, ManualCpc = new gagvc::ManualCpc(), ManualCpm = new gagvc::ManualCpm(), TargetCpa = new gagvc::TargetCpa(), TargetSpend = new gagvc::TargetSpend(), TargetRoas = new gagvc::TargetRoas(), MaximizeConversions = new gagvc::MaximizeConversions(), MaximizeConversionValue = new gagvc::MaximizeConversionValue(), HotelSetting = new gagvr::Campaign.Types.HotelSettingInfo(), DynamicSearchAdsSetting = new gagvr::Campaign.Types.DynamicSearchAdsSetting(), PercentCpc = new gagvc::PercentCpc(), ShoppingSetting = new gagvr::Campaign.Types.ShoppingSetting(), ManualCpv = new gagvc::ManualCpv(), RealTimeBiddingSetting = new gagvc::RealTimeBiddingSetting(), FrequencyCaps = { new gagvc::FrequencyCapEntry(), }, TargetCpm = new gagvc::TargetCpm(), VideoBrandSafetySuitability = gagve::BrandSafetySuitabilityEnum.Types.BrandSafetySuitability.Unknown, TargetingSetting = new gagvc::TargetingSetting(), VanityPharma = new gagvr::Campaign.Types.VanityPharma(), SelectiveOptimization = new gagvr::Campaign.Types.SelectiveOptimization(), TrackingSetting = new gagvr::Campaign.Types.TrackingSetting(), GeoTargetTypeSetting = new gagvr::Campaign.Types.GeoTargetTypeSetting(), TargetImpressionShare = new gagvc::TargetImpressionShare(), Commission = new gagvc::Commission(), LocalCampaignSetting = new gagvr::Campaign.Types.LocalCampaignSetting(), AppCampaignSetting = new gagvr::Campaign.Types.AppCampaignSetting(), PaymentMode = gagve::PaymentModeEnum.Types.PaymentMode.Clicks, OptimizationGoalSetting = new gagvr::Campaign.Types.OptimizationGoalSetting(), BaseCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Id = -6774108720365892680L, TrackingUrlTemplate = "tracking_url_template157f152a", LabelsAsCampaignLabelNames = { gagvr::CampaignLabelName.FromCustomerCampaignLabel("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[LABEL_ID]"), }, CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", FinalUrlSuffix = "final_url_suffix046ed37a", OptimizationScore = -4.7741588361660064E+17, BiddingStrategyAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), ExcludedParentAssetFieldTypes = { gagve::AssetFieldTypeEnum.Types.AssetFieldType.Unknown, }, AccessibleBiddingStrategyAsAccessibleBiddingStrategyName = gagvr::AccessibleBiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaign(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); gagvr::Campaign response = client.GetCampaign(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignRequestObjectAsync() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); GetCampaignRequest request = new GetCampaignRequest { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::Campaign expectedResponse = new gagvr::Campaign { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::CampaignStatusEnum.Types.CampaignStatus.Removed, AdServingOptimizationStatus = gagve::AdServingOptimizationStatusEnum.Types.AdServingOptimizationStatus.ConversionOptimize, AdvertisingChannelType = gagve::AdvertisingChannelTypeEnum.Types.AdvertisingChannelType.MultiChannel, AdvertisingChannelSubType = gagve::AdvertisingChannelSubTypeEnum.Types.AdvertisingChannelSubType.AppCampaign, UrlCustomParameters = { new gagvc::CustomParameter(), }, NetworkSettings = new gagvr::Campaign.Types.NetworkSettings(), ExperimentType = gagve::CampaignExperimentTypeEnum.Types.CampaignExperimentType.Unknown, ServingStatus = gagve::CampaignServingStatusEnum.Types.CampaignServingStatus.Ended, BiddingStrategyType = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.PercentCpc, ManualCpc = new gagvc::ManualCpc(), ManualCpm = new gagvc::ManualCpm(), TargetCpa = new gagvc::TargetCpa(), TargetSpend = new gagvc::TargetSpend(), TargetRoas = new gagvc::TargetRoas(), MaximizeConversions = new gagvc::MaximizeConversions(), MaximizeConversionValue = new gagvc::MaximizeConversionValue(), HotelSetting = new gagvr::Campaign.Types.HotelSettingInfo(), DynamicSearchAdsSetting = new gagvr::Campaign.Types.DynamicSearchAdsSetting(), PercentCpc = new gagvc::PercentCpc(), ShoppingSetting = new gagvr::Campaign.Types.ShoppingSetting(), ManualCpv = new gagvc::ManualCpv(), RealTimeBiddingSetting = new gagvc::RealTimeBiddingSetting(), FrequencyCaps = { new gagvc::FrequencyCapEntry(), }, TargetCpm = new gagvc::TargetCpm(), VideoBrandSafetySuitability = gagve::BrandSafetySuitabilityEnum.Types.BrandSafetySuitability.Unknown, TargetingSetting = new gagvc::TargetingSetting(), VanityPharma = new gagvr::Campaign.Types.VanityPharma(), SelectiveOptimization = new gagvr::Campaign.Types.SelectiveOptimization(), TrackingSetting = new gagvr::Campaign.Types.TrackingSetting(), GeoTargetTypeSetting = new gagvr::Campaign.Types.GeoTargetTypeSetting(), TargetImpressionShare = new gagvc::TargetImpressionShare(), Commission = new gagvc::Commission(), LocalCampaignSetting = new gagvr::Campaign.Types.LocalCampaignSetting(), AppCampaignSetting = new gagvr::Campaign.Types.AppCampaignSetting(), PaymentMode = gagve::PaymentModeEnum.Types.PaymentMode.Clicks, OptimizationGoalSetting = new gagvr::Campaign.Types.OptimizationGoalSetting(), BaseCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Id = -6774108720365892680L, TrackingUrlTemplate = "tracking_url_template157f152a", LabelsAsCampaignLabelNames = { gagvr::CampaignLabelName.FromCustomerCampaignLabel("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[LABEL_ID]"), }, CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", FinalUrlSuffix = "final_url_suffix046ed37a", OptimizationScore = -4.7741588361660064E+17, BiddingStrategyAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), ExcludedParentAssetFieldTypes = { gagve::AssetFieldTypeEnum.Types.AssetFieldType.Unknown, }, AccessibleBiddingStrategyAsAccessibleBiddingStrategyName = gagvr::AccessibleBiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Campaign>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); gagvr::Campaign responseCallSettings = await client.GetCampaignAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Campaign responseCancellationToken = await client.GetCampaignAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaign() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); GetCampaignRequest request = new GetCampaignRequest { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::Campaign expectedResponse = new gagvr::Campaign { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::CampaignStatusEnum.Types.CampaignStatus.Removed, AdServingOptimizationStatus = gagve::AdServingOptimizationStatusEnum.Types.AdServingOptimizationStatus.ConversionOptimize, AdvertisingChannelType = gagve::AdvertisingChannelTypeEnum.Types.AdvertisingChannelType.MultiChannel, AdvertisingChannelSubType = gagve::AdvertisingChannelSubTypeEnum.Types.AdvertisingChannelSubType.AppCampaign, UrlCustomParameters = { new gagvc::CustomParameter(), }, NetworkSettings = new gagvr::Campaign.Types.NetworkSettings(), ExperimentType = gagve::CampaignExperimentTypeEnum.Types.CampaignExperimentType.Unknown, ServingStatus = gagve::CampaignServingStatusEnum.Types.CampaignServingStatus.Ended, BiddingStrategyType = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.PercentCpc, ManualCpc = new gagvc::ManualCpc(), ManualCpm = new gagvc::ManualCpm(), TargetCpa = new gagvc::TargetCpa(), TargetSpend = new gagvc::TargetSpend(), TargetRoas = new gagvc::TargetRoas(), MaximizeConversions = new gagvc::MaximizeConversions(), MaximizeConversionValue = new gagvc::MaximizeConversionValue(), HotelSetting = new gagvr::Campaign.Types.HotelSettingInfo(), DynamicSearchAdsSetting = new gagvr::Campaign.Types.DynamicSearchAdsSetting(), PercentCpc = new gagvc::PercentCpc(), ShoppingSetting = new gagvr::Campaign.Types.ShoppingSetting(), ManualCpv = new gagvc::ManualCpv(), RealTimeBiddingSetting = new gagvc::RealTimeBiddingSetting(), FrequencyCaps = { new gagvc::FrequencyCapEntry(), }, TargetCpm = new gagvc::TargetCpm(), VideoBrandSafetySuitability = gagve::BrandSafetySuitabilityEnum.Types.BrandSafetySuitability.Unknown, TargetingSetting = new gagvc::TargetingSetting(), VanityPharma = new gagvr::Campaign.Types.VanityPharma(), SelectiveOptimization = new gagvr::Campaign.Types.SelectiveOptimization(), TrackingSetting = new gagvr::Campaign.Types.TrackingSetting(), GeoTargetTypeSetting = new gagvr::Campaign.Types.GeoTargetTypeSetting(), TargetImpressionShare = new gagvc::TargetImpressionShare(), Commission = new gagvc::Commission(), LocalCampaignSetting = new gagvr::Campaign.Types.LocalCampaignSetting(), AppCampaignSetting = new gagvr::Campaign.Types.AppCampaignSetting(), PaymentMode = gagve::PaymentModeEnum.Types.PaymentMode.Clicks, OptimizationGoalSetting = new gagvr::Campaign.Types.OptimizationGoalSetting(), BaseCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Id = -6774108720365892680L, TrackingUrlTemplate = "tracking_url_template157f152a", LabelsAsCampaignLabelNames = { gagvr::CampaignLabelName.FromCustomerCampaignLabel("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[LABEL_ID]"), }, CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", FinalUrlSuffix = "final_url_suffix046ed37a", OptimizationScore = -4.7741588361660064E+17, BiddingStrategyAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), ExcludedParentAssetFieldTypes = { gagve::AssetFieldTypeEnum.Types.AssetFieldType.Unknown, }, AccessibleBiddingStrategyAsAccessibleBiddingStrategyName = gagvr::AccessibleBiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaign(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); gagvr::Campaign response = client.GetCampaign(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignAsync() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); GetCampaignRequest request = new GetCampaignRequest { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::Campaign expectedResponse = new gagvr::Campaign { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::CampaignStatusEnum.Types.CampaignStatus.Removed, AdServingOptimizationStatus = gagve::AdServingOptimizationStatusEnum.Types.AdServingOptimizationStatus.ConversionOptimize, AdvertisingChannelType = gagve::AdvertisingChannelTypeEnum.Types.AdvertisingChannelType.MultiChannel, AdvertisingChannelSubType = gagve::AdvertisingChannelSubTypeEnum.Types.AdvertisingChannelSubType.AppCampaign, UrlCustomParameters = { new gagvc::CustomParameter(), }, NetworkSettings = new gagvr::Campaign.Types.NetworkSettings(), ExperimentType = gagve::CampaignExperimentTypeEnum.Types.CampaignExperimentType.Unknown, ServingStatus = gagve::CampaignServingStatusEnum.Types.CampaignServingStatus.Ended, BiddingStrategyType = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.PercentCpc, ManualCpc = new gagvc::ManualCpc(), ManualCpm = new gagvc::ManualCpm(), TargetCpa = new gagvc::TargetCpa(), TargetSpend = new gagvc::TargetSpend(), TargetRoas = new gagvc::TargetRoas(), MaximizeConversions = new gagvc::MaximizeConversions(), MaximizeConversionValue = new gagvc::MaximizeConversionValue(), HotelSetting = new gagvr::Campaign.Types.HotelSettingInfo(), DynamicSearchAdsSetting = new gagvr::Campaign.Types.DynamicSearchAdsSetting(), PercentCpc = new gagvc::PercentCpc(), ShoppingSetting = new gagvr::Campaign.Types.ShoppingSetting(), ManualCpv = new gagvc::ManualCpv(), RealTimeBiddingSetting = new gagvc::RealTimeBiddingSetting(), FrequencyCaps = { new gagvc::FrequencyCapEntry(), }, TargetCpm = new gagvc::TargetCpm(), VideoBrandSafetySuitability = gagve::BrandSafetySuitabilityEnum.Types.BrandSafetySuitability.Unknown, TargetingSetting = new gagvc::TargetingSetting(), VanityPharma = new gagvr::Campaign.Types.VanityPharma(), SelectiveOptimization = new gagvr::Campaign.Types.SelectiveOptimization(), TrackingSetting = new gagvr::Campaign.Types.TrackingSetting(), GeoTargetTypeSetting = new gagvr::Campaign.Types.GeoTargetTypeSetting(), TargetImpressionShare = new gagvc::TargetImpressionShare(), Commission = new gagvc::Commission(), LocalCampaignSetting = new gagvr::Campaign.Types.LocalCampaignSetting(), AppCampaignSetting = new gagvr::Campaign.Types.AppCampaignSetting(), PaymentMode = gagve::PaymentModeEnum.Types.PaymentMode.Clicks, OptimizationGoalSetting = new gagvr::Campaign.Types.OptimizationGoalSetting(), BaseCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Id = -6774108720365892680L, TrackingUrlTemplate = "tracking_url_template157f152a", LabelsAsCampaignLabelNames = { gagvr::CampaignLabelName.FromCustomerCampaignLabel("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[LABEL_ID]"), }, CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", FinalUrlSuffix = "final_url_suffix046ed37a", OptimizationScore = -4.7741588361660064E+17, BiddingStrategyAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), ExcludedParentAssetFieldTypes = { gagve::AssetFieldTypeEnum.Types.AssetFieldType.Unknown, }, AccessibleBiddingStrategyAsAccessibleBiddingStrategyName = gagvr::AccessibleBiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Campaign>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); gagvr::Campaign responseCallSettings = await client.GetCampaignAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Campaign responseCancellationToken = await client.GetCampaignAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignResourceNames() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); GetCampaignRequest request = new GetCampaignRequest { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::Campaign expectedResponse = new gagvr::Campaign { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::CampaignStatusEnum.Types.CampaignStatus.Removed, AdServingOptimizationStatus = gagve::AdServingOptimizationStatusEnum.Types.AdServingOptimizationStatus.ConversionOptimize, AdvertisingChannelType = gagve::AdvertisingChannelTypeEnum.Types.AdvertisingChannelType.MultiChannel, AdvertisingChannelSubType = gagve::AdvertisingChannelSubTypeEnum.Types.AdvertisingChannelSubType.AppCampaign, UrlCustomParameters = { new gagvc::CustomParameter(), }, NetworkSettings = new gagvr::Campaign.Types.NetworkSettings(), ExperimentType = gagve::CampaignExperimentTypeEnum.Types.CampaignExperimentType.Unknown, ServingStatus = gagve::CampaignServingStatusEnum.Types.CampaignServingStatus.Ended, BiddingStrategyType = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.PercentCpc, ManualCpc = new gagvc::ManualCpc(), ManualCpm = new gagvc::ManualCpm(), TargetCpa = new gagvc::TargetCpa(), TargetSpend = new gagvc::TargetSpend(), TargetRoas = new gagvc::TargetRoas(), MaximizeConversions = new gagvc::MaximizeConversions(), MaximizeConversionValue = new gagvc::MaximizeConversionValue(), HotelSetting = new gagvr::Campaign.Types.HotelSettingInfo(), DynamicSearchAdsSetting = new gagvr::Campaign.Types.DynamicSearchAdsSetting(), PercentCpc = new gagvc::PercentCpc(), ShoppingSetting = new gagvr::Campaign.Types.ShoppingSetting(), ManualCpv = new gagvc::ManualCpv(), RealTimeBiddingSetting = new gagvc::RealTimeBiddingSetting(), FrequencyCaps = { new gagvc::FrequencyCapEntry(), }, TargetCpm = new gagvc::TargetCpm(), VideoBrandSafetySuitability = gagve::BrandSafetySuitabilityEnum.Types.BrandSafetySuitability.Unknown, TargetingSetting = new gagvc::TargetingSetting(), VanityPharma = new gagvr::Campaign.Types.VanityPharma(), SelectiveOptimization = new gagvr::Campaign.Types.SelectiveOptimization(), TrackingSetting = new gagvr::Campaign.Types.TrackingSetting(), GeoTargetTypeSetting = new gagvr::Campaign.Types.GeoTargetTypeSetting(), TargetImpressionShare = new gagvc::TargetImpressionShare(), Commission = new gagvc::Commission(), LocalCampaignSetting = new gagvr::Campaign.Types.LocalCampaignSetting(), AppCampaignSetting = new gagvr::Campaign.Types.AppCampaignSetting(), PaymentMode = gagve::PaymentModeEnum.Types.PaymentMode.Clicks, OptimizationGoalSetting = new gagvr::Campaign.Types.OptimizationGoalSetting(), BaseCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Id = -6774108720365892680L, TrackingUrlTemplate = "tracking_url_template157f152a", LabelsAsCampaignLabelNames = { gagvr::CampaignLabelName.FromCustomerCampaignLabel("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[LABEL_ID]"), }, CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", FinalUrlSuffix = "final_url_suffix046ed37a", OptimizationScore = -4.7741588361660064E+17, BiddingStrategyAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), ExcludedParentAssetFieldTypes = { gagve::AssetFieldTypeEnum.Types.AssetFieldType.Unknown, }, AccessibleBiddingStrategyAsAccessibleBiddingStrategyName = gagvr::AccessibleBiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaign(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); gagvr::Campaign response = client.GetCampaign(request.ResourceNameAsCampaignName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignResourceNamesAsync() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); GetCampaignRequest request = new GetCampaignRequest { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::Campaign expectedResponse = new gagvr::Campaign { ResourceNameAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::CampaignStatusEnum.Types.CampaignStatus.Removed, AdServingOptimizationStatus = gagve::AdServingOptimizationStatusEnum.Types.AdServingOptimizationStatus.ConversionOptimize, AdvertisingChannelType = gagve::AdvertisingChannelTypeEnum.Types.AdvertisingChannelType.MultiChannel, AdvertisingChannelSubType = gagve::AdvertisingChannelSubTypeEnum.Types.AdvertisingChannelSubType.AppCampaign, UrlCustomParameters = { new gagvc::CustomParameter(), }, NetworkSettings = new gagvr::Campaign.Types.NetworkSettings(), ExperimentType = gagve::CampaignExperimentTypeEnum.Types.CampaignExperimentType.Unknown, ServingStatus = gagve::CampaignServingStatusEnum.Types.CampaignServingStatus.Ended, BiddingStrategyType = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.PercentCpc, ManualCpc = new gagvc::ManualCpc(), ManualCpm = new gagvc::ManualCpm(), TargetCpa = new gagvc::TargetCpa(), TargetSpend = new gagvc::TargetSpend(), TargetRoas = new gagvc::TargetRoas(), MaximizeConversions = new gagvc::MaximizeConversions(), MaximizeConversionValue = new gagvc::MaximizeConversionValue(), HotelSetting = new gagvr::Campaign.Types.HotelSettingInfo(), DynamicSearchAdsSetting = new gagvr::Campaign.Types.DynamicSearchAdsSetting(), PercentCpc = new gagvc::PercentCpc(), ShoppingSetting = new gagvr::Campaign.Types.ShoppingSetting(), ManualCpv = new gagvc::ManualCpv(), RealTimeBiddingSetting = new gagvc::RealTimeBiddingSetting(), FrequencyCaps = { new gagvc::FrequencyCapEntry(), }, TargetCpm = new gagvc::TargetCpm(), VideoBrandSafetySuitability = gagve::BrandSafetySuitabilityEnum.Types.BrandSafetySuitability.Unknown, TargetingSetting = new gagvc::TargetingSetting(), VanityPharma = new gagvr::Campaign.Types.VanityPharma(), SelectiveOptimization = new gagvr::Campaign.Types.SelectiveOptimization(), TrackingSetting = new gagvr::Campaign.Types.TrackingSetting(), GeoTargetTypeSetting = new gagvr::Campaign.Types.GeoTargetTypeSetting(), TargetImpressionShare = new gagvc::TargetImpressionShare(), Commission = new gagvc::Commission(), LocalCampaignSetting = new gagvr::Campaign.Types.LocalCampaignSetting(), AppCampaignSetting = new gagvr::Campaign.Types.AppCampaignSetting(), PaymentMode = gagve::PaymentModeEnum.Types.PaymentMode.Clicks, OptimizationGoalSetting = new gagvr::Campaign.Types.OptimizationGoalSetting(), BaseCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Id = -6774108720365892680L, TrackingUrlTemplate = "tracking_url_template157f152a", LabelsAsCampaignLabelNames = { gagvr::CampaignLabelName.FromCustomerCampaignLabel("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[LABEL_ID]"), }, CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", FinalUrlSuffix = "final_url_suffix046ed37a", OptimizationScore = -4.7741588361660064E+17, BiddingStrategyAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), ExcludedParentAssetFieldTypes = { gagve::AssetFieldTypeEnum.Types.AssetFieldType.Unknown, }, AccessibleBiddingStrategyAsAccessibleBiddingStrategyName = gagvr::AccessibleBiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Campaign>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); gagvr::Campaign responseCallSettings = await client.GetCampaignAsync(request.ResourceNameAsCampaignName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Campaign responseCancellationToken = await client.GetCampaignAsync(request.ResourceNameAsCampaignName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignsRequestObject() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); MutateCampaignsRequest request = new MutateCampaignsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignsResponse expectedResponse = new MutateCampaignsResponse { Results = { new MutateCampaignResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaigns(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignsResponse response = client.MutateCampaigns(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignsRequestObjectAsync() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); MutateCampaignsRequest request = new MutateCampaignsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignsResponse expectedResponse = new MutateCampaignsResponse { Results = { new MutateCampaignResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignsResponse responseCallSettings = await client.MutateCampaignsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignsResponse responseCancellationToken = await client.MutateCampaignsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaigns() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); MutateCampaignsRequest request = new MutateCampaignsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignOperation(), }, }; MutateCampaignsResponse expectedResponse = new MutateCampaignsResponse { Results = { new MutateCampaignResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaigns(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignsResponse response = client.MutateCampaigns(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignsAsync() { moq::Mock<CampaignService.CampaignServiceClient> mockGrpcClient = new moq::Mock<CampaignService.CampaignServiceClient>(moq::MockBehavior.Strict); MutateCampaignsRequest request = new MutateCampaignsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignOperation(), }, }; MutateCampaignsResponse expectedResponse = new MutateCampaignsResponse { Results = { new MutateCampaignResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignServiceClient client = new CampaignServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignsResponse responseCallSettings = await client.MutateCampaignsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignsResponse responseCancellationToken = await client.MutateCampaignsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : brian.nickel@gmail.com based on : mpegfile.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System; namespace TagLib.Mpeg { [SupportedMimeType("taglib/mp3", "mp3")] [SupportedMimeType("audio/x-mp3")] [SupportedMimeType("application/x-id3")] [SupportedMimeType("audio/mpeg")] [SupportedMimeType("audio/x-mpeg")] [SupportedMimeType("audio/x-mpeg-3")] [SupportedMimeType("audio/mpeg3")] [SupportedMimeType("audio/mp3")] public class File : TagLib.File { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private Id3v2.Tag id3v2_tag; private Ape.Tag ape_tag; private Id3v1.Tag id3v1_tag; private CombinedTag tag; private Properties properties; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public File (string file, Properties.ReadStyle properties_style) : base (file) { id3v2_tag = null; ape_tag = null; id3v1_tag = null; tag = new CombinedTag (); properties = null; try {Mode = AccessMode.Read;} catch {return;} Read (properties_style); Mode = AccessMode.Closed; } public File (string file) : this (file, Properties.ReadStyle.Average) { } public override void Save () { Mode = AccessMode.Write; long tag_start, tag_end; // Update ID3v2 tag FindId3v2 (out tag_start, out tag_end); if (id3v2_tag == null) RemoveBlock (tag_start, tag_end - tag_start); else Insert (id3v2_tag.Render (), tag_start, tag_end - tag_start); // Update ID3v1 tag FindId3v1 (out tag_start, out tag_end); if (id3v1_tag == null) RemoveBlock (tag_start, tag_end - tag_start); else Insert (id3v1_tag.Render (), tag_start, tag_end - tag_start); // Update Ape tag FindApe (id3v2_tag != null, out tag_start, out tag_end); if (ape_tag == null) RemoveBlock (tag_start, tag_end - tag_start); else Insert (ape_tag.Render (), tag_start, tag_end - tag_start); Mode = AccessMode.Closed; } public override TagLib.Tag GetTag (TagTypes type, bool create) { switch (type) { case TagTypes.Id3v1: { if (create && id3v1_tag == null) { id3v1_tag = new Id3v1.Tag (); TagLib.Tag.Duplicate (tag, id3v1_tag, true); tag.SetTags (id3v2_tag, ape_tag, id3v1_tag); } return id3v1_tag; } case TagTypes.Id3v2: { if (create && id3v2_tag == null) { id3v2_tag = new Id3v2.Tag (); TagLib.Tag.Duplicate (tag, id3v2_tag, true); tag.SetTags (id3v2_tag, ape_tag, id3v1_tag); } return id3v2_tag; } case TagTypes.Ape: { if (create && ape_tag == null) { ape_tag = new Ape.Tag (); TagLib.Tag.Duplicate (tag, ape_tag, true); tag.SetTags (id3v2_tag, ape_tag, id3v1_tag); } return ape_tag; } default: return null; } } public void Remove (TagTypes types) { if ((types & TagTypes.Id3v1) != 0) id3v1_tag = null; if ((types & TagTypes.Id3v2) != 0) id3v2_tag = null; if ((types & TagTypes.Ape) != 0) ape_tag = null; tag.SetTags (id3v2_tag, ape_tag, id3v1_tag); } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// private Header FindFirstFrameHeader (long start) { long position = start; Seek (position); ByteVector buffer = ReadBlock (3); if (buffer.Count < 3) return null; do { Seek (position + 3); buffer = buffer.Mid (buffer.Count - 3); buffer.Add (ReadBlock ((int) BufferSize)); for (int i = 0; i < buffer.Count - 3; i++) if (buffer [i] == 0xFF && SecondSynchByte (buffer [i + 1])) try {return new Header (buffer.Mid (i, 4), position + i);} catch {} position += BufferSize; } while (buffer.Count > 3); return null; } /* private Header FindLastFrameHeader (long end) { long position = end - 3; Seek (position); ByteVector buffer = ReadBlock (3); position -= BufferSize; while (position >= 0) { Seek (position); buffer.Insert (0, ReadBlock ((int) BufferSize)); for (int i = buffer.Count - 4; i >= 0; i--) if (buffer [i] == 0xFF && SecondSynchByte (buffer [i + 1])) try {return new Header (buffer.Mid (i, 4), position + i);} catch {} position -= BufferSize; buffer = buffer.Mid (0, 3); } return null; } */ public override TagLib.Tag Tag {get {return tag;}} public override AudioProperties AudioProperties {get {return properties;}} ////////////////////////////////////////////////////////////////////////// // private methods ////////////////////////////////////////////////////////////////////////// private void Read (Properties.ReadStyle properties_style) { long start, end; Header first_header = null; // Look for an ID3v2 tag. if (FindId3v2 (out start, out end)) id3v2_tag = new Id3v2.Tag (this, start); // If we're reading properties, grab the first one for good measure. if (properties_style != Properties.ReadStyle.None) first_header = FindFirstFrameHeader (start > 2048 ? 0 : end); // Look for an ID3v1 tag. if (FindId3v1 (out start, out end)) id3v1_tag = new Id3v1.Tag (this, start); // Look for an APE tag. if (FindApe (id3v1_tag != null, out start, out end)) ape_tag = new Ape.Tag (this, start); // Set the tags and create Id3v2. tag.SetTags (id3v2_tag, ape_tag, id3v1_tag); GetTag (TagTypes.Id3v2, true); // Now read the properties. if (properties_style != Properties.ReadStyle.None) properties = new Properties (this, first_header, properties_style); } private bool FindId3v2 (out long start, out long end) { Seek (0); start = end = 0; long offset = 0; ByteVector buffer; for (buffer = ReadBlock ((int) (BufferSize + Id3v2.Header.Size - 1)); buffer.Count >= Id3v2.Header.Size; buffer.Add (ReadBlock ((int)BufferSize))) { int header_pos = buffer.Find (Id3v2.Header.FileIdentifier); if (header_pos >= 0 && header_pos < BufferSize) { Id3v2.Header header = new Id3v2.Header (buffer.Mid (header_pos, (int)Id3v2.Header.Size)); if (header.TagSize != 0) { start = offset + header_pos; end = start + header.CompleteTagSize; return true; } } int sync_position = -1; while ((sync_position = buffer.Find ((byte) 0xFF, sync_position + 1)) >= 0 && sync_position < buffer.Count) if (SecondSynchByte (buffer [sync_position + 1])) return false; buffer = buffer.Mid ((int)BufferSize); offset += BufferSize; } return false; } private bool FindApe (bool has_id3v1, out long start, out long end) { start = end = Length - (has_id3v1 ? 128 : 0); if (end >= 32) { Seek (end - 32); ByteVector data = ReadBlock (32); if (data.StartsWith (Ape.Tag.FileIdentifier)) { Ape.Footer footer = new Ape.Footer (data); start = end - footer.CompleteTagSize; return true; } } return false; } private bool FindId3v1 (out long start, out long end) { start = end = Length; if (end >= 128) { Seek (end - 128); start = Tell; if (ReadBlock (3) == Id3v1.Tag.FileIdentifier) return true; } start = end; return false; } private bool SecondSynchByte (byte b) { return b >= 0xE0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public class UnboxTests { [Theory] [PerCompilationType(nameof(UnboxableFromObject))] [PerCompilationType(nameof(NullableUnboxableFromObject))] [PerCompilationType(nameof(UnboxableFromIComparable))] [PerCompilationType(nameof(NullableUnboxableFromIComparable))] [PerCompilationType(nameof(UnboxableFromIComparableT))] [PerCompilationType(nameof(NullableUnboxableFromIComparableT))] public void CanUnbox(object value, Type type, Type boxedType, bool useInterpreter) { Expression expression = Expression.Constant(value, boxedType); UnaryExpression unbox = Expression.Unbox(expression, type); Assert.Equal(type, unbox.Type); BinaryExpression isEqual = Expression.Equal(Expression.Constant(value, type), unbox); Assert.True(Expression.Lambda<Func<bool>>(isEqual).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(UnboxableFromObject))] [PerCompilationType(nameof(NullableUnboxableFromObject))] [PerCompilationType(nameof(UnboxableFromIComparable))] [PerCompilationType(nameof(NullableUnboxableFromIComparable))] [PerCompilationType(nameof(UnboxableFromIComparableT))] [PerCompilationType(nameof(NullableUnboxableFromIComparableT))] public void CanUnboxFromMake(object value, Type type, Type boxedType, bool useInterpreter) { Expression expression = Expression.Constant(value, boxedType); UnaryExpression unbox = Expression.MakeUnary(ExpressionType.Unbox, expression, type); Assert.Equal(type, unbox.Type); BinaryExpression isEqual = Expression.Equal(Expression.Constant(value, type), unbox); Assert.True(Expression.Lambda<Func<bool>>(isEqual).Compile(useInterpreter)()); } public static IEnumerable<object[]> UnboxableFromObject() { yield return new object[] { 1, typeof(int), typeof(object) }; yield return new object[] { 42, typeof(int), typeof(object) }; yield return new object[] { DateTime.MinValue, typeof(DateTime), typeof(object) }; yield return new object[] { DateTimeOffset.MinValue, typeof(DateTimeOffset), typeof(object) }; yield return new object[] { 42L, typeof(long), typeof(object) }; yield return new object[] { 13m, typeof(decimal), typeof(object) }; yield return new object[] { ExpressionType.Unbox, typeof(ExpressionType), typeof(object) }; } public static IEnumerable<object[]> NullableUnboxableFromObject() { yield return new object[] { 1, typeof(int?), typeof(object) }; yield return new object[] { 42, typeof(int?), typeof(object) }; yield return new object[] { DateTime.MinValue, typeof(DateTime?), typeof(object) }; yield return new object[] { DateTimeOffset.MinValue, typeof(DateTimeOffset?), typeof(object) }; yield return new object[] { 42L, typeof(long?), typeof(object) }; yield return new object[] { 13m, typeof(decimal?), typeof(object) }; yield return new object[] { ExpressionType.Unbox, typeof(ExpressionType?), typeof(object) }; } public static IEnumerable<object[]> UnboxableFromIComparable() { yield return new object[] { 1, typeof(int), typeof(IComparable) }; yield return new object[] { 42, typeof(int), typeof(IComparable) }; yield return new object[] { DateTime.MinValue, typeof(DateTime), typeof(IComparable) }; yield return new object[] { DateTimeOffset.MinValue, typeof(DateTimeOffset), typeof(IComparable) }; yield return new object[] { 42L, typeof(long), typeof(IComparable) }; yield return new object[] { 13m, typeof(decimal), typeof(IComparable) }; yield return new object[] { ExpressionType.Unbox, typeof(ExpressionType), typeof(IComparable) }; } public static IEnumerable<object[]> NullableUnboxableFromIComparable() { yield return new object[] { 1, typeof(int?), typeof(IComparable) }; yield return new object[] { 42, typeof(int?), typeof(IComparable) }; yield return new object[] { DateTime.MinValue, typeof(DateTime?), typeof(IComparable) }; yield return new object[] { DateTimeOffset.MinValue, typeof(DateTimeOffset?), typeof(IComparable) }; yield return new object[] { 42L, typeof(long?), typeof(IComparable) }; yield return new object[] { 13m, typeof(decimal?), typeof(IComparable) }; yield return new object[] { ExpressionType.Unbox, typeof(ExpressionType?), typeof(IComparable) }; } public static IEnumerable<object[]> UnboxableFromIComparableT() { yield return new object[] { 1, typeof(int), typeof(IComparable<int>) }; yield return new object[] { 42, typeof(int), typeof(IComparable<int>) }; yield return new object[] { DateTime.MinValue, typeof(DateTime), typeof(IComparable<DateTime>) }; yield return new object[] { DateTimeOffset.MinValue, typeof(DateTimeOffset), typeof(IComparable<DateTimeOffset>) }; yield return new object[] { 42L, typeof(long), typeof(IComparable<long>) }; yield return new object[] { 13m, typeof(decimal), typeof(IComparable<decimal>) }; } public static IEnumerable<object[]> NullableUnboxableFromIComparableT() { yield return new object[] { 1, typeof(int?), typeof(IComparable<int>) }; yield return new object[] { 42, typeof(int?), typeof(IComparable<int>) }; yield return new object[] { DateTime.MinValue, typeof(DateTime?), typeof(IComparable<DateTime>) }; yield return new object[] { DateTimeOffset.MinValue, typeof(DateTimeOffset?), typeof(IComparable<DateTimeOffset>) }; yield return new object[] { 42L, typeof(long?), typeof(IComparable<long>) }; yield return new object[] { 13m, typeof(decimal?), typeof(IComparable<decimal>) }; } public static IEnumerable<object[]> NullableTypes() { yield return new object[] { typeof(int?) }; yield return new object[] { typeof(DateTime?) }; yield return new object[] { typeof(DateTimeKind?) }; yield return new object[] { typeof(DateTimeOffset?) }; yield return new object[] { typeof(long?) }; yield return new object[] { typeof(decimal?) }; } [Theory] [PerCompilationType(nameof(NullableTypes))] public void NullNullable(Type type, bool useInterpreter) { UnaryExpression unbox = Expression.Unbox(Expression.Default(typeof(object)), type); Func<bool> isNull = Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Default(type), unbox)).Compile(useInterpreter); Assert.True(isNull()); } [Fact] public void CannotUnboxToNonInterfaceExceptObject() { Expression value = Expression.Constant(0); Assert.Throws<ArgumentException>("expression", () => Expression.Unbox(value, typeof(int))); } [Fact] public void CannotUnboxReferenceType() { Expression value = Expression.Constant("", typeof(IComparable<string>)); Assert.Throws<ArgumentException>("type", () => Expression.Unbox(value, typeof(string))); } private static class Unreadable { public static object WriteOnly { set { } } } [Fact] public void CannotUnboxUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable), "WriteOnly"); Assert.Throws<ArgumentException>("expression", () => Expression.Unbox(value, typeof(int))); } [Fact] public void ExpressionNull() { Assert.Throws<ArgumentNullException>("expression", () => Expression.Unbox(null, typeof(int))); } [Fact] public void TypeNull() { Expression value = Expression.Constant(0, typeof(object)); Assert.Throws<ArgumentNullException>("type", () => Expression.Unbox(value, null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void MistmatchFailsOnRuntime(bool useInterpreter) { Expression unbox = Expression.Unbox(Expression.Constant(0, typeof(object)), typeof(long)); Func<long> del = Expression.Lambda<Func<long>>(unbox).Compile(useInterpreter); Assert.Throws<InvalidCastException>(() => del()); } [Fact] public void CannotReduce() { Expression unbox = Expression.Unbox(Expression.Constant(0, typeof(object)), typeof(int)); Assert.False(unbox.CanReduce); Assert.Same(unbox, unbox.Reduce()); Assert.Throws<ArgumentException>(null, () => unbox.ReduceAndCheck()); } [Fact] public static void PointerType() { Type pointerType = typeof(int).MakePointerType(); Assert.Throws<ArgumentException>("type", () => Expression.Unbox(Expression.Constant(new object()), pointerType)); } [Fact] public static void ByRefType() { Type byRefType = typeof(int).MakeByRefType(); Assert.Throws<ArgumentException>("type", () => Expression.Unbox(Expression.Constant(new object()), byRefType)); } private struct GenericValueType<T> { public T Value { get; set; } } [Fact] public static void GenericType() { Type genType = typeof(GenericValueType<>); Assert.Throws<ArgumentException>("type", () => Expression.Unbox(Expression.Constant(new object()), genType)); } [Fact] public static void GenericTypeParameters() { Type genType = typeof(GenericValueType<>); Assert.Throws<ArgumentException>("type", () => Expression.Unbox(Expression.Constant(new object()), genType.MakeGenericType(genType))); } } }
/* Copyright (c) 2014, Lars Brubaker, Kevin Pope All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.Agg.PlatformAbstract; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PluginSystem; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.PrintQueue; using MatterHackers.MatterControl.SettingsManagement; using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.PolygonMesh.Processors; using MatterHackers.RenderOpenGl.OpenGl; using MatterHackers.GuiAutomation; using MatterHackers.VectorMath; using Mindscape.Raygun4Net; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace MatterHackers.MatterControl { public class MatterControlApplication : SystemWindow { public static Action AfterFirstDraw = null; public bool RestartOnClose = false; private static readonly Vector2 minSize = new Vector2(600, 600); private static MatterControlApplication instance; private string[] commandLineArgs = null; private string confirmExit = "Confirm Exit".Localize(); private bool DoCGCollectEveryDraw = false; private int drawCount = 0; private bool firstDraw = true; private AverageMillisecondTimer millisecondTimer = new AverageMillisecondTimer(); private Gaming.Game.DataViewGraph msGraph = new Gaming.Game.DataViewGraph(new Vector2(20, 500), 50, 50, 0, 200); private string savePartsSheetExitAnywayMessage = "You are currently saving a parts sheet, are you sure you want to exit?".Localize(); private bool ShowMemoryUsed = false; private Stopwatch totalDrawTime = new Stopwatch(); private string unableToExitMessage = "Oops! You cannot exit while a print is active.".Localize(); private string unableToExitTitle = "Unable to Exit".Localize(); #if true//!DEBUG static RaygunClient _raygunClient = GetCorrectClient(); #endif static RaygunClient GetCorrectClient() { if (OsInformation.OperatingSystem == OSType.Mac) { return new RaygunClient("qmMBpKy3OSTJj83+tkO7BQ=="); // this is the Mac key } else { return new RaygunClient("hQIlyUUZRGPyXVXbI6l1dA=="); // this is the PC key } } static MatterControlApplication() { // Because fields on this class call localization methods and because those methods depend on the StaticData provider and because the field // initializers run before the class constructor, we need to init the platform specific provider in the static constructor (or write a custom initializer method) // // Initialize a standard file system backed StaticData provider StaticData.Instance = new MatterHackers.Agg.FileSystemStaticData(); } private MatterControlApplication(double width, double height, out bool showWindow) : base(width, height) { Name = "MatterControl"; showWindow = false; // set this at startup so that we can tell next time if it got set to true in close UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1; this.commandLineArgs = Environment.GetCommandLineArgs(); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; bool forceSofwareRendering = false; for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++) { string command = commandLineArgs[currentCommandIndex]; string commandUpper = command.ToUpper(); switch (commandUpper) { case "TEST": CheckKnownAssemblyConditionalCompSymbols(); return; case "FORCE_SOFTWARE_RENDERING": forceSofwareRendering = true; GL.ForceSoftwareRendering(); break; case "MHSERIAL_TO_ANDROID": { Dictionary<string, string> vidPid_NameDictionary = new Dictionary<string, string>(); string[] MHSerialLines = File.ReadAllLines(Path.Combine("..", "..", "StaticData", "Drivers", "MHSerial", "MHSerial.inf")); foreach (string line in MHSerialLines) { if (line.Contains("=DriverInstall,")) { string name = Regex.Match(line, "%(.*).name").Groups[1].Value; string vid = Regex.Match(line, "VID_(.*)&PID").Groups[1].Value; string pid = Regex.Match(line, "PID_([0-9a-fA-F]+)").Groups[1].Value; string vidPid = "{0},{1}".FormatWith(vid, pid); if (!vidPid_NameDictionary.ContainsKey(vidPid)) { vidPid_NameDictionary.Add(vidPid, name); } } } using (StreamWriter deviceFilter = new StreamWriter("deviceFilter.txt")) { using (StreamWriter serialPort = new StreamWriter("serialPort.txt")) { foreach (KeyValuePair<string, string> vidPid_Name in vidPid_NameDictionary) { string[] vidPid = vidPid_Name.Key.Split(','); int vid = Int32.Parse(vidPid[0], System.Globalization.NumberStyles.HexNumber); int pid = Int32.Parse(vidPid[1], System.Globalization.NumberStyles.HexNumber); serialPort.WriteLine("customTable.AddProduct(0x{0:X4}, 0x{1:X4}, cdcDriverType); // {2}".FormatWith(vid, pid, vidPid_Name.Value)); deviceFilter.WriteLine("<!-- {2} -->\n<usb-device vendor-id=\"{0}\" product-id=\"{1}\" />".FormatWith(vid, pid, vidPid_Name.Value)); } } } } return; case "CLEAR_CACHE": AboutWidget.DeleteCacheData(); break; case "SHOW_MEMORY": ShowMemoryUsed = true; break; case "DO_GC_COLLECT_EVERY_DRAW": ShowMemoryUsed = true; DoCGCollectEveryDraw = true; break; case "CREATE_AND_SELECT_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string argument = commandLineArgs[currentCommandIndex]; string[] printerData = argument.Split(','); if (printerData.Length >= 2) { Printer ActivePrinter = new Printer(); ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]); ActivePrinter.Make = printerData[0]; ActivePrinter.Model = printerData[1]; if (printerData.Length == 3) { ActivePrinter.ComPort = printerData[2]; } PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter); test.LoadDefaultSliceSettings(ActivePrinter.Make, ActivePrinter.Model); ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter; } } break; case "CONNECT_TO_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); } break; case "START_PRINT": if (currentCommandIndex + 1 <= commandLineArgs.Length) { bool hasBeenRun = false; currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath))); PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) => { if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected) { hasBeenRun = true; PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible(); } }, ref unregisterEvent); } } break; case "SLICE_AND_EXPORT_GCODE": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath)); QueueData.Instance.AddItem(printItemWrapper); SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper); ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper); exportForTest.ExportGcodeCommandLineUtility(fileName); } } break; } if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper())) { // If we are the only instance running then do nothing. // Else send these to the running instance so it can load them. } } //WriteTestGCodeFile(); #if !DEBUG if (File.Exists("RunUnitTests.txt")) #endif { #if IS_WINDOWS_FORMS if (!Clipboard.IsInitialized) { Clipboard.SetSystemClipboard(new WindowsFormsClipboard()); } #endif // you can turn this on to debug some bounds issues //GuiWidget.DebugBoundsUnderMouse = true; } GuiWidget.DefaultEnforceIntegerBounds = true; if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen) { TextWidget.GlobalPointSizeScaleRatio = 1.3; } this.AddChild(ApplicationController.Instance.MainView); this.MinimumSize = minSize; this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off #if false // this is to test freeing gcodefile memory Button test = new Button("test"); test.Click += (sender, e) => { //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile(); //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode"); SystemWindow window = new SystemWindow(100, 100); window.ShowAsSystemWindow(); }; allControls.AddChild(test); #endif this.AnchorAll(); if (!forceSofwareRendering) { UseOpenGL = true; } string version = "1.3"; Title = "MatterControl {0}".FormatWith(version); if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0) { Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra); } UiThread.RunOnIdle(CheckOnPrinter); string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition"); if (desktopPosition != null && desktopPosition != "") { string[] sizes = desktopPosition.Split(','); //If the desktop position is less than -10,-10, override int xpos = Math.Max(int.Parse(sizes[0]), -10); int ypos = Math.Max(int.Parse(sizes[1]), -10); DesktopPosition = new Point2D(xpos, ypos); } showWindow = true; } public enum ReportSeverity2 { Warning, Error } public void ReportException(Exception e, string key = "", string value = "", ReportSeverity2 warningLevel = ReportSeverity2.Warning) { // Conditionally spin up error reporting if not on the Stable channel string channel = UserSettings.Instance.get("UpdateFeedType"); if (string.IsNullOrEmpty(channel) || channel != "release" || OemSettings.Instance.WindowTitleExtra == "Experimental") { #if !DEBUG _raygunClient.Send(e); #endif } } private event EventHandler unregisterEvent; public static MatterControlApplication Instance { get { if (instance == null) { // try and open our window matching the last size that we had for it. string windowSize = ApplicationSettings.Instance.get("WindowSize"); int width = 1280; int height = 720; if (windowSize != null && windowSize != "") { string[] sizes = windowSize.Split(','); width = Math.Max(int.Parse(sizes[0]), (int)minSize.x + 1); height = Math.Max(int.Parse(sizes[1]), (int)minSize.y + 1); } bool showWindow; instance = new MatterControlApplication(width, height, out showWindow); if (showWindow) { instance.ShowAsSystemWindow(); } } return instance; } } [STAThread] public static void Main() { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // Make sure we have the right working directory as we assume everything relative to the executable. Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)); Datastore.Instance.Initialize(); #if !DEBUG // Conditionally spin up error reporting if not on the Stable channel string channel = UserSettings.Instance.get("UpdateFeedType"); if (string.IsNullOrEmpty(channel) || channel != "release" || OemSettings.Instance.WindowTitleExtra == "Experimental") #endif { System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); } MatterControlApplication app = MatterControlApplication.Instance; } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { #if !DEBUG _raygunClient.Send(e.Exception); #endif } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { #if !DEBUG _raygunClient.Send(e.ExceptionObject as Exception); #endif } public static void WriteTestGCodeFile() { using (StreamWriter file = new StreamWriter("PerformanceTest.gcode")) { //int loops = 150000; int loops = 150; int steps = 200; double radius = 50; Vector2 center = new Vector2(150, 100); file.WriteLine("G28 ; home all axes"); file.WriteLine("G90 ; use absolute coordinates"); file.WriteLine("G21 ; set units to millimeters"); file.WriteLine("G92 E0"); file.WriteLine("G1 F7800"); file.WriteLine("G1 Z" + (5).ToString()); WriteMove(file, center); for (int loop = 0; loop < loops; loop++) { for (int step = 0; step < steps; step++) { Vector2 nextPosition = new Vector2(radius, 0); nextPosition.Rotate(MathHelper.Tau / steps * step); WriteMove(file, center + nextPosition); } } file.WriteLine("M84 ; disable motors"); } } public void DoAutoConnectIfRequired() { ActivePrinterProfile.CheckForAndDoAutoConnect(); } public void LaunchBrowser(string targetUri) { UiThread.RunOnIdle(() => { System.Diagnostics.Process.Start(targetUri); }); } public override void OnClosed(EventArgs e) { UserSettings.Instance.Fields.StartCountDurringExit = UserSettings.Instance.Fields.StartCount; TerminalWindow.CloseIfOpen(); PrinterConnectionAndCommunication.Instance.Disable(); //Close connection to the local datastore Datastore.Instance.Exit(); PrinterConnectionAndCommunication.Instance.HaltConnectionThread(); SlicingQueue.Instance.ShutDownSlicingThread(); ApplicationController.Instance.OnApplicationClosed(); if (RestartOnClose) { string appPathAndFile = System.Reflection.Assembly.GetExecutingAssembly().Location; string pathToAppFolder = Path.GetDirectoryName(appPathAndFile); ProcessStartInfo runAppLauncherStartInfo = new ProcessStartInfo(); runAppLauncherStartInfo.Arguments = "\"{0}\" \"{1}\"".FormatWith(appPathAndFile, 1000); runAppLauncherStartInfo.FileName = Path.Combine(pathToAppFolder, "Launcher.exe"); runAppLauncherStartInfo.WindowStyle = ProcessWindowStyle.Hidden; runAppLauncherStartInfo.CreateNoWindow = true; Process.Start(runAppLauncherStartInfo); } base.OnClosed(e); } public override void OnClosing(out bool CancelClose) { // save the last size of the window so we can restore it next time. ApplicationSettings.Instance.set("WindowSize", string.Format("{0},{1}", Width, Height)); ApplicationSettings.Instance.set("DesktopPosition", string.Format("{0},{1}", DesktopPosition.x, DesktopPosition.y)); //Save a snapshot of the prints in queue QueueData.Instance.SaveDefaultQueue(); if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting) { StyledMessageBox.ShowMessageBox(null, unableToExitMessage, unableToExitTitle); CancelClose = true; } else if (PartsSheet.IsSaving()) { StyledMessageBox.ShowMessageBox(onConfirmExit, savePartsSheetExitAnywayMessage, confirmExit, StyledMessageBox.MessageType.YES_NO); CancelClose = true; } else { base.OnClosing(out CancelClose); } } public override void OnDraw(Graphics2D graphics2D) { totalDrawTime.Restart(); GuiWidget.DrawCount = 0; base.OnDraw(graphics2D); totalDrawTime.Stop(); millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds); if (ShowMemoryUsed) { long memory = GC.GetTotalMemory(false); this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, drawCount = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount); if (DoCGCollectEveryDraw) { GC.Collect(); } } if (firstDraw) { //Task.Run((Action)AutomationTest); UiThread.RunOnIdle(DoAutoConnectIfRequired); firstDraw = false; foreach (string arg in commandLineArgs) { string argExtension = Path.GetExtension(arg).ToUpper(); if (argExtension.Length > 1 && MeshFileIo.ValidFileExtensions().Contains(argExtension)) { QueueData.Instance.AddItem(new PrintItemWrapper(new DataStorage.PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg)))); } } TerminalWindow.ShowIfLeftOpen(); //new SaveAsWindow(null, null); if (AfterFirstDraw != null) { AfterFirstDraw(); } } //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds); //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D); } private void AutomationTest() { AutomationRunner test = new AutomationRunner("C:/TestImages"); test.Wait(2); test.ClickByName("SettingsAndControls"); test.Wait(2); test.ClickImage("BackButton.png"); //ImageIO.SaveImageData("test.png", test.GetCurrentScreen()); } public override void OnMouseMove(MouseEventArgs mouseEvent) { if (GuiWidget.DebugBoundsUnderMouse) { Invalidate(); } base.OnMouseMove(mouseEvent); } public override void OnParentChanged(EventArgs e) { if (File.Exists("RunUnitTests.txt")) { //DiagnosticWidget diagnosticView = new DiagnosticWidget(this); } base.OnParentChanged(e); // now that we are all set up lets load our plugins and allow them their chance to set things up FindAndInstantiatePlugins(); if(ApplicationController.Instance.PluginsLoaded != null) { ApplicationController.Instance.PluginsLoaded.CallEvents(null, null); } } public void OpenCameraPreview() { //Camera launcher placeholder (KP) if (ApplicationSettings.Instance.get("HardwareHasCamera") == "true") { //Do something } else { //Do something else (like show warning message) } } public void PlaySound(string fileName) { if (OsInformation.OperatingSystem == OSType.Windows) { using (var mediaStream = StaticData.Instance.OpenSteam(Path.Combine("Sounds", fileName))) { (new System.Media.SoundPlayer(mediaStream)).Play(); } } } private static void WriteMove(StreamWriter file, Vector2 center) { file.WriteLine("G1 X" + center.x.ToString() + " Y" + center.y.ToString()); } private void CheckOnPrinter() { try { PrinterConnectionAndCommunication.Instance.OnIdle(); } catch (Exception e) { Debug.Print(e.Message); #if DEBUG throw e; #endif } UiThread.RunOnIdle(CheckOnPrinter); } private void FindAndInstantiatePlugins() { #if false string pluginDirectory = Path.Combine("..", "..", "..", "MatterControlPlugins", "bin"); #if DEBUG pluginDirectory = Path.Combine(pluginDirectory, "Debug"); #else pluginDirectory = Path.Combine(pluginDirectory, "Release"); #endif if (!Directory.Exists(pluginDirectory)) { string dataPath = DataStorage.ApplicationDataStorage.Instance.ApplicationUserDataPath; pluginDirectory = Path.Combine(dataPath, "Plugins"); } // TODO: this should look in a plugin folder rather than just the application directory (we probably want it in the user folder). PluginFinder<MatterControlPlugin> pluginFinder = new PluginFinder<MatterControlPlugin>(pluginDirectory); #else PluginFinder<MatterControlPlugin> pluginFinder = new PluginFinder<MatterControlPlugin>(); #endif string oemName = ApplicationSettings.Instance.GetOEMName(); foreach (MatterControlPlugin plugin in pluginFinder.Plugins) { string pluginInfo = plugin.GetPluginInfoJSon(); Dictionary<string, string> nameValuePairs = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(pluginInfo); if (nameValuePairs != null && nameValuePairs.ContainsKey("OEM")) { if (nameValuePairs["OEM"] == oemName) { plugin.Initialize(this); } } else { plugin.Initialize(this); } } } private void onConfirmExit(bool messageBoxResponse) { bool CancelClose; if (messageBoxResponse) { base.OnClosing(out CancelClose); } } private static void AssertDebugNotDefined() { #if DEBUG throw new Exception("DEBUG is defined and should not be!"); #endif } public static void CheckKnownAssemblyConditionalCompSymbols() { MatterControlApplication.AssertDebugNotDefined(); MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); MatterHackers.Agg.Graphics2D.AssertDebugNotDefined(); MatterHackers.Agg.UI.SystemWindow.AssertDebugNotDefined(); ClipperLib.Clipper.AssertDebugNotDefined(); MatterHackers.Agg.ImageProcessing.InvertLightness.AssertDebugNotDefined(); MatterHackers.Localizations.TranslationMap.AssertDebugNotDefined(); MatterHackers.MarchingSquares.MarchingSquaresByte.AssertDebugNotDefined(); MatterHackers.MatterControl.PluginSystem.MatterControlPlugin.AssertDebugNotDefined(); MatterHackers.MatterSlice.MatterSlice.AssertDebugNotDefined(); MatterHackers.MeshVisualizer.MeshViewerWidget.AssertDebugNotDefined(); MatterHackers.RenderOpenGl.GLMeshTrianglePlugin.AssertDebugNotDefined(); } } }
// Copyright 2008 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.IO; using System.Runtime.InteropServices; namespace DBus.Unix { // size_t using SizeT = System.UIntPtr; // ssize_t using SSizeT = System.IntPtr; // socklen_t: assumed to be 4 bytes // uid_t: assumed to be 4 bytes //[StructLayout(LayoutKind.Sequential, Pack=1)] unsafe struct IOVector { public IOVector (IntPtr bbase, int length) { this.Base = (void*)bbase; this.length = (SizeT)length; } //public IntPtr Base; public void* Base; public SizeT length; public int Length { get { return (int)length; } set { length = (SizeT)value; } } } unsafe class UnixSocket { internal const string LIBC = "libc"; // Solaris provides socket functionality in libsocket rather than libc. // We use a dllmap in the .config to deal with this. internal const string LIBSOCKET = "libc"; public const short AF_UNIX = 1; // FIXME: SOCK_STREAM is 2 on Solaris public const short SOCK_STREAM = 1; [DllImport (LIBC, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern IntPtr fork (); [DllImport (LIBC, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern int dup2 (int fd, int fd2); [DllImport (LIBC, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern int open ([MarshalAs(UnmanagedType.LPStr)] string path, int oflag); [DllImport (LIBC, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern IntPtr setsid (); [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] internal static extern int close (int fd); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int socket (int domain, int type, int protocol); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int connect (int sockfd, byte[] serv_addr, uint addrlen); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int bind (int sockfd, byte[] my_addr, uint addrlen); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int listen (int sockfd, int backlog); //TODO: this prototype is probably wrong, fix it [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int accept (int sockfd, void* addr, ref uint addrlen); //TODO: confirm and make use of these functions [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int getsockopt (int s, int optname, IntPtr optval, ref uint optlen); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] protected static extern int setsockopt (int s, int optname, IntPtr optval, uint optlen); [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] unsafe static extern SSizeT read (int fd, byte* buf, SizeT count); [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] unsafe static extern SSizeT write (int fd, byte* buf, SizeT count); [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] unsafe static extern SSizeT readv (int fd, IOVector* iov, int iovcnt); [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] unsafe static extern SSizeT writev (int fd, IOVector* iov, int iovcnt); // Linux //[DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] //static extern int vmsplice (int fd, IOVector* iov, uint nr_segs, uint flags); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] public static extern SSizeT recvmsg (int s, void* msg, int flags); [DllImport (LIBSOCKET, CallingConvention=CallingConvention.Cdecl, SetLastError=true)] public static extern SSizeT sendmsg (int s, void* msg, int flags); public int Handle; bool ownsHandle = false; public UnixSocket (int handle) : this (handle, false) { } public UnixSocket (int handle, bool ownsHandle) { this.Handle = handle; this.ownsHandle = ownsHandle; // TODO: SafeHandle? } public UnixSocket () { //TODO: don't hard-code PF_UNIX and SOCK_STREAM or SocketType.Stream //AddressFamily family, SocketType type, ProtocolType proto int r = socket (AF_UNIX, SOCK_STREAM, 0); if (r < 0) throw UnixError.GetLastUnixException (); Handle = r; ownsHandle = true; } ~UnixSocket () { if (ownsHandle && Handle > 0) Close (); } protected bool connected = false; //TODO: consider memory management public void Close () { int r = 0; do { r = close (Handle); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); Handle = -1; connected = false; } //TODO: consider memory management public void Connect (byte[] remote_end) { int r = 0; do { r = connect (Handle, remote_end, (uint)remote_end.Length); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); connected = true; } //assigns a name to the socket public void Bind (byte[] local_end) { int r = bind (Handle, local_end, (uint)local_end.Length); if (r < 0) throw UnixError.GetLastUnixException (); } public void Listen (int backlog) { int r = listen (Handle, backlog); if (r < 0) throw UnixError.GetLastUnixException (); } public UnixSocket Accept () { byte[] addr = new byte[110]; uint addrlen = (uint)addr.Length; fixed (byte* addrP = addr) { int r = 0; do { r = accept (Handle, addrP, ref addrlen); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); //TODO: use the returned addr //string str = Encoding.Default.GetString (addr, 0, (int)addrlen); return new UnixSocket (r, true); } } unsafe public int Read (byte[] buf, int offset, int count) { fixed (byte* bufP = buf) return Read (bufP + offset, count); } public int Write (byte[] buf, int offset, int count) { fixed (byte* bufP = buf) return Write (bufP + offset, count); } unsafe public int Read (byte* bufP, int count) { int r = 0; do { r = (int)read (Handle, bufP, (SizeT)count); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); return r; } public int Write (byte* bufP, int count) { int r = 0; do { r = (int)write (Handle, bufP, (SizeT)count); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); return r; } public int RecvMsg (void* bufP, int flags) { int r = 0; do { r = (int)recvmsg (Handle, bufP, flags); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); return r; } public int SendMsg (void* bufP, int flags) { int r = 0; do { r = (int)sendmsg (Handle, bufP, flags); } while (r < 0 && UnixError.ShouldRetry); if (r < 0) throw UnixError.GetLastUnixException (); return r; } public int ReadV (IOVector* iov, int count) { //FIXME: Handle EINTR here or elsewhere //FIXME: handle r != count //TODO: check offset correctness int r = (int)readv (Handle, iov, count); if (r < 0) throw UnixError.GetLastUnixException (); return r; } public int WriteV (IOVector* iov, int count) { //FIXME: Handle EINTR here or elsewhere //FIXME: handle r != count //TODO: check offset correctness int r = (int)writev (Handle, iov, count); if (r < 0) throw UnixError.GetLastUnixException (); return r; } public int Write (IOVector[] iov, int offset, int count) { //FIXME: Handle EINTR here or elsewhere //FIXME: handle r != count //TODO: check offset correctness fixed (IOVector* bufP = &iov[offset]) { int r = (int)writev (Handle, bufP + offset, count); if (r < 0) throw UnixError.GetLastUnixException (); return r; } } public int Write (IOVector[] iov) { return Write (iov, 0, iov.Length); } } }
#pragma warning disable 0420 // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ThreadLocal.cs // // <OWNER>[....]</OWNER> // // A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing // thread; this provides an alternative to using a ThreadStatic static variable and having // to check the variable prior to every access to see if it's been initialized. // // // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Collections.Generic; using System.Security.Permissions; using System.Diagnostics.Contracts; namespace System.Threading { /// <summary> /// Provides thread-local storage of data. /// </summary> /// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam> /// <remarks> /// <para> /// With the exception of <see cref="Dispose()"/>, all public and protected members of /// <see cref="ThreadLocal{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))] [DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")] [HostProtection(Synchronization = true, ExternalThreading = true)] public class ThreadLocal<T> : IDisposable { // a delegate that returns the created value, if null the created value will be default(T) private Func<T> m_valueFactory; // // ts_slotArray is a table of thread-local values for all ThreadLocal<T> instances // // So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal<T> values for this thread and this T. // The slot relevant to this particular ThreadLocal<T> instance is determined by the m_idComplement instance field stored in // the ThreadLocal<T> instance. // [ThreadStatic] static LinkedSlotVolatile[] ts_slotArray; [ThreadStatic] static FinalizationHelper ts_finalizationHelper; // Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish // between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or // possibly due to a memory model issue in user code. private int m_idComplement; // This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor // threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false // when the instance is disposed. private volatile bool m_initialized; // IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock. private static IdManager s_idManager = new IdManager(); // A linked list of all values associated with this ThreadLocal<T> instance. // We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field. private LinkedSlot m_linkedSlot = new LinkedSlot(null); // Whether the Values property is supported private bool m_trackAllValues; /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance. /// </summary> public ThreadLocal() { Initialize(null, false); } /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance. /// </summary> /// <param name="trackAllValues">Whether to track all values set on the instance and expose them through the Values property.</param> public ThreadLocal(bool trackAllValues) { Initialize(null, trackAllValues); } /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the /// specified <paramref name="valueFactory"/> function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when /// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic). /// </exception> public ThreadLocal(Func<T> valueFactory) { if (valueFactory == null) throw new ArgumentNullException("valueFactory"); Initialize(valueFactory, false); } /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the /// specified <paramref name="valueFactory"/> function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when /// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized. /// </param> /// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic). /// </exception> public ThreadLocal(Func<T> valueFactory, bool trackAllValues) { if (valueFactory == null) throw new ArgumentNullException("valueFactory"); Initialize(valueFactory, trackAllValues); } private void Initialize(Func<T> valueFactory, bool trackAllValues) { m_valueFactory = valueFactory; m_trackAllValues = trackAllValues; // Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized // in a finally block, to avoid a thread abort in between the two statements. try { } finally { m_idComplement = ~s_idManager.GetId(); // As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception // occurred in the constructor.) m_initialized = true; } } /// <summary> /// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance. /// </summary> ~ThreadLocal() { // finalizer to return the type combination index to the pool Dispose(false); } #region IDisposable Members /// <summary> /// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance. /// </summary> /// <param name="disposing"> /// A Boolean value that indicates whether this method is being called due to a call to <see cref="Dispose()"/>. /// </param> /// <remarks> /// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe. /// </remarks> protected virtual void Dispose(bool disposing) { int id; lock (s_idManager) { id = ~m_idComplement; m_idComplement = 0; if (id < 0 || !m_initialized) { Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized"); // Handle double Dispose calls or disposal of an instance whose constructor threw an exception. return; } m_initialized = false; for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) { LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray; if (slotArray == null) { // The thread that owns this slotArray has already finished. continue; } // Remove the reference from the LinkedSlot to the slot table. linkedSlot.SlotArray = null; // And clear the references from the slot table to the linked slot and the value so that // both can get garbage collected. slotArray[id].Value.Value = default(T); slotArray[id].Value = null; } } m_linkedSlot = null; s_idManager.ReturnId(id); } #endregion /// <summary>Creates and returns a string representation of this instance for the current thread.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> for the current thread is a null reference (Nothing in Visual Basic). /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The initialization function referenced <see cref="Value"/> in an improper manner. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> /// <remarks> /// Calling this method forces initialization for the current thread, as is the /// case with accessing <see cref="Value"/> directly. /// </remarks> public override string ToString() { return Value.ToString(); } /// <summary> /// Gets or sets the value of this instance for the current thread. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The initialization function referenced <see cref="Value"/> in an improper manner. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> /// <remarks> /// If this instance was not previously initialized for the current thread, /// accessing <see cref="Value"/> will attempt to initialize it. If an initialization function was /// supplied during the construction, that initialization will happen by invoking the function /// to retrieve the initial value for <see cref="Value"/>. Otherwise, the default value of /// <typeparamref name="T"/> will be used. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { LinkedSlotVolatile[] slotArray = ts_slotArray; LinkedSlot slot; int id = ~m_idComplement; // // Attempt to get the value using the fast path // if (slotArray != null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? && m_initialized // Has the instance *still* not been disposed (important for ----s with Dispose)? ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. // This guarantees that we have a reference to the right slot. // // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // will not be reordered before the read of slotArray[id]. return slot.Value; } return GetValueSlow(); } set { LinkedSlotVolatile[] slotArray = ts_slotArray; LinkedSlot slot; int id = ~m_idComplement; // // Attempt to set the value using the fast path // if (slotArray != null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? && m_initialized // Has the instance *still* not been disposed (important for ----s with Dispose)? ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. // This guarantees that we have a reference to the right slot. // // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // will not be reordered before the read of slotArray[id]. slot.Value = value; } else { SetValueSlow(value, slotArray); } } } private T GetValueSlow() { // If the object has been disposed, the id will be -1. int id = ~m_idComplement; if (id < 0) { throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed")); } Debugger.NotifyOfCrossThreadDependency(); // Determine the initial value T value; if (m_valueFactory == null) { value = default(T); } else { value = m_valueFactory(); if (IsValueCreated) { throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_Value_RecursiveCallsToValue")); } } // Since the value has been previously uninitialized, we also need to set it (according to the ThreadLocal semantics). Value = value; return value; } private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray) { int id = ~m_idComplement; // If the object has been disposed, id will be -1. if (id < 0) { throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed")); } // If a slot array has not been created on this thread yet, create it. if (slotArray == null) { slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)]; ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues); ts_slotArray = slotArray; } // If the slot array is not big enough to hold this ID, increase the table size. if (id >= slotArray.Length) { GrowTable(ref slotArray, id + 1); ts_finalizationHelper.SlotArray = slotArray; ts_slotArray = slotArray; } // If we are using the slot in this table for the first time, create a new LinkedSlot and add it into // the linked list for this ThreadLocal instance. if (slotArray[id].Value == null) { CreateLinkedSlot(slotArray, id, value); } else { // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // that follows will not be reordered before the read of slotArray[id]. LinkedSlot slot = slotArray[id].Value; // It is important to verify that the ThreadLocal instance has not been disposed. The check must come // after capturing slotArray[id], but before assigning the value into the slot. This ensures that // if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was // created, we definitely won't assign the value into the wrong instance. if (!m_initialized) { throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed")); } slot.Value = value; } } /// <summary> /// Creates a LinkedSlot and inserts it into the linked list for this ThreadLocal instance. /// </summary> private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value) { // Create a LinkedSlot var linkedSlot = new LinkedSlot(slotArray); // Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array lock (s_idManager) { // Check that the instance has not been disposed. It is important to check this under a lock, since // Dispose also executes under a lock. if (!m_initialized) { throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed")); } LinkedSlot firstRealNode = m_linkedSlot.Next; // // Insert linkedSlot between nodes m_linkedSlot and firstRealNode. // (m_linkedSlot is the dummy head node that should always be in the front.) // linkedSlot.Next = firstRealNode; linkedSlot.Previous = m_linkedSlot; linkedSlot.Value = value; if (firstRealNode != null) { firstRealNode.Previous = linkedSlot; } m_linkedSlot.Next = linkedSlot; // Assigning the slot under a lock prevents a ---- with Dispose (dispose also acquires the lock). // Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created // with the same ID, and the write would go to the wrong instance. slotArray[id].Value = linkedSlot; } } /// <summary> /// Gets a list for all of the values currently stored by all of the threads that have accessed this instance. /// </summary> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> public IList<T> Values { get { if (!m_trackAllValues) { throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_ValuesNotAvailable")); } var list = GetValuesAsList(); // returns null if disposed if (list == null) throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed")); return list; } } /// <summary>Gets all of the threads' values in a list.</summary> private List<T> GetValuesAsList() { List<T> valueList = new List<T>(); int id = ~m_idComplement; if (id == -1) { return null; } // Walk over the linked list of slots and gather the values associated with this ThreadLocal instance. for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) { // We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot // objects will never be assigned to another ThreadLocal instance. valueList.Add(linkedSlot.Value); } return valueList; } /// <summary>Gets the number of threads that have data in this instance.</summary> private int ValuesCountForDebugDisplay { get { int count = 0; for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) { count++; } return count; } } /// <summary> /// Gets whether <see cref="Value"/> is initialized on the current thread. /// </summary> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> public bool IsValueCreated { get { int id = ~m_idComplement; if (id < 0) { throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed")); } LinkedSlotVolatile[] slotArray = ts_slotArray; return slotArray != null && id < slotArray.Length && slotArray[id].Value != null; } } /// <summary>Gets the value of the ThreadLocal&lt;T&gt; for debugging display purposes. It takes care of getting /// the value for the current thread in the ThreadLocal mode.</summary> internal T ValueForDebugDisplay { get { LinkedSlotVolatile[] slotArray = ts_slotArray; int id = ~m_idComplement; LinkedSlot slot; if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized) return default(T); return slot.Value; } } /// <summary>Gets the values of all threads that accessed the ThreadLocal&lt;T&gt;.</summary> internal List<T> ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed { get { return GetValuesAsList(); } } /// <summary> /// Resizes a table to a certain length (or larger). /// </summary> private void GrowTable(ref LinkedSlotVolatile[] table, int minLength) { Contract.Assert(table.Length < minLength); // Determine the size of the new table and allocate it. int newLen = GetNewTableSize(minLength); LinkedSlotVolatile[] newTable = new LinkedSlotVolatile[newLen]; // // The lock is necessary to avoid a race with ThreadLocal.Dispose. GrowTable has to point all // LinkedSlot instances referenced in the old table to reference the new table. Without locking, // Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while // the value continues to be referenced from the new (larger) array. // lock (s_idManager) { for (int i = 0; i < table.Length; i++) { LinkedSlot linkedSlot = table[i].Value; if (linkedSlot != null && linkedSlot.SlotArray != null) { linkedSlot.SlotArray = newTable; newTable[i] = table[i]; } } } table = newTable; } /// <summary> /// Chooses the next larger table size /// </summary> private static int GetNewTableSize(int minSize) { if ((uint)minSize > Array.MaxArrayLength) { // Intentionally return a value that will result in an OutOfMemoryException return int.MaxValue; } Contract.Assert(minSize > 0); // // Round up the size to the next power of 2 // // The algorithm takes three steps: // input -> subtract one -> propagate 1-bits to the right -> add one // // Let's take a look at the 3 steps in both interesting cases: where the input // is (Example 1) and isn't (Example 2) a power of 2. // // Example 1: 100000 -> 011111 -> 011111 -> 100000 // Example 2: 011010 -> 011001 -> 011111 -> 100000 // int newSize = minSize; // Step 1: Decrement newSize--; // Step 2: Propagate 1-bits to the right. newSize |= newSize >> 1; newSize |= newSize >> 2; newSize |= newSize >> 4; newSize |= newSize >> 8; newSize |= newSize >> 16; // Step 3: Increment newSize++; // Don't set newSize to more than Array.MaxArrayLength if ((uint)newSize > Array.MaxArrayLength) { newSize = Array.MaxArrayLength; } return newSize; } /// <summary> /// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics /// on array accesses. /// </summary> private struct LinkedSlotVolatile { internal volatile LinkedSlot Value; } /// <summary> /// A node in the doubly-linked list stored in the ThreadLocal instance. /// /// The value is stored in one of two places: /// /// 1. If SlotArray is not null, the value is in SlotArray.Table[id] /// 2. If SlotArray is null, the value is in FinalValue. /// </summary> private sealed class LinkedSlot { internal LinkedSlot(LinkedSlotVolatile[] slotArray) { SlotArray = slotArray; } // The next LinkedSlot for this ThreadLocal<> instance internal volatile LinkedSlot Next; // The previous LinkedSlot for this ThreadLocal<> instance internal volatile LinkedSlot Previous; // The SlotArray that stores this LinkedSlot at SlotArray.Table[id]. internal volatile LinkedSlotVolatile[] SlotArray; // The value for this slot. internal T Value; } /// <summary> /// A manager class that assigns IDs to ThreadLocal instances /// </summary> private class IdManager { // The next ID to try private int m_nextIdToTry = 0; // Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager. private List<bool> m_freeIds = new List<bool>(); internal int GetId() { lock (m_freeIds) { int availableId = m_nextIdToTry; while (availableId < m_freeIds.Count) { if (m_freeIds[availableId]) { break; } availableId++; } if (availableId == m_freeIds.Count) { m_freeIds.Add(false); } else { m_freeIds[availableId] = false; } m_nextIdToTry = availableId + 1; return availableId; } } // Return an ID to the pool internal void ReturnId(int id) { lock (m_freeIds) { m_freeIds[id] = true; if (id < m_nextIdToTry) m_nextIdToTry = id; } } } /// <summary> /// A class that facilitates ThreadLocal cleanup after a thread exits. /// /// After a thread with an associated thread-local table has exited, the FinalizationHelper /// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper /// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once /// the thread has exited. /// /// The FinalizationHelper then locates all LinkedSlot instances with back-references to the table /// (all those LinkedSlot instances can be found by following references from the table slots) and /// releases the table so that it can get GC'd. /// </summary> private class FinalizationHelper { internal LinkedSlotVolatile[] SlotArray; private bool m_trackAllValues; internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues) { SlotArray = slotArray; m_trackAllValues = trackAllValues; } ~FinalizationHelper() { LinkedSlotVolatile[] slotArray = SlotArray; Contract.Assert(slotArray != null); for (int i = 0; i < slotArray.Length; i++) { LinkedSlot linkedSlot = slotArray[i].Value; if (linkedSlot == null) { // This slot in the table is empty continue; } if (m_trackAllValues) { // Set the SlotArray field to null to release the slot array. linkedSlot.SlotArray = null; } else { // Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to // the table will be have been removed, and so the table can get GC'd. lock (s_idManager) { if (linkedSlot.Next != null) { linkedSlot.Next.Previous = linkedSlot.Previous; } // Since the list uses a dummy head node, the Previous reference should never be null. Contract.Assert(linkedSlot.Previous != null); linkedSlot.Previous.Next = linkedSlot.Next; } } } } } } /// <summary>A debugger view of the ThreadLocal&lt;T&gt; to surface additional debugging properties and /// to ensure that the ThreadLocal&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class SystemThreading_ThreadLocalDebugView<T> { //The ThreadLocal object being viewed. private readonly ThreadLocal<T> m_tlocal; /// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary> /// <param name="tlocal">A ThreadLocal object to browse in the debugger.</param> public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal) { m_tlocal = tlocal; } /// <summary>Returns whether the ThreadLocal object is initialized or not.</summary> public bool IsValueCreated { get { return m_tlocal.IsValueCreated; } } /// <summary>Returns the value of the ThreadLocal object.</summary> public T Value { get { return m_tlocal.ValueForDebugDisplay; } } /// <summary>Return all values for all threads that have accessed this instance.</summary> public List<T> Values { get { return m_tlocal.ValuesForDebugDisplay; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookRangeViewRequest. /// </summary> public partial class WorkbookRangeViewRequest : BaseRequest, IWorkbookRangeViewRequest { /// <summary> /// Constructs a new WorkbookRangeViewRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookRangeViewRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookRangeView using POST. /// </summary> /// <param name="workbookRangeViewToCreate">The WorkbookRangeView to create.</param> /// <returns>The created WorkbookRangeView.</returns> public System.Threading.Tasks.Task<WorkbookRangeView> CreateAsync(WorkbookRangeView workbookRangeViewToCreate) { return this.CreateAsync(workbookRangeViewToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookRangeView using POST. /// </summary> /// <param name="workbookRangeViewToCreate">The WorkbookRangeView to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookRangeView.</returns> public async System.Threading.Tasks.Task<WorkbookRangeView> CreateAsync(WorkbookRangeView workbookRangeViewToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookRangeView>(workbookRangeViewToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookRangeView. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookRangeView. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookRangeView>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookRangeView. /// </summary> /// <returns>The WorkbookRangeView.</returns> public System.Threading.Tasks.Task<WorkbookRangeView> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookRangeView. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookRangeView.</returns> public async System.Threading.Tasks.Task<WorkbookRangeView> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookRangeView>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookRangeView using PATCH. /// </summary> /// <param name="workbookRangeViewToUpdate">The WorkbookRangeView to update.</param> /// <returns>The updated WorkbookRangeView.</returns> public System.Threading.Tasks.Task<WorkbookRangeView> UpdateAsync(WorkbookRangeView workbookRangeViewToUpdate) { return this.UpdateAsync(workbookRangeViewToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookRangeView using PATCH. /// </summary> /// <param name="workbookRangeViewToUpdate">The WorkbookRangeView to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookRangeView.</returns> public async System.Threading.Tasks.Task<WorkbookRangeView> UpdateAsync(WorkbookRangeView workbookRangeViewToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookRangeView>(workbookRangeViewToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeViewRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeViewRequest Expand(Expression<Func<WorkbookRangeView, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeViewRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeViewRequest Select(Expression<Func<WorkbookRangeView, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookRangeViewToInitialize">The <see cref="WorkbookRangeView"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookRangeView workbookRangeViewToInitialize) { if (workbookRangeViewToInitialize != null && workbookRangeViewToInitialize.AdditionalData != null) { if (workbookRangeViewToInitialize.Rows != null && workbookRangeViewToInitialize.Rows.CurrentPage != null) { workbookRangeViewToInitialize.Rows.AdditionalData = workbookRangeViewToInitialize.AdditionalData; object nextPageLink; workbookRangeViewToInitialize.AdditionalData.TryGetValue("rows@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { workbookRangeViewToInitialize.Rows.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace Newtonsoft.Json { public static class __JsonConvert { public static IObservable<System.String> ToString(IObservable<System.DateTime> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.DateTime> value, IObservable<Newtonsoft.Json.DateFormatHandling> format, IObservable<Newtonsoft.Json.DateTimeZoneHandling> timeZoneHandling) { return Observable.Zip(value, format, timeZoneHandling, (valueLambda, formatLambda, timeZoneHandlingLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda, formatLambda, timeZoneHandlingLambda)); } public static IObservable<System.String> ToString(IObservable<System.DateTimeOffset> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.DateTimeOffset> value, IObservable<Newtonsoft.Json.DateFormatHandling> format) { return Observable.Zip(value, format, (valueLambda, formatLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda, formatLambda)); } public static IObservable<System.String> ToString(IObservable<System.Boolean> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Char> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Enum> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Int32> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Int16> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.UInt16> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.UInt32> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Int64> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.UInt64> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Single> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Double> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Byte> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.SByte> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Decimal> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Guid> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.TimeSpan> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.Uri> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> ToString(IObservable<System.String> value, IObservable<System.Char> delimiter) { return Observable.Zip(value, delimiter, (valueLambda, delimiterLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda, delimiterLambda)); } public static IObservable<System.String> ToString(IObservable<System.String> value, IObservable<System.Char> delimiter, IObservable<Newtonsoft.Json.StringEscapeHandling> stringEscapeHandling) { return Observable.Zip(value, delimiter, stringEscapeHandling, (valueLambda, delimiterLambda, stringEscapeHandlingLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda, delimiterLambda, stringEscapeHandlingLambda)); } public static IObservable<System.String> ToString(IObservable<System.Object> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.ToString(valueLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<Newtonsoft.Json.Formatting> formatting) { return Observable.Zip(value, formatting, (valueLambda, formattingLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, formattingLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<Newtonsoft.Json.JsonConverter[]> converters) { return Observable.Zip(value, converters, (valueLambda, convertersLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, convertersLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<Newtonsoft.Json.JsonConverter[]> converters) { return Observable.Zip(value, formatting, converters, (valueLambda, formattingLambda, convertersLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, formattingLambda, convertersLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, settings, (valueLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, settingsLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<System.Type> type, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, type, settings, (valueLambda, typeLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, typeLambda, settingsLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, formatting, settings, (valueLambda, formattingLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, formattingLambda, settingsLambda)); } public static IObservable<System.String> SerializeObject(IObservable<System.Object> value, IObservable<System.Type> type, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, type, formatting, settings, (valueLambda, typeLambda, formattingLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.SerializeObject(valueLambda, typeLambda, formattingLambda, settingsLambda)); } public static IObservable<System.String> SerializeObjectAsync(IObservable<System.Object> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.SerializeObjectAsync(valueLambda).ToObservable()).Flatten(); } public static IObservable<System.String> SerializeObjectAsync(IObservable<System.Object> value, IObservable<Newtonsoft.Json.Formatting> formatting) { return Observable.Zip(value, formatting, (valueLambda, formattingLambda) => Newtonsoft.Json.JsonConvert.SerializeObjectAsync(valueLambda, formattingLambda).ToObservable()).Flatten(); } public static IObservable<System.String> SerializeObjectAsync(IObservable<System.Object> value, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, formatting, settings, (valueLambda, formattingLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.SerializeObjectAsync(valueLambda, formattingLambda, settingsLambda).ToObservable()).Flatten(); } public static IObservable<System.Object> DeserializeObject(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject(valueLambda)); } public static IObservable<System.Object> DeserializeObject(IObservable<System.String> value, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, settings, (valueLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject(valueLambda, settingsLambda)); } public static IObservable<System.Object> DeserializeObject(IObservable<System.String> value, IObservable<System.Type> type) { return Observable.Zip(value, type, (valueLambda, typeLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject(valueLambda, typeLambda)); } public static IObservable<T> DeserializeObject<T>(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject<T>(valueLambda)); } public static IObservable<T> DeserializeAnonymousType<T>(IObservable<System.String> value, IObservable<T> anonymousTypeObject) { return Observable.Zip(value, anonymousTypeObject, (valueLambda, anonymousTypeObjectLambda) => Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(valueLambda, anonymousTypeObjectLambda)); } public static IObservable<T> DeserializeAnonymousType<T>(IObservable<System.String> value, IObservable<T> anonymousTypeObject, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, anonymousTypeObject, settings, (valueLambda, anonymousTypeObjectLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(valueLambda, anonymousTypeObjectLambda, settingsLambda)); } public static IObservable<T> DeserializeObject<T>(IObservable<System.String> value, IObservable<Newtonsoft.Json.JsonConverter[]> converters) { return Observable.Zip(value, converters, (valueLambda, convertersLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject<T>(valueLambda, convertersLambda)); } public static IObservable<T> DeserializeObject<T>(IObservable<System.String> value, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, settings, (valueLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject<T>(valueLambda, settingsLambda)); } public static IObservable<System.Object> DeserializeObject(IObservable<System.String> value, IObservable<System.Type> type, IObservable<Newtonsoft.Json.JsonConverter[]> converters) { return Observable.Zip(value, type, converters, (valueLambda, typeLambda, convertersLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject(valueLambda, typeLambda, convertersLambda)); } public static IObservable<System.Object> DeserializeObject(IObservable<System.String> value, IObservable<System.Type> type, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, type, settings, (valueLambda, typeLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.DeserializeObject(valueLambda, typeLambda, settingsLambda)); } public static IObservable<T> DeserializeObjectAsync<T>(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(valueLambda).ToObservable()).Flatten(); } public static IObservable<T> DeserializeObjectAsync<T>(IObservable<System.String> value, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, settings, (valueLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(valueLambda, settingsLambda).ToObservable()).Flatten(); } public static IObservable<System.Object> DeserializeObjectAsync(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DeserializeObjectAsync(valueLambda).ToObservable()).Flatten(); } public static IObservable<System.Object> DeserializeObjectAsync(IObservable<System.String> value, IObservable<System.Type> type, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, type, settings, (valueLambda, typeLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.DeserializeObjectAsync(valueLambda, typeLambda, settingsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> PopulateObject(IObservable<System.String> value, IObservable<System.Object> target) { return ObservableExt.ZipExecute(value, target, (valueLambda, targetLambda) => Newtonsoft.Json.JsonConvert.PopulateObject(valueLambda, targetLambda)); } public static IObservable<System.Reactive.Unit> PopulateObject(IObservable<System.String> value, IObservable<System.Object> target, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return ObservableExt.ZipExecute(value, target, settings, (valueLambda, targetLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.PopulateObject(valueLambda, targetLambda, settingsLambda)); } public static IObservable<System.Reactive.Unit> PopulateObjectAsync(IObservable<System.String> value, IObservable<System.Object> target, IObservable<Newtonsoft.Json.JsonSerializerSettings> settings) { return Observable.Zip(value, target, settings, (valueLambda, targetLambda, settingsLambda) => Newtonsoft.Json.JsonConvert.PopulateObjectAsync(valueLambda, targetLambda, settingsLambda).ToObservable()).Flatten(); } public static IObservable<System.String> SerializeXmlNode(IObservable<System.Xml.XmlNode> node) { return Observable.Select(node, (nodeLambda) => Newtonsoft.Json.JsonConvert.SerializeXmlNode(nodeLambda)); } public static IObservable<System.String> SerializeXmlNode(IObservable<System.Xml.XmlNode> node, IObservable<Newtonsoft.Json.Formatting> formatting) { return Observable.Zip(node, formatting, (nodeLambda, formattingLambda) => Newtonsoft.Json.JsonConvert.SerializeXmlNode(nodeLambda, formattingLambda)); } public static IObservable<System.String> SerializeXmlNode(IObservable<System.Xml.XmlNode> node, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<System.Boolean> omitRootObject) { return Observable.Zip(node, formatting, omitRootObject, (nodeLambda, formattingLambda, omitRootObjectLambda) => Newtonsoft.Json.JsonConvert.SerializeXmlNode(nodeLambda, formattingLambda, omitRootObjectLambda)); } public static IObservable<System.Xml.XmlDocument> DeserializeXmlNode(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DeserializeXmlNode(valueLambda)); } public static IObservable<System.Xml.XmlDocument> DeserializeXmlNode(IObservable<System.String> value, IObservable<System.String> deserializeRootElementName) { return Observable.Zip(value, deserializeRootElementName, (valueLambda, deserializeRootElementNameLambda) => Newtonsoft.Json.JsonConvert.DeserializeXmlNode(valueLambda, deserializeRootElementNameLambda)); } public static IObservable<System.Xml.XmlDocument> DeserializeXmlNode(IObservable<System.String> value, IObservable<System.String> deserializeRootElementName, IObservable<System.Boolean> writeArrayAttribute) { return Observable.Zip(value, deserializeRootElementName, writeArrayAttribute, (valueLambda, deserializeRootElementNameLambda, writeArrayAttributeLambda) => Newtonsoft.Json.JsonConvert.DeserializeXmlNode(valueLambda, deserializeRootElementNameLambda, writeArrayAttributeLambda)); } public static IObservable<System.String> SerializeXNode(IObservable<System.Xml.Linq.XObject> node) { return Observable.Select(node, (nodeLambda) => Newtonsoft.Json.JsonConvert.SerializeXNode(nodeLambda)); } public static IObservable<System.String> SerializeXNode(IObservable<System.Xml.Linq.XObject> node, IObservable<Newtonsoft.Json.Formatting> formatting) { return Observable.Zip(node, formatting, (nodeLambda, formattingLambda) => Newtonsoft.Json.JsonConvert.SerializeXNode(nodeLambda, formattingLambda)); } public static IObservable<System.String> SerializeXNode(IObservable<System.Xml.Linq.XObject> node, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<System.Boolean> omitRootObject) { return Observable.Zip(node, formatting, omitRootObject, (nodeLambda, formattingLambda, omitRootObjectLambda) => Newtonsoft.Json.JsonConvert.SerializeXNode(nodeLambda, formattingLambda, omitRootObjectLambda)); } public static IObservable<System.Xml.Linq.XDocument> DeserializeXNode(IObservable<System.String> value) { return Observable.Select(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DeserializeXNode(valueLambda)); } public static IObservable<System.Xml.Linq.XDocument> DeserializeXNode(IObservable<System.String> value, IObservable<System.String> deserializeRootElementName) { return Observable.Zip(value, deserializeRootElementName, (valueLambda, deserializeRootElementNameLambda) => Newtonsoft.Json.JsonConvert.DeserializeXNode(valueLambda, deserializeRootElementNameLambda)); } public static IObservable<System.Xml.Linq.XDocument> DeserializeXNode(IObservable<System.String> value, IObservable<System.String> deserializeRootElementName, IObservable<System.Boolean> writeArrayAttribute) { return Observable.Zip(value, deserializeRootElementName, writeArrayAttribute, (valueLambda, deserializeRootElementNameLambda, writeArrayAttributeLambda) => Newtonsoft.Json.JsonConvert.DeserializeXNode(valueLambda, deserializeRootElementNameLambda, writeArrayAttributeLambda)); } public static IObservable<System.Func<Newtonsoft.Json.JsonSerializerSettings>> get_DefaultSettings() { return ObservableExt.Factory(() => Newtonsoft.Json.JsonConvert.DefaultSettings); } public static IObservable<System.Reactive.Unit> set_DefaultSettings(IObservable<System.Func<Newtonsoft.Json.JsonSerializerSettings>> value) { return Observable.Do(value, (valueLambda) => Newtonsoft.Json.JsonConvert.DefaultSettings = valueLambda).ToUnit(); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Core; using Orleans.Providers; using Orleans.Runtime.Configuration; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.Placement; using Orleans.Runtime.Scheduler; using Orleans.Storage; namespace Orleans.Runtime { internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener { /// <summary> /// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected. /// </summary> [Serializable] internal class DuplicateActivationException : Exception { public ActivationAddress ActivationToUse { get; set; } public SiloAddress PrimaryDirectoryForGrain { get; set; } // for diagnostics only! } [Serializable] internal class NonExistentActivationException : Exception { public NonExistentActivationException(string message) : base(message) { } public ActivationAddress NonExistentActivation { get; set; } } public GrainTypeManager GrainTypeManager { get; private set; } public SiloAddress LocalSilo { get; private set; } internal ISiloStatusOracle SiloStatusOracle { get; set; } internal readonly ActivationCollector ActivationCollector; private readonly ILocalGrainDirectory directory; private readonly OrleansTaskScheduler scheduler; private readonly ActivationDirectory activations; private IStorageProviderManager storageProviderManager; private Dispatcher dispatcher; private readonly TraceLogger logger; private int collectionNumber; private int destroyActivationsNumber; private IDisposable gcTimer; private readonly GlobalConfiguration config; private readonly string localSiloName; private readonly CounterStatistic activationsCreated; private readonly CounterStatistic activationsDestroyed; private readonly CounterStatistic activationsFailedToActivate; private readonly IntValueStatistic inProcessRequests; private readonly CounterStatistic collectionCounter; private readonly IGrainRuntime grainRuntime; internal Catalog( GrainId grainId, SiloAddress silo, string siloName, ILocalGrainDirectory grainDirectory, GrainTypeManager typeManager, OrleansTaskScheduler scheduler, ActivationDirectory activationDirectory, ClusterConfiguration config, IGrainRuntime grainRuntime, out Action<Dispatcher> setDispatcher) : base(grainId, silo) { LocalSilo = silo; localSiloName = siloName; directory = grainDirectory; activations = activationDirectory; this.scheduler = scheduler; GrainTypeManager = typeManager; this.grainRuntime = grainRuntime; collectionNumber = 0; destroyActivationsNumber = 0; logger = TraceLogger.GetLogger("Catalog", TraceLogger.LoggerType.Runtime); this.config = config.Globals; setDispatcher = d => dispatcher = d; ActivationCollector = new ActivationCollector(config); GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false); IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count); activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED); activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED); activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE); collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS); inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () => { long counter = 0; lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; counter += data.GetRequestCount(); } } return counter; }); } internal void SetStorageManager(IStorageProviderManager storageManager) { storageProviderManager = storageManager; } internal void Start() { if (gcTimer != null) gcTimer.Dispose(); var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum); t.Start(); gcTimer = t; } private Task OnTimer(object _) { return CollectActivationsImpl(true); } public Task CollectActivations(TimeSpan ageLimit) { return CollectActivationsImpl(false, ageLimit); } private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan)) { var watch = new Stopwatch(); watch.Start(); var number = Interlocked.Increment(ref collectionNumber); long memBefore = GC.GetTotalMemory(false) / (1024 * 1024); logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.", number, memBefore, activations.Count, ActivationCollector.ToString()); List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit); collectionCounter.Increment(); var count = 0; if (list != null && list.Count > 0) { count = list.Count; if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId)); await DeactivateActivationsFromCollector(list); } long memAfter = GC.GetTotalMemory(false) / (1024 * 1024); watch.Stop(); logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.", number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed); } public List<Tuple<GrainId, string, int>> GetGrainStatistics() { var counts = new Dictionary<string, Dictionary<GrainId, int>>(); lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; if (data == null || data.GrainInstance == null) continue; // TODO: generic type expansion var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType); Dictionary<GrainId, int> grains; int n; if (!counts.TryGetValue(grainTypeName, out grains)) { counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } }); } else if (!grains.TryGetValue(data.Grain, out n)) grains[data.Grain] = 1; else grains[data.Grain] = n + 1; } } return counts .SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value))) .ToList(); } public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics() { return activations.GetSimpleGrainStatistics(); } public DetailedGrainReport GetDetailedGrainReport(GrainId grain) { var report = new DetailedGrainReport { Grain = grain, SiloAddress = LocalSilo, SiloName = localSiloName, LocalCacheActivationAddresses = directory.GetLocalCacheData(grain), LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain), PrimaryForGrain = directory.GetPrimaryForGrain(grain) }; try { PlacementStrategy unused; string grainClassName; GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused); report.GrainClassTypeName = grainClassName; } catch (Exception exc) { report.GrainClassTypeName = exc.ToString(); } List<ActivationData> acts = activations.FindTargets(grain); report.LocalActivations = acts != null ? acts.Select(activationData => activationData.ToDetailedString()).ToList() : new List<string>(); return report; } #region MessageTargets /// <summary> /// Register a new object to which messages can be delivered with the local lookup table and scheduler. /// </summary> /// <param name="activation"></param> public void RegisterMessageTarget(ActivationData activation) { var context = new SchedulingContext(activation); scheduler.RegisterWorkContext(context); activations.RecordNewTarget(activation); activationsCreated.Increment(); } /// <summary> /// Unregister message target and stop delivering messages to it /// </summary> /// <param name="activation"></param> public void UnregisterMessageTarget(ActivationData activation) { activations.RemoveTarget(activation); // this should be removed once we've refactored the deactivation code path. For now safe to keep. ActivationCollector.TryCancelCollection(activation); activationsDestroyed.Increment(); scheduler.UnregisterWorkContext(new SchedulingContext(activation)); if (activation.GrainInstance == null) return; var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType); activations.DecrementGrainCounter(grainTypeName); activation.SetGrainInstance(null); } /// <summary> /// FOR TESTING PURPOSES ONLY!! /// </summary> /// <param name="grain"></param> internal int UnregisterGrainForTesting(GrainId grain) { var acts = activations.FindTargets(grain); if (acts == null) return 0; int numActsBefore = acts.Count; foreach (var act in acts) UnregisterMessageTarget(act); return numActsBefore; } #endregion #region Grains internal bool IsReentrantGrain(ActivationId running) { ActivationData target; GrainTypeData data; return TryGetActivationData(running, out target) && target.GrainInstance != null && GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) && data.IsReentrant; } public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, string genericArguments = null) { GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, genericArguments); } #endregion #region Activations public int ActivationCount { get { return activations.Count; } } /// <summary> /// If activation already exists, use it /// Otherwise, create an activation of an existing grain by reading its state. /// Return immediately using a dummy that will queue messages. /// Concurrently start creating and initializing the real activation and replace it when it is ready. /// </summary> /// <param name="address">Grain's activation address</param> /// <param name="newPlacement">Creation of new activation was requested by the placement director.</param> /// <param name="grainType">The type of grain to be activated or created</param> /// <param name="genericArguments">Specific generic type of grain to be activated or created</param> /// <param name="activatedPromise"></param> /// <returns></returns> public ActivationData GetOrCreateActivation( ActivationAddress address, bool newPlacement, string grainType, string genericArguments, out Task activatedPromise) { ActivationData result; activatedPromise = TaskDone.Done; lock (activations) { if (TryGetActivationData(address.Activation, out result)) { ActivationCollector.TryRescheduleCollection(result); return result; } if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating()) { // create a dummy activation that will queue up messages until the real data arrives PlacementStrategy placement; int typeCode = address.Grain.GetTypeCode(); string actualGrainType = null; if (typeCode != 0) // special case for Membership grain. GetGrainTypeInfo(typeCode, out actualGrainType, out placement); else placement = SystemPlacement.Singleton; if (string.IsNullOrEmpty(grainType)) { grainType = actualGrainType; } // We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory. result = new ActivationData( address, genericArguments, placement, ActivationCollector, config.Application.GetCollectionAgeLimit(grainType)); RegisterMessageTarget(result); } } // End lock // Did not find and did not start placing new if (result == null) { var msg = String.Format("Non-existent activation: {0}, grain type: {1}.", address.ToFullString(), grainType); if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment(); throw new NonExistentActivationException(msg) { NonExistentActivation = address }; } SetupActivationInstance(result, grainType, genericArguments); activatedPromise = InitActivation(result, grainType, genericArguments); return result; } private void SetupActivationInstance(ActivationData result, string grainType, string genericInterface) { var genericArguments = String.IsNullOrEmpty(genericInterface) ? null : TypeUtils.GenericTypeArgsString(genericInterface); lock (result) { if (result.GrainInstance == null) { CreateGrainInstance(grainType, result, genericArguments); } } } private async Task InitActivation(ActivationData activation, string grainType, string genericInterface) { // We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly) // the operations required to turn the "dummy" activation into a real activation ActivationAddress address = activation.Address; int initStage = 0; // A chain of promises that will have to complete in order to complete the activation // Register with the grain directory, register with the store if necessary and call the Activate method on the new activation. try { initStage = 1; await RegisterActivationInGrainDirectory(address, !activation.IsMultiActivationGrain); initStage = 2; await SetupActivationState(activation, grainType); initStage = 3; await InvokeActivate(activation); ActivationCollector.ScheduleCollection(activation); // Success!! Log the result, and start processing messages if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address); } catch (Exception ex) { lock (activation) { activation.SetState(ActivationState.Invalid); try { UnregisterMessageTarget(activation); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc); } switch (initStage) { case 1: // failed to RegisterActivationInGrainDirectory ActivationAddress target = null; Exception dupExc; // Failure!! Could it be that this grain uses single activation placement, and there already was an activation? if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc)) { target = ((DuplicateActivationException) dupExc).ActivationToUse; CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS) .Increment(); } activation.ForwardingAddress = target; if (target != null) { // If this was a duplicate, it's not an error, just a race. // Forward on all of the pending messages, and then forget about this activation. logger.Info(ErrorCode.Catalog_DuplicateActivation, "Tried to create a duplicate activation {0}, but we'll use {1} instead. " + "GrainInstanceType is {2}. " + "Primary Directory partition for this grain is {3}, " + "full activation address is {4}. We have {5} messages to forward.", address, target, activation.GrainInstanceType, ((DuplicateActivationException) dupExc).PrimaryDirectoryForGrain, address.ToFullString(), activation.WaitingCount); RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex); } else { logger.Warn(ErrorCode.Runtime_Error_100064, String.Format("Failed to RegisterActivationInGrainDirectory for {0}.", activation), ex); // Need to undo the registration we just did earlier scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address), SchedulingContext).Ignore(); RerouteAllQueuedMessages(activation, null, "Failed RegisterActivationInGrainDirectory", ex); } break; case 2: // failed to setup persistent state logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState, String.Format("Failed to SetupActivationState for {0}.", activation), ex); // Need to undo the registration we just did earlier scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address), SchedulingContext).Ignore(); RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex); break; case 3: // failed to InvokeActivate logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate, String.Format("Failed to InvokeActivate for {0}.", activation), ex); // Need to undo the registration we just did earlier scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address), SchedulingContext).Ignore(); RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex); break; } } throw; } } /// <summary> /// Perform just the prompt, local part of creating an activation object /// Caller is responsible for registering locally, registering with store and calling its activate routine /// </summary> /// <param name="grainTypeName"></param> /// <param name="data"></param> /// <param name="genericArguments"></param> /// <returns></returns> private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments) { string grainClassName; var interfaceToClassMap = GrainTypeManager.GetGrainInterfaceToClassMap(); if (!interfaceToClassMap.TryGetValue(grainTypeName, out grainClassName)) { // Lookup from grain type code var typeCode = data.Grain.GetTypeCode(); if (typeCode != 0) { PlacementStrategy unused; GetGrainTypeInfo(typeCode, out grainClassName, out unused, genericArguments); } else { grainClassName = grainTypeName; } } GrainTypeData grainTypeData = GrainTypeManager[grainClassName]; Type grainType = grainTypeData.Type; Type stateObjectType = grainTypeData.StateObjectType; lock (data) { var grain = (Grain) Activator.CreateInstance(grainType); grain.Identity = data.Identity; grain.Runtime = grainRuntime; data.SetGrainInstance(grain); if (stateObjectType != null) { SetupStorageProvider(data); var state = (GrainState)Activator.CreateInstance(stateObjectType); state.InitState(null); data.GrainInstance.GrainState = state; data.GrainInstance.Storage = new GrainStateStorageBridge(data.GrainTypeName, data.GrainInstance, data.StorageProvider); } } activations.IncrementGrainCounter(grainClassName); data.GrainInstance.Data = data; if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId); } private void SetupStorageProvider(ActivationData data) { var grainTypeName = data.GrainInstanceType.FullName; // Get the storage provider name, using the default if not specified. var attrs = data.GrainInstanceType.GetCustomAttributes(typeof(StorageProviderAttribute), true); var attr = attrs.FirstOrDefault() as StorageProviderAttribute; var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME; IStorageProvider provider; if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0) { var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName); logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg); throw new BadProviderConfigException(errMsg); } if (string.IsNullOrWhiteSpace(storageProviderName)) { // Use default storage provider provider = storageProviderManager.GetDefaultProvider(); } else { // Look for MemoryStore provider as special case name bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase); storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive); if (provider == null) { var errMsg = string.Format( "Cannot find storage provider with Name={0} for grain type {1}", storageProviderName, grainTypeName); logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg); throw new BadProviderConfigException(errMsg); } } data.StorageProvider = provider; if (logger.IsVerbose2) { string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}", storageProviderName, grainTypeName); logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg); } } private async Task SetupActivationState(ActivationData result, string grainType) { var state = result.GrainInstance.GrainState; if (result.StorageProvider != null && state != null) { var sw = Stopwatch.StartNew(); // Populate state data try { var grainRef = result.GrainReference; await scheduler.RunOrQueueTask(() => result.StorageProvider.ReadStateAsync(grainType, grainRef, state), new SchedulingContext(result)); sw.Stop(); StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed); result.GrainInstance.GrainState = state; } catch (Exception ex) { StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference); sw.Stop(); if (!(ex.GetBaseException() is KeyNotFoundException)) throw; result.GrainInstance.GrainState = state; // Just keep original empty state object } } } /// <summary> /// Try to get runtime data for an activation /// </summary> /// <param name="activationId"></param> /// <param name="data"></param> /// <returns></returns> public bool TryGetActivationData(ActivationId activationId, out ActivationData data) { data = null; if (activationId.IsSystem) return false; data = activations.FindTarget(activationId); return data != null; } private Task DeactivateActivationsFromCollector(List<ActivationData> list) { logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count); foreach (var activation in list) { lock (activation) { activation.PrepareForDeactivation(); // Don't accept any new messages } } return DestroyActivations(list); } // To be called fro within Activation context. // Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task. internal void DeactivateActivationOnIdle(ActivationData data) { bool promptly = false; bool alreadBeingDestroyed = false; lock (data) { if (data.State == ActivationState.Valid) { // Change the ActivationData state here, since we're about to give up the lock. data.PrepareForDeactivation(); // Don't accept any new messages if (!data.IsCurrentlyExecuting) { promptly = true; } else // busy, so destroy later. { data.AddOnInactive(() => DestroyActivationVoid(data)); } } else { alreadBeingDestroyed = true; } } logger.Info(ErrorCode.Catalog_ShutdownActivations_2, "DeactivateActivationOnIdle: 1 {0}.", promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle")); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE).Increment(); if (promptly) { DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed! } } /// <summary> /// Gracefully deletes activations, putting it into a shutdown state to /// complete and commit outstanding transactions before deleting it. /// To be called not from within Activation context, so can be awaited. /// </summary> /// <param name="list"></param> /// <returns></returns> internal async Task DeactivateActivations(List<ActivationData> list) { if (list == null || list.Count == 0) return; if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count); List<ActivationData> destroyNow = null; List<MultiTaskCompletionSource> destroyLater = null; int alreadyBeingDestroyed = 0; foreach (var d in list) { var activationData = d; // capture lock (activationData) { if (activationData.State == ActivationState.Valid) { // Change the ActivationData state here, since we're about to give up the lock. activationData.PrepareForDeactivation(); // Don't accept any new messages if (!activationData.IsCurrentlyExecuting) { if (destroyNow == null) { destroyNow = new List<ActivationData>(); } destroyNow.Add(activationData); } else // busy, so destroy later. { if (destroyLater == null) { destroyLater = new List<MultiTaskCompletionSource>(); } var tcs = new MultiTaskCompletionSource(1); destroyLater.Add(tcs); activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs)); } } else { alreadyBeingDestroyed++; } } } int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count; int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count; logger.Info(ErrorCode.Catalog_ShutdownActivations_3, "DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.", list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count); if (destroyNow != null && destroyNow.Count > 0) { await DestroyActivations(destroyNow); } if (destroyLater != null && destroyLater.Count > 0) { await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray()); } } public Task DeactivateAllActivations() { logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations."); var activationsToShutdown = activations.Select(kv => kv.Value).ToList(); return DeactivateActivations(activationsToShutdown); } /// <summary> /// Deletes activation immediately regardless of active transactions etc. /// For use by grain delete, transaction abort, etc. /// </summary> /// <param name="activation"></param> private void DestroyActivationVoid(ActivationData activation) { StartDestroyActivations(new List<ActivationData> { activation }); } private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs) { StartDestroyActivations(new List<ActivationData> { activation }, tcs); } /// <summary> /// Forcibly deletes activations now, without waiting for any outstanding transactions to complete. /// Deletes activation immediately regardless of active transactions etc. /// For use by grain delete, transaction abort, etc. /// </summary> /// <param name="list"></param> /// <returns></returns> // Overall code flow: // Deactivating state was already set before, in the correct context under lock. // that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued) // Wait for all already scheduled ticks to finish // CallGrainDeactivate // when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks): // Unregister in the directory // when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest): // Set Invalid state // UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor). // InvalidateCacheEntry // Reroute pending private Task DestroyActivations(List<ActivationData> list) { var tcs = new MultiTaskCompletionSource(list.Count); StartDestroyActivations(list, tcs); return tcs.Task; } private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null) { int number = destroyActivationsNumber; destroyActivationsNumber++; try { logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count); // step 1 - WaitForAllTimersToFinish var tasks1 = new List<Task>(); foreach (var activation in list) { tasks1.Add(activation.WaitForAllTimersToFinish()); } try { await Task.WhenAll(tasks1); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc); } // step 2 - CallGrainDeactivate var tasks2 = new List<Tuple<Task, ActivationData>>(); foreach (var activation in list) { var activationData = activation; // Capture loop variable var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData)); tasks2.Add(new Tuple<Task, ActivationData>(task, activationData)); } var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>(); asyncQueue.Queue(tasks2, tupleList => { FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs); GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe. }); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc); } } private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs) { try { //logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count); // step 3 - UnregisterManyAsync try { await scheduler.RunOrQueueTask(() => directory.UnregisterManyAsync(list.Select(d => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList()), SchedulingContext); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc); } // step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate foreach (var activationData in list) { try { lock (activationData) { activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished } UnregisterMessageTarget(activationData); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc); } try { // IMPORTANT: no more awaits and .Ignore after that point. // Just use this opportunity to invalidate local Cache Entry as well. // If this silo is not the grain directory partition for this grain, it may have it in its cache. directory.InvalidateCacheEntry(activationData.Address); RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation"); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc); } } // step 5 - Resolve any waiting TaskCompletionSource if (tcs != null) { tcs.SetMultipleResults(list.Count); } logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count); }catch (Exception exc) { logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc); } } private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { lock (activation) { List<Message> msgs = activation.DequeueAllWaitingMessages(); if (msgs == null || msgs.Count <= 0) return; if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation)); dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc); } } private async Task CallGrainActivate(ActivationData activation) { var grainTypeName = activation.GrainInstanceType.FullName; // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName); // Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function try { await activation.GrainInstance.OnActivateAsync(); if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName); lock (activation) { if (activation.State == ActivationState.Activating) { activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished } if (!activation.IsCurrentlyExecuting) { activation.RunOnInactive(); } // Run message pump to see if there is a new request is queued to be processed dispatcher.RunMessagePump(activation); } } catch (Exception exc) { logger.Error(ErrorCode.Catalog_ErrorCallingActivate, string.Format("Error calling grain's AsyncActivate method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc); activation.SetState(ActivationState.Invalid); // Mark this activation as unusable activationsFailedToActivate.Increment(); throw; } } private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation) { try { var grainTypeName = activation.GrainInstanceType.FullName; // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName); // Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function try { // just check in case this activation data is already Invalid or not here at all. ActivationData ignore; if (TryGetActivationData(activation.ActivationId, out ignore) && activation.State == ActivationState.Deactivating) { await activation.GrainInstance.OnDeactivateAsync(); } if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName); } catch (Exception exc) { logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate, string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc); } if (activation.IsUsingStreams) { try { await activation.DeactivateStreamResources(); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc); } } } catch(Exception exc) { logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc); } return activation; } private async Task RegisterActivationInGrainDirectory(ActivationAddress address, bool singleActivationMode) { if (singleActivationMode) { ActivationAddress returnedAddress = await scheduler.RunOrQueueTask(() => directory.RegisterSingleActivationAsync(address), this.SchedulingContext); if (address.Equals(returnedAddress)) return; SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain); var dae = new DuplicateActivationException { ActivationToUse = returnedAddress, PrimaryDirectoryForGrain = primaryDirectoryForGrain }; throw dae; } await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address), this.SchedulingContext); } #endregion #region Activations - private /// <summary> /// Invoke the activate method on a newly created activation /// </summary> /// <param name="activation"></param> /// <returns></returns> private Task InvokeActivate(ActivationData activation) { // NOTE: This should only be called with the correct schedulering context for the activation to be invoked. lock (activation) { activation.SetState(ActivationState.Activating); } return scheduler.QueueTask(() => CallGrainActivate(activation), new SchedulingContext(activation)); // Target grain's scheduler context); // ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest } #endregion #region IPlacementContext public TraceLogger Logger { get { return logger; } } public bool FastLookup(GrainId grain, out List<ActivationAddress> addresses) { return directory.LocalLookup(grain, out addresses) && addresses != null && addresses.Count > 0; // NOTE: only check with the local directory cache. // DO NOT check in the local activations TargetDirectory!!! // The only source of truth about which activation should be legit to is the state of the ditributed directory. // Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth"). // If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it, // thus volaiting the single-activation semantics and not converging even eventualy! } public Task<List<ActivationAddress>> FullLookup(GrainId grain) { return scheduler.RunOrQueueTask(() => directory.FullLookup(grain), this.SchedulingContext); } public bool LocalLookup(GrainId grain, out List<ActivationData> addresses) { addresses = activations.FindTargets(grain); return addresses != null; } public List<SiloAddress> AllActiveSilos { get { var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList(); if (result.Count > 0) return result; logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty"); return new List<SiloAddress> { LocalSilo }; } } #endregion #region Implementation of ICatalog public Task CreateSystemGrain(GrainId grainId, string grainType) { ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId); Task activatedPromise; GetOrCreateActivation(target, true, grainType, null, out activatedPromise); return activatedPromise ?? TaskDone.Done; } public Task DeleteActivations(List<ActivationAddress> addresses) { return DestroyActivations(TryGetActivationDatas(addresses)); } private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses) { var datas = new List<ActivationData>(addresses.Count); foreach (var activationAddress in addresses) { ActivationData data; if (TryGetActivationData(activationAddress.Activation, out data)) datas.Add(data); } return datas; } #endregion #region Implementation of ISiloStatusListener public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // ignore joining events and also events on myself. if (updatedSilo.Equals(LocalSilo)) return; // We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states, // since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses, // thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified. // We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well. if (!status.IsTerminating()) return; var activationsToShutdown = new List<ActivationData>(); try { // scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner. lock (activations) { foreach (var activation in activations) { try { var activationData = activation.Value; if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue; lock (activationData) { // adapted from InsideGarinClient.DeactivateOnIdle(). activationData.ResetKeepAliveRequest(); activationsToShutdown.Add(activationData); } } catch (Exception exc) { logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception, String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc); } } } logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification, String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.", activationsToShutdown.Count, updatedSilo.ToStringWithHashCode())); } finally { // outside the lock. if (activationsToShutdown.Count > 0) { DeactivateActivations(activationsToShutdown).Ignore(); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial // processing queue, and using just the concurrent scheduler with a specified // MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across // a bunch of tasks, parallel loops, dataflow blocks, etc. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Threading.Tasks { /// <summary> /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair { /// <summary>A processing mode to denote what kinds of tasks are currently being processed on this thread.</summary> private readonly ThreadLocal<ProcessingMode> m_threadProcessingMode = new ThreadLocal<ProcessingMode>(); /// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary> private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; /// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary> private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; /// <summary>The underlying task scheduler to which all work should be scheduled.</summary> private readonly TaskScheduler m_underlyingTaskScheduler; /// <summary> /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, /// since exlusive tasks are inherently limited to 1. /// </summary> private readonly int m_maxConcurrencyLevel; /// <summary>The maximum number of tasks we can process before recyling our runner tasks.</summary> private readonly int m_maxItemsPerTask; /// <summary> /// If positive, it represents the number of concurrently running concurrent tasks. /// If negative, it means an exclusive task has been scheduled. /// If 0, nothing has been scheduled. /// </summary> private int m_processingCount; /// <summary>Completion state for a task representing the completion of this pair.</summary> /// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks> private CompletionState m_completionState; /// <summary>A constant value used to signal unlimited processing.</summary> private const int UNLIMITED_PROCESSING = -1; /// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary> private const int EXCLUSIVE_PROCESSING_SENTINEL = -1; /// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary> private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary> private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// <summary>Gets the sync obj used to protect all state on this instance.</summary> private readonly Lock ValueLock = new Lock(); /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum /// concurrency level and a maximum number of scheduled tasks that may be processed as a unit. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> /// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); // Store configuration m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; // Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level int mcl = taskScheduler.MaximumConcurrencyLevel; if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl; // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue; if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } /// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary> /// <remarks> /// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/> /// will be relied on for notification of all processing being completed. /// </remarks> public void Complete() { using (LockHolder.Hold(ValueLock)) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized().Task; } } /// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); } /// <summary>Gets whether completion has been requested.</summary> private bool CompletionRequested { // ValueLock not needed, but it's ok if it's held get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); } } /// <summary>Sets that completion has been requested.</summary> private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; } /// <summary> /// Cleans up state if and only if there's no processing currently happening /// and no more to be done later. /// </summary> private void CleanupStateIfCompletingAndQuiesced() { ContractAssertMonitorStatus(ValueLock, held: true); if (ReadyToComplete) CompleteTaskAsync(); } /// <summary>Gets whether the pair is ready to complete.</summary> private bool ReadyToComplete { get { ContractAssertMonitorStatus(ValueLock, held: true); // We can only complete if completion has been requested and no processing is currently happening. if (!CompletionRequested || m_processingCount != 0) return false; // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } /// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Debug.Assert(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context var cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); var exceptions = localCs.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localCs.TrySetException(exceptions) : localCs.TrySetResult(default(VoidTaskResult)); Debug.Assert(success, "Expected to complete completion task."); }, cs); } } /// <summary>Initiatites scheduler shutdown due to a worker task faulting..</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Debug.Assert(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); if (cs.m_exceptions == null) cs.m_exceptions = new LowLevelListWithIList<Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that may run concurrently with other tasks on this pair. /// </summary> public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that must run exclusively with regards to other tasks on this pair. /// </summary> public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } } /// <summary>Notifies the pair that new work has arrived to be processed.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <remarks>Must only be called while holding the lock.</remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary(bool fairly = false) { ContractAssertMonitorStatus(ValueLock, held: true); // If the current processing count is >= 0, we can potentially launch further processing. if (m_processingCount >= 0) { // We snap whether there are any exclusive tasks or concurrent tasks waiting. // (We grab the concurrent count below only once we know we need it.) // With processing happening concurrent to this operation, this data may // immediately be out of date, but it can only go from non-empty // to empty and not the other way around. As such, this is safe, // as worst case is we'll schedule an extra task when we didn't // otherwise need to, and we'll just eat its overhead. bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; // If there's no processing currently happening but there are waiting exclusive tasks, // let's start processing those exclusive tasks. Task processingTask = null; if (m_processingCount == 0 && exclusiveTasksAreWaiting) { // Launch exclusive task processing m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1 try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. // Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask. } catch { m_processingCount = 0; FaultWithTask(processingTask); } } // If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum // concurrency level for processing, let's start processing more concurrent tasks. else { int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count; if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel) { // Launch concurrent task processing, up to the allowed limit for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i) { ++m_processingCount; try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch { --m_processingCount; FaultWithTask(processingTask); } } } } // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary> /// Processes exclusive tasks serially until either there are no more to process /// or we've reached our user-specified maximum limit. /// </summary> private void ProcessExclusiveTasks() { Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); Debug.Assert(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing exclusive tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.NotCurrentlyProcessing, "This thread should not yet be involved in this pair's processing."); m_threadProcessingMode.Value = ProcessingMode.ProcessingExclusiveTask; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available exclusive task. If we can't find one, bail. Task exclusiveTask; if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask); } } finally { // We're no longer processing exclusive tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; using (LockHolder.Hold(ValueLock)) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Processes concurrent tasks serially until either there are no more to process, /// we've reached our user-specified maximum limit, or exclusive tasks have arrived. /// </summary> private void ProcessConcurrentTasks() { Debug.Assert(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing concurrent tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.NotCurrentlyProcessing, "This thread should not yet be involved in this pair's processing."); m_threadProcessingMode.Value = ProcessingMode.ProcessingConcurrentTasks; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available concurrent task. If we can't find one, bail. Task concurrentTask; if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask); // Now check to see if exclusive tasks have arrived; if any have, they take priority // so we'll bail out here. Note that we could have checked this condition // in the for loop's condition, but that could lead to extra overhead // in the case where a concurrent task arrives, this task is launched, and then // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent // race here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } } finally { // We're no longer processing concurrent tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; using (LockHolder.Hold(ValueLock)) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Holder for lazily-initialized state about the completion of a scheduler pair. /// Completion is only triggered either by rare exceptional conditions or by /// the user calling Complete, and as such we only lazily initialize this /// state in one of those conditions or if the user explicitly asks for /// the Completion. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class CompletionState : TaskCompletionSource<VoidTaskResult> { /// <summary>Whether the scheduler has had completion requested.</summary> /// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks> internal bool m_completionRequested; /// <summary>Whether completion processing has been queued.</summary> internal bool m_completionQueued; /// <summary>Unrecoverable exceptions incurred while processing.</summary> internal LowLevelListWithIList<Exception> m_exceptions; } /// <summary> /// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair. /// </summary> [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { /// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary> private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim); /// <summary>The parent pair.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int m_maxConcurrencyLevel; /// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary> private readonly ProcessingMode m_processingMode; /// <summary>Gets the queue of tasks for this scheduler.</summary> internal readonly IProducerConsumerQueue<Task> m_tasks; /// <summary>Initializes the scheduler.</summary> /// <param name="pair">The parent pair.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param> /// <param name="processingMode">The processing mode of this scheduler.</param> internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { Debug.Assert(pair != null, "Scheduler must be associated with a valid pair."); Debug.Assert(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Debug.Assert( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ? (IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() : (IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>(); } /// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary> public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected internal override void QueueTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); using (LockHolder.Hold(m_pair.ValueLock)) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().ToString()); // Queue the task, and then let the pair know that more work is now available to be scheduled m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> internal void ExecuteTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } /// <summary>Tries to execute the task synchronously on this scheduler.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: // a) we don't need to be exact... a Complete call could come in later in the function anyway // b) this is only a fast path escape hatch. To actually inline the task, // we need to be inside of an already executing task, and in such a case, // while completion may have been requested, we can't have shutdown yet. if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false; // We know the implementation of the default scheduler and how it will behave. // As it's the most common underlying scheduler, we optimize for it. bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; // If we're targeting the default scheduler and taskWasPreviouslyQueued is true, // we know that the default scheduler will only allow it to be inlined // if we're on a thread pool thread (but it won't always allow it in that case, // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. if (isDefaultScheduler && taskWasPreviouslyQueued && !ThreadPool.IsThreadPoolThread) { return false; } else { // If a task is already running on this thread, allow inline execution to proceed. // If there's already a task from this scheduler running on the current thread, we know it's safe // to run this task, in effect temporarily taking that task's count allocation. if (m_pair.m_threadProcessingMode.Value == m_processingMode) { // If we're targeting the default scheduler and taskWasPreviouslyQueued is false, // we know the default scheduler will allow it, so we can just execute it here. // Otherwise, delegate to the target scheduler's inlining. return (isDefaultScheduler && !taskWasPreviouslyQueued) ? TryExecuteTask(task) : TryExecuteTaskInlineOnTargetScheduler(task); } } // We're not in the context of a task already executing on this scheduler. Bail. return false; } /// <summary> /// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler, /// which we can't call directly on the underlying scheduler. /// </summary> /// <param name="task">The task to execute inline if possible.</param> /// <returns>true if the task was inlined successfully; otherwise, false.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { // We'd like to simply call TryExecuteTaskInline here, but we can't. // As there's no built-in API for this, a workaround is to create a new task that, // when executed, will simply call TryExecuteTask to run the real task, and then // we run our new shim task synchronously on the target scheduler. If all goes well, // our synchronous invocation will succeed in running the shim task on the current thread, // which will in turn run the real task on the current thread. If the scheduler // doesn't allow that execution, RunSynchronously will block until the underlying scheduler // is able to invoke the task, which might account for an additional but unavoidable delay. // Once it's done, we can return whether the task executed by returning the // shim task's Result, which is in turn the result of TryExecuteTask. var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task)); try { t.RunSynchronously(m_pair.m_underlyingTaskScheduler); return t.Result; } catch { Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } } /// <summary>Shim used to invoke this.TryExecuteTask(task).</summary> /// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param> /// <returns>true if the task was successfully inlined; otherwise, false.</returns> /// <remarks> /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; return tuple.Item1.TryExecuteTask(tuple.Item2); } /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int CountForDebugger { get { return m_tasks.Count; } } /// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary> private sealed class DebugView { /// <summary>The scheduler being debugged.</summary> private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler being debugged.</param> public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { Debug.Assert(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } /// <summary>Gets this pair's maximum allowed concurrency level.</summary> public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } } /// <summary>Gets the scheduler pair with which this scheduler is associated.</summary> public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } } } } /// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary> private sealed class DebugView { /// <summary>The pair being debugged.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>Initializes the debug view.</summary> /// <param name="pair">The pair being debugged.</param> public DebugView(ConcurrentExclusiveSchedulerPair pair) { Debug.Assert(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } /// <summary>Gets a representation of the execution state of the pair.</summary> public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks currently being executed.</summary> public int CurrentlyExecutingTaskCount { get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; } } /// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary> public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } } } /// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary> /// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks> private ProcessingMode ModeForDebugger { get { // If our completion task is done, so are we. if (m_completionState != null && m_completionState.Task.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. var mode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask; if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks; if (CompletionRequested) mode |= ProcessingMode.Completing; return mode; } } /// <summary>Asserts that a given Lock object is either held or not held.</summary> /// <param name="syncObj">The Lock object to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> [Conditional("DEBUG")] private static void ContractAssertMonitorStatus(Lock syncObj, bool held) { Debug.Assert(syncObj != null, "The Lock object to check must be provided."); Debug.Assert(syncObj.IsAcquired == held, "The locking scheme was not correctly followed."); } /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> /// These options should be used for all tasks that have the potential to run user code or /// that are repeatedly spawned and thus need a modicum of fair treatment. /// </remarks> /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions options = TaskCreationOptions.DenyChildAttach; if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary> [Flags] internal enum ProcessingMode : byte { /// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary> NotCurrentlyProcessing = 0x0, /// <summary>The scheduler pair has queued processing for exclusive tasks.</summary> ProcessingExclusiveTask = 0x1, /// <summary>The scheduler pair has queued processing for concurrent tasks.</summary> ProcessingConcurrentTasks = 0x2, /// <summary>Completion has been requested.</summary> Completing = 0x4, /// <summary>The scheduler pair is finished processing.</summary> Completed = 0x8 } } }
// <copyright file="UserLUTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// LU factorization tests for a user matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class UserLUTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorLU = matrixI.LU(); // Check lower triangular part. var matrixL = factorLU.L; Assert.AreEqual(matrixI.RowCount, matrixL.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount); for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < matrixL.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixL[i, j]); } } // Check upper triangular part. var matrixU = factorLU.U; Assert.AreEqual(matrixI.RowCount, matrixU.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount); for (var i = 0; i < matrixU.RowCount; i++) { for (var j = 0; j < matrixU.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixU[i, j]); } } } /// <summary> /// LU factorization fails with a non-square matrix. /// </summary> [Test] public void LUFailsWithNonSquareMatrix() { var matrix = new UserDefinedMatrix(3, 2); Assert.That(() => matrix.LU(), Throws.ArgumentException); } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = UserDefinedMatrix.Identity(order); var lu = matrixI.LU(); Assert.AreEqual(Complex.One, lu.Determinant); } /// <summary> /// Can factorize a random square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanFactorizeRandomMatrix(int order) { var matrixX = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var factorLU = matrixX.LU(); var matrixL = factorLU.L; var matrixU = factorLU.U; // Make sure the factors have the right dimensions. Assert.AreEqual(order, matrixL.RowCount); Assert.AreEqual(order, matrixL.ColumnCount); Assert.AreEqual(order, matrixU.RowCount); Assert.AreEqual(order, matrixU.ColumnCount); // Make sure the L factor is lower triangular. for (var i = 0; i < matrixL.RowCount; i++) { Assert.AreEqual(Complex.One, matrixL[i, i]); for (var j = i + 1; j < matrixL.ColumnCount; j++) { Assert.AreEqual(Complex.Zero, matrixL[i, j]); } } // Make sure the U factor is upper triangular. for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < i; j++) { Assert.AreEqual(Complex.Zero, matrixU[i, j]); } } // Make sure the LU factor times it's transpose is the original matrix. var matrixXfromLU = matrixL * matrixU; var permutationInverse = factorLU.P.Inverse(); matrixXfromLU.PermuteRows(permutationInverse); for (var i = 0; i < matrixXfromLU.RowCount; i++) { for (var j = 0; j < matrixXfromLU.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(matrixX[i, j], matrixXfromLU[i, j], 9); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray()); var resultx = factorLU.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixX = factorLU.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray()); var vectorbCopy = vectorb.Clone(); var resultx = new UserDefinedVector(order); factorLU.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix row number.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(order, order); factorLU.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can inverse a matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanInverse(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixAInverse = factorLU.Inverse(); // The inverse dimension is equal A Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount); Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount); var matrixIdentity = matrixA * matrixAInverse; // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Check if multiplication of A and AI produced identity matrix. for (var i = 0; i < matrixIdentity.RowCount; i++) { AssertHelpers.AlmostEqualRelative(matrixIdentity[i, i], Complex.One, 9); } } } }
using System; using System.Runtime.InteropServices; using System.Diagnostics; using DirectShowLib; namespace AgreementTrac { class CCapture : IDisposable { #region Member Fields public IFilterGraph2 m_FilterGraph = null; private ICaptureGraphBuilder2 m_CaptureGraph = null; private string m_sCaptureFile = string.Empty; #endregion #region Constructor/Destructor public CCapture(DsDevice devVideo, DsDevice devAudio) { m_FilterGraph = (IFilterGraph2)new FilterGraph(); m_CaptureGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); SetupGraphForPreview(devVideo, devAudio); } public CCapture(DsDevice devVideo, DsDevice devAudio, string sOutputFilename) { m_FilterGraph = (IFilterGraph2)new FilterGraph(); m_CaptureGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); m_sCaptureFile = sOutputFilename; SetupGraphForCapture(devVideo, devAudio, m_sCaptureFile); } ~CCapture() { Dispose(); } #endregion #region Static Methods public static DsDevice[] GetVideoDevices() { DsDevice[] vidDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); if (vidDevices.Length <= 0) return null; return vidDevices; } public static DsDevice[] GetAudioDevices() { DsDevice[] audDevices = DsDevice.GetDevicesOfCat(FilterCategory.AudioInputDevice); if (audDevices.Length <= 0) return null; return audDevices; } #endregion #region Private Methods private void SetupGraphForPreview(DsDevice videoDevice, DsDevice audioDevice) { Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered SetupGraphForPreview() method."); int hr = 0; string sErrorText = string.Empty; IBaseFilter videoCapFilter = null; IBaseFilter audioCapFilter = null; try { // start building the graph hr = m_CaptureGraph.SetFiltergraph(m_FilterGraph); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); // add the video capture device to the graph hr = m_FilterGraph.AddSourceFilterForMoniker(videoDevice.Mon, null, videoDevice.Name, out videoCapFilter); sErrorText = DsError.GetErrorText(hr); if (hr != 0) { Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tAddSourceFilter failed with message: " + sErrorText); throw new Exception("AddSourceFilterForMoniker() failed with error: " + sErrorText.Trim() + "\r\nVideo source incompatible with graph. Please select a different video device."); } DsError.ThrowExceptionForHR(hr); hr = m_FilterGraph.AddSourceFilterForMoniker(audioDevice.Mon, null, audioDevice.Name, out audioCapFilter); sErrorText = DsError.GetErrorText(hr); if (hr != 0) { Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tAddSourceFilter failed with message: " + sErrorText); throw new Exception("AddSourceFilterForMoniker() failed with error: " + sErrorText.Trim() + "\r\nAudio source incompatible with graph. Please select a different audio device."); } // Used for preview hr = m_CaptureGraph.RenderStream(PinCategory.Preview, MediaType.Video, videoCapFilter, null, null); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); } finally { if (videoCapFilter != null) { hr = Marshal.ReleaseComObject(videoCapFilter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); videoCapFilter = null; } if (audioCapFilter != null) { hr = Marshal.ReleaseComObject(audioCapFilter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); audioCapFilter = null; } } Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting SetupGraphForPreview() method.\r\n"); } private void SetupGraphForCapture(DsDevice video, DsDevice audio, string sOutputFilename) { int hr = 0; string sErrorText = string.Empty; IBaseFilter videoCapFilter = null; IBaseFilter audioCapFilter = null; IBaseFilter asfWriter = null; try { // Instantiate the capture graph m_CaptureGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); // start building the graph hr = m_CaptureGraph.SetFiltergraph(m_FilterGraph); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); // add the video capture device to the graph hr = m_FilterGraph.AddSourceFilterForMoniker(video.Mon, null, video.Name, out videoCapFilter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); hr = m_FilterGraph.AddSourceFilterForMoniker(audio.Mon, null, audio.Name, out audioCapFilter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); // Used for preview //hr = m_CaptureGraph.RenderStream(PinCategory.Preview, MediaType.Video, videoCapFilter, null, null); //sErrorText = DsError.GetErrorText(hr); //DsError.ThrowExceptionForHR(hr); asfWriter = ConfigAsf(m_CaptureGraph, sOutputFilename); hr = m_CaptureGraph.RenderStream(PinCategory.Capture, MediaType.Video, videoCapFilter, null, asfWriter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); hr = m_CaptureGraph.RenderStream(PinCategory.Capture, MediaType.Audio, audioCapFilter, null, asfWriter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); } finally { if (videoCapFilter != null) { hr = Marshal.ReleaseComObject(videoCapFilter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); videoCapFilter = null; } if (audioCapFilter != null) { hr = Marshal.ReleaseComObject(audioCapFilter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); audioCapFilter = null; } if (asfWriter != null) { hr = Marshal.ReleaseComObject(asfWriter); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); asfWriter = null; } } } private IBaseFilter ConfigAsf(ICaptureGraphBuilder2 captureGraph, string sOutputFilename) { IFileSinkFilter pTmpSink = null; IBaseFilter asfWriter = null; int hr = captureGraph.SetOutputFileName(MediaSubType.Asf, sOutputFilename, out asfWriter, out pTmpSink); string sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); try { IConfigAsfWriter lConfig = asfWriter as IConfigAsfWriter; // Following profiles found in C:\Windows\WMSysPr9.prx // Video for LAN, cable modem, or xDSL (100 to 768 Kbps) // Approximately 10MB/min //Guid cat = new Guid(0x045880DC, 0x34B6, 0x4CA9, 0xA3, 0x26, 0x73, 0x55, 0x7E, 0xD1, 0x43, 0xF3); //Video for dial-up modems or LAN (28.8 to 100 Kbps)" // Approximately 1MB/min //guid="{07DF7A25-3FE2-4A5B-8B1E-348B0721CA70}" //Guid cat = new Guid(0x07DF7A25,0x3FE2,0x4A5B,0x8B,0x1E,0x34,0x8B,0x07,0x21,0xCA,0x70); //Video for e-mail and dual-channel ISDN (128 Kbps)" //guid="{D9F3C932-5EA9-4C6D-89B4-2686E515426E}" // Approximately 800KB/min (audio is mono) Guid cat = new Guid(0xD9F3C932, 0x5EA9, 0x4C6D, 0x89, 0xB4, 0x26, 0x86, 0xE5, 0x15, 0x42, 0x6E); hr = lConfig.ConfigureFilterUsingProfileGuid(cat); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); } finally { hr = Marshal.ReleaseComObject(pTmpSink); sErrorText = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); } return asfWriter; } private void CloseInterfaces() { try { int hr = 0; string sErr = string.Empty; if (m_FilterGraph != null) { hr = Marshal.FinalReleaseComObject(m_FilterGraph); sErr = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); m_FilterGraph = null; } if (m_CaptureGraph != null) { hr = Marshal.FinalReleaseComObject(m_CaptureGraph); sErr = DsError.GetErrorText(hr); DsError.ThrowExceptionForHR(hr); m_CaptureGraph = null; } } catch(Exception ex) { System.Diagnostics.Debug.Print(ex.Message); } } #endregion #region IDisposable Members public void Dispose() { GC.SuppressFinalize(this); CloseInterfaces(); } #endregion } }
namespace Epi.Windows.Analysis.Dialogs { partial class GraphDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GraphDialog)); this.comboBoxMainVariable = new System.Windows.Forms.ComboBox(); this.labelXAxisMainVar = new System.Windows.Forms.Label(); this.listBoxVariables = new System.Windows.Forms.ListBox(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.comboBoxGraphType = new System.Windows.Forms.ComboBox(); this.labelGraphType = new System.Windows.Forms.Label(); this.groupBoxXAxis = new System.Windows.Forms.GroupBox(); this.textBoxXAxisLabel = new System.Windows.Forms.TextBox(); this.labelXAxisLabel = new System.Windows.Forms.Label(); this.groupBoxYAxis = new System.Windows.Forms.GroupBox(); this.comboBoxWeightVar = new System.Windows.Forms.ComboBox(); this.comboBoxShowValueOf = new System.Windows.Forms.ComboBox(); this.labelShowValueOf = new System.Windows.Forms.Label(); this.labelWeightVariable = new System.Windows.Forms.Label(); this.textBoxYAxisLabel = new System.Windows.Forms.TextBox(); this.labelYAxis = new System.Windows.Forms.Label(); this.groupBoxSeries = new System.Windows.Forms.GroupBox(); this.labelOneGraphForEachValueOf = new System.Windows.Forms.Label(); this.labelBarOfEachValueOf = new System.Windows.Forms.Label(); this.comboBoxStrataVar = new System.Windows.Forms.ComboBox(); this.comboBoxBarOfEachValueOf = new System.Windows.Forms.ComboBox(); this.labelTitle = new System.Windows.Forms.Label(); this.textBoxTitle = new System.Windows.Forms.TextBox(); this.groupBoxFormat = new System.Windows.Forms.GroupBox(); this.comboBoxDateFormat = new System.Windows.Forms.ComboBox(); this.labelDateFormat = new System.Windows.Forms.Label(); this.groupBoxInterval = new System.Windows.Forms.GroupBox(); this.startDateTime = new System.Windows.Forms.DateTimePicker(); this.labelInterval = new System.Windows.Forms.Label(); this.labelFirstValue = new System.Windows.Forms.Label(); this.comboBoxIntervalType = new System.Windows.Forms.ComboBox(); this.textBoxInterval = new System.Windows.Forms.TextBox(); this.groupBoxXAxis.SuspendLayout(); this.groupBoxYAxis.SuspendLayout(); this.groupBoxSeries.SuspendLayout(); this.groupBoxFormat.SuspendLayout(); this.groupBoxInterval.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // comboBoxMainVariable // this.comboBoxMainVariable.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxMainVariable.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; resources.ApplyResources(this.comboBoxMainVariable, "comboBoxMainVariable"); this.comboBoxMainVariable.Name = "comboBoxMainVariable"; // // labelXAxisMainVar // this.labelXAxisMainVar.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.labelXAxisMainVar, "labelXAxisMainVar"); this.labelXAxisMainVar.Name = "labelXAxisMainVar"; // // listBoxVariables // resources.ApplyResources(this.listBoxVariables, "listBoxVariables"); this.listBoxVariables.Name = "listBoxVariables"; this.listBoxVariables.TabStop = false; this.listBoxVariables.SelectedIndexChanged += new System.EventHandler(this.lbxVariables_SelectedIndexChanged); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // comboBoxGraphType // this.comboBoxGraphType.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxGraphType.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.comboBoxGraphType.Items.AddRange(new object[] { resources.GetString("comboBoxGraphType.Items"), resources.GetString("comboBoxGraphType.Items1"), resources.GetString("comboBoxGraphType.Items2"), resources.GetString("comboBoxGraphType.Items3"), resources.GetString("comboBoxGraphType.Items4"), resources.GetString("comboBoxGraphType.Items5"), resources.GetString("comboBoxGraphType.Items6"), resources.GetString("comboBoxGraphType.Items7")}); resources.ApplyResources(this.comboBoxGraphType, "comboBoxGraphType"); this.comboBoxGraphType.Name = "comboBoxGraphType"; this.comboBoxGraphType.SelectedIndexChanged += new System.EventHandler(this.comboBoxGraphType_SelectedIndexChanged); // // labelGraphType // this.labelGraphType.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.labelGraphType, "labelGraphType"); this.labelGraphType.Name = "labelGraphType"; // // groupBoxXAxis // this.groupBoxXAxis.Controls.Add(this.textBoxXAxisLabel); this.groupBoxXAxis.Controls.Add(this.labelXAxisLabel); this.groupBoxXAxis.Controls.Add(this.comboBoxMainVariable); this.groupBoxXAxis.Controls.Add(this.labelXAxisMainVar); this.groupBoxXAxis.Controls.Add(this.listBoxVariables); resources.ApplyResources(this.groupBoxXAxis, "groupBoxXAxis"); this.groupBoxXAxis.Name = "groupBoxXAxis"; this.groupBoxXAxis.TabStop = false; // // textBoxXAxisLabel // resources.ApplyResources(this.textBoxXAxisLabel, "textBoxXAxisLabel"); this.textBoxXAxisLabel.Name = "textBoxXAxisLabel"; // // labelXAxisLabel // resources.ApplyResources(this.labelXAxisLabel, "labelXAxisLabel"); this.labelXAxisLabel.Name = "labelXAxisLabel"; // // groupBoxYAxis // this.groupBoxYAxis.Controls.Add(this.comboBoxWeightVar); this.groupBoxYAxis.Controls.Add(this.comboBoxShowValueOf); this.groupBoxYAxis.Controls.Add(this.labelShowValueOf); this.groupBoxYAxis.Controls.Add(this.labelWeightVariable); this.groupBoxYAxis.Controls.Add(this.textBoxYAxisLabel); this.groupBoxYAxis.Controls.Add(this.labelYAxis); resources.ApplyResources(this.groupBoxYAxis, "groupBoxYAxis"); this.groupBoxYAxis.Name = "groupBoxYAxis"; this.groupBoxYAxis.TabStop = false; // // comboBoxWeightVar // this.comboBoxWeightVar.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxWeightVar.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; resources.ApplyResources(this.comboBoxWeightVar, "comboBoxWeightVar"); this.comboBoxWeightVar.Name = "comboBoxWeightVar"; // // comboBoxShowValueOf // this.comboBoxShowValueOf.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxShowValueOf.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.comboBoxShowValueOf.Items.AddRange(new object[] { resources.GetString("comboBoxShowValueOf.Items"), resources.GetString("comboBoxShowValueOf.Items1"), resources.GetString("comboBoxShowValueOf.Items2"), resources.GetString("comboBoxShowValueOf.Items3"), resources.GetString("comboBoxShowValueOf.Items4"), resources.GetString("comboBoxShowValueOf.Items5"), resources.GetString("comboBoxShowValueOf.Items6")}); resources.ApplyResources(this.comboBoxShowValueOf, "comboBoxShowValueOf"); this.comboBoxShowValueOf.Name = "comboBoxShowValueOf"; // // labelShowValueOf // resources.ApplyResources(this.labelShowValueOf, "labelShowValueOf"); this.labelShowValueOf.Name = "labelShowValueOf"; // // labelWeightVariable // resources.ApplyResources(this.labelWeightVariable, "labelWeightVariable"); this.labelWeightVariable.Name = "labelWeightVariable"; // // textBoxYAxisLabel // resources.ApplyResources(this.textBoxYAxisLabel, "textBoxYAxisLabel"); this.textBoxYAxisLabel.Name = "textBoxYAxisLabel"; // // labelYAxis // resources.ApplyResources(this.labelYAxis, "labelYAxis"); this.labelYAxis.Name = "labelYAxis"; // // groupBoxSeries // this.groupBoxSeries.Controls.Add(this.labelOneGraphForEachValueOf); this.groupBoxSeries.Controls.Add(this.labelBarOfEachValueOf); this.groupBoxSeries.Controls.Add(this.comboBoxStrataVar); this.groupBoxSeries.Controls.Add(this.comboBoxBarOfEachValueOf); resources.ApplyResources(this.groupBoxSeries, "groupBoxSeries"); this.groupBoxSeries.Name = "groupBoxSeries"; this.groupBoxSeries.TabStop = false; // // labelOneGraphForEachValueOf // resources.ApplyResources(this.labelOneGraphForEachValueOf, "labelOneGraphForEachValueOf"); this.labelOneGraphForEachValueOf.Name = "labelOneGraphForEachValueOf"; // // labelBarOfEachValueOf // resources.ApplyResources(this.labelBarOfEachValueOf, "labelBarOfEachValueOf"); this.labelBarOfEachValueOf.Name = "labelBarOfEachValueOf"; // // comboBoxStrataVar // this.comboBoxStrataVar.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxStrataVar.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; resources.ApplyResources(this.comboBoxStrataVar, "comboBoxStrataVar"); this.comboBoxStrataVar.Name = "comboBoxStrataVar"; // // comboBoxBarOfEachValueOf // this.comboBoxBarOfEachValueOf.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxBarOfEachValueOf.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; resources.ApplyResources(this.comboBoxBarOfEachValueOf, "comboBoxBarOfEachValueOf"); this.comboBoxBarOfEachValueOf.Name = "comboBoxBarOfEachValueOf"; // // labelTitle // this.labelTitle.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.labelTitle, "labelTitle"); this.labelTitle.Name = "labelTitle"; // // textBoxTitle // resources.ApplyResources(this.textBoxTitle, "textBoxTitle"); this.textBoxTitle.Name = "textBoxTitle"; // // groupBoxFormat // this.groupBoxFormat.Controls.Add(this.comboBoxDateFormat); this.groupBoxFormat.Controls.Add(this.labelDateFormat); resources.ApplyResources(this.groupBoxFormat, "groupBoxFormat"); this.groupBoxFormat.Name = "groupBoxFormat"; this.groupBoxFormat.TabStop = false; // // comboBoxDateFormat // this.comboBoxDateFormat.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxDateFormat.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.comboBoxDateFormat.Items.AddRange(new object[] { resources.GetString("comboBoxDateFormat.Items"), resources.GetString("comboBoxDateFormat.Items1"), resources.GetString("comboBoxDateFormat.Items2"), resources.GetString("comboBoxDateFormat.Items3"), resources.GetString("comboBoxDateFormat.Items4"), resources.GetString("comboBoxDateFormat.Items5"), resources.GetString("comboBoxDateFormat.Items6"), resources.GetString("comboBoxDateFormat.Items7"), resources.GetString("comboBoxDateFormat.Items8")}); resources.ApplyResources(this.comboBoxDateFormat, "comboBoxDateFormat"); this.comboBoxDateFormat.Name = "comboBoxDateFormat"; // // labelDateFormat // resources.ApplyResources(this.labelDateFormat, "labelDateFormat"); this.labelDateFormat.Name = "labelDateFormat"; // // groupBoxInterval // this.groupBoxInterval.Controls.Add(this.startDateTime); this.groupBoxInterval.Controls.Add(this.labelInterval); this.groupBoxInterval.Controls.Add(this.labelFirstValue); this.groupBoxInterval.Controls.Add(this.comboBoxIntervalType); this.groupBoxInterval.Controls.Add(this.textBoxInterval); resources.ApplyResources(this.groupBoxInterval, "groupBoxInterval"); this.groupBoxInterval.Name = "groupBoxInterval"; this.groupBoxInterval.TabStop = false; // // startDateTime // this.startDateTime.Checked = false; resources.ApplyResources(this.startDateTime, "startDateTime"); this.startDateTime.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.startDateTime.Name = "startDateTime"; this.startDateTime.ShowCheckBox = true; this.startDateTime.ValueChanged += new System.EventHandler(this.startDateTime_ValueChanged); // // labelInterval // resources.ApplyResources(this.labelInterval, "labelInterval"); this.labelInterval.Name = "labelInterval"; // // labelFirstValue // resources.ApplyResources(this.labelFirstValue, "labelFirstValue"); this.labelFirstValue.Name = "labelFirstValue"; // // comboBoxIntervalType // this.comboBoxIntervalType.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxIntervalType.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; resources.ApplyResources(this.comboBoxIntervalType, "comboBoxIntervalType"); this.comboBoxIntervalType.Items.AddRange(new object[] { resources.GetString("comboBoxIntervalType.Items"), resources.GetString("comboBoxIntervalType.Items1"), resources.GetString("comboBoxIntervalType.Items2"), resources.GetString("comboBoxIntervalType.Items3"), resources.GetString("comboBoxIntervalType.Items4"), resources.GetString("comboBoxIntervalType.Items5"), resources.GetString("comboBoxIntervalType.Items6"), resources.GetString("comboBoxIntervalType.Items7"), resources.GetString("comboBoxIntervalType.Items8")}); this.comboBoxIntervalType.Name = "comboBoxIntervalType"; // // textBoxInterval // resources.ApplyResources(this.textBoxInterval, "textBoxInterval"); this.textBoxInterval.Name = "textBoxInterval"; // // GraphDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.groupBoxInterval); this.Controls.Add(this.groupBoxFormat); this.Controls.Add(this.textBoxTitle); this.Controls.Add(this.labelTitle); this.Controls.Add(this.groupBoxSeries); this.Controls.Add(this.groupBoxYAxis); this.Controls.Add(this.groupBoxXAxis); this.Controls.Add(this.labelGraphType); this.Controls.Add(this.comboBoxGraphType); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnClear); this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "GraphDialog"; this.Load += new System.EventHandler(this.ListDialog_Load); this.groupBoxXAxis.ResumeLayout(false); this.groupBoxXAxis.PerformLayout(); this.groupBoxYAxis.ResumeLayout(false); this.groupBoxYAxis.PerformLayout(); this.groupBoxSeries.ResumeLayout(false); this.groupBoxSeries.PerformLayout(); this.groupBoxFormat.ResumeLayout(false); this.groupBoxFormat.PerformLayout(); this.groupBoxInterval.ResumeLayout(false); this.groupBoxInterval.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.ComboBox comboBoxMainVariable; private System.Windows.Forms.Label labelXAxisMainVar; private System.Windows.Forms.ListBox listBoxVariables; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.ComboBox comboBoxGraphType; private System.Windows.Forms.Label labelGraphType; private System.Windows.Forms.GroupBox groupBoxXAxis; private System.Windows.Forms.TextBox textBoxXAxisLabel; private System.Windows.Forms.Label labelXAxisLabel; private System.Windows.Forms.GroupBox groupBoxYAxis; private System.Windows.Forms.TextBox textBoxYAxisLabel; private System.Windows.Forms.Label labelYAxis; private System.Windows.Forms.GroupBox groupBoxSeries; private System.Windows.Forms.Label labelTitle; private System.Windows.Forms.TextBox textBoxTitle; private System.Windows.Forms.ComboBox comboBoxWeightVar; private System.Windows.Forms.ComboBox comboBoxShowValueOf; private System.Windows.Forms.Label labelShowValueOf; private System.Windows.Forms.Label labelWeightVariable; private System.Windows.Forms.Label labelOneGraphForEachValueOf; private System.Windows.Forms.Label labelBarOfEachValueOf; private System.Windows.Forms.ComboBox comboBoxStrataVar; private System.Windows.Forms.ComboBox comboBoxBarOfEachValueOf; private System.Windows.Forms.GroupBox groupBoxFormat; private System.Windows.Forms.ComboBox comboBoxDateFormat; private System.Windows.Forms.Label labelDateFormat; private System.Windows.Forms.GroupBox groupBoxInterval; private System.Windows.Forms.Label labelInterval; private System.Windows.Forms.Label labelFirstValue; private System.Windows.Forms.ComboBox comboBoxIntervalType; private System.Windows.Forms.TextBox textBoxInterval; private System.Windows.Forms.DateTimePicker startDateTime; } }
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using CodeSmith.Engine; using CslaGenerator.Controls; using CslaGenerator.Metadata; namespace CslaGenerator.CodeGen { public class AdvancedGenerator : CodeGeneratorBase, ICodeGenerator { #region Service Method public class ServiceMethod { public string DataPortalMethod { get; set; } public string MethodHeader { get; set; } public ServiceMethod(string dataPortalMethod, string methodHeader) { DataPortalMethod = dataPortalMethod; MethodHeader = methodHeader; } } #endregion #region Private Fields private readonly Dictionary<string, bool?> _fileSuccess = new Dictionary<string, bool?>(); private List<ServiceMethod> _methodList; private readonly string _templatesDirectory = string.Empty; private bool _abortRequested; private string _fullTemplatesPath; private bool _generateDatabaseClass; private readonly GenerationReportCollection _errorReport = new GenerationReportCollection(); private readonly GenerationReportCollection _warningReport = new GenerationReportCollection(); private readonly List<string> _infoReport = new List<string>(); private int _objFailed; private int _objSuccess; private int _objectWarnings; private int _sprocFailed; private int _sprocWarnings; private int _sprocSuccess; private int _retryCount; private Hashtable _templates = new Hashtable(); private string _codeEncoding; private string _sprocEncoding; private CslaGeneratorUnit _unit; private bool _businessError; private bool _currentSprocError; #endregion #region ICodeGenerator Members public string TargetDirectory { get; set; } public GenerationReportCollection ErrorReport { get { return _errorReport; } } public GenerationReportCollection WarningReport { get { return _warningReport; } } public List<string> InfoReport { get { return _infoReport; } } public void Abort() { _abortRequested = true; } public void GenerateProject(CslaGeneratorUnit unit) { _unit = unit; _unit.GenerationTimer.Restart(); CslaTemplateHelperCS.PrimaryKeys.ClearCache(); CslaObjectInfo objInfo = null; _objFailed = 0; _objSuccess = 0; _sprocFailed = 0; _sprocSuccess = 0; _retryCount = 0; OutputWindow.Current.ClearOutput(); var generationParams = unit.GenerationParams; _generateDatabaseClass = generationParams.GenerateDatabaseClass; _abortRequested = false; _fullTemplatesPath += _templatesDirectory + "CSLA40"; if (generationParams.TargetIsCsla4DAL) _fullTemplatesPath += "DAL"; _fullTemplatesPath += @"\"; _templates = new Hashtable(); //to recompile templates in case they changed. //This is just in case users add/remove objects while generating... var list = unit.CslaObjects.Where(t => t.Generate).ToList(); /*for (var i = 0; i < unit.CslaObjects.Count; i++) { if (unit.CslaObjects[i].Generate) list.Add(unit.CslaObjects[i]); }*/ var generalValidation = GeneralValidation(GenerationStep.Business); if (_abortRequested) OnGenerationInformation(Environment.NewLine + "* * * * Code Generation Cancelled!"); if (generationParams.GenerateDalInterface) generalValidation &= GeneralValidation(GenerationStep.DalInterface); if (_abortRequested) OnGenerationInformation(Environment.NewLine + "* * * * Code Generation Cancelled!"); if (generationParams.GenerateDalObject) generalValidation &= GeneralValidation(GenerationStep.DalObject); if (_abortRequested) OnGenerationInformation(Environment.NewLine + "* * * * Code Generation Cancelled!"); if (!generalValidation) { _unit.GenerationTimer.Stop(); OnFinalized(false); return; } // add blank line OnGenerationInformation(""); foreach (var info in list) { _businessError = false; if (objInfo == null) objInfo = info; if (_abortRequested) break; OnStep(info.ObjectName); // Stored Procedures if (generationParams.GenerateSprocs && info.GenerateSprocs) { try { if (generationParams.OneSpFilePerObject) { GenerateAllSprocsFile(info, TargetDirectory); if (_abortRequested) break; } else { GenerateSelectProcedure(info, TargetDirectory); if (_abortRequested) break; if (NeedsDbInsUpdDel(info)) { GenerateInsertProcedure(info, TargetDirectory); if (_abortRequested) break; GenerateDeleteProcedure(info, TargetDirectory); if (_abortRequested) break; GenerateUpdateProcedure(info, TargetDirectory); if (_abortRequested) break; } } } catch (Exception ex) { var generationErrors = new StringBuilder(); generationErrors.AppendLine("* * * Error:"); generationErrors.AppendFormat("SProc {0} failed to generate:", info.ObjectName); generationErrors.AppendLine(); generationErrors.AppendLine(ex.Message); if (ex.InnerException != null) { generationErrors.AppendLine(ex.InnerException.Message); generationErrors.AppendLine("Stack Trace"); generationErrors.AppendLine(ex.InnerException.StackTrace); } OnGenerationInformation(generationErrors.ToString()); } } // Business Objects try { GenerateObject(info); } catch (Exception ex) { _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = info.ObjectName, ObjectType = info.ObjectType.ToString(), Message = ex.Message, FileName = "unknown (Business)" }); var sb = new StringBuilder(); sb.AppendLine("* * * Error:"); sb.AppendFormat("Business Object: {0} failed to generate:", info.ObjectName); sb.AppendLine(); sb.AppendLine(ex.Message); OnGenerationInformation(sb.ToString()); } if (_abortRequested) break; if (generationParams.GenerateDalInterface && generationParams.GenerateDTO && info.GenerateDataAccessRegion && (CslaTemplateHelperCS.IsObjectType(info.ObjectType) || info.ObjectType == CslaObjectType.NameValueList)) { // DTO goes into DAL Interface try { DoGenerateDal(info, GenerationStep.DalInterfaceDto); } catch (Exception ex) { _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = info.ObjectName, ObjectType = info.ObjectType.ToString(), Message = ex.Message, FileName = "unknown (DTO for DAL interface)" }); var sb = new StringBuilder(); sb.AppendLine("* * * Error:"); sb.AppendFormat("DAL Interface: DTO {0} failed to generate:", info.ObjectName); sb.AppendLine(); sb.AppendLine(ex.Message); OnGenerationInformation(sb.ToString()); } if (_abortRequested) break; } if (((generationParams.GenerateDalInterface || generationParams.GenerateDalObject) && info.GenerateDataAccessRegion) && ((NeedsDbFetch(info) && HasFetchCriteria(info)) || (NeedsDbInsUpdDel(info) && HasInsUpdDelcriteria(info)))) { // DAL Interface try { DoGenerateDalInterface(info); } catch (Exception ex) { _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = info.ObjectName, ObjectType = info.ObjectType.ToString(), Message = ex.Message, FileName = "unknown (DAL interface)" }); var sb = new StringBuilder(); sb.AppendLine("* * * Error:"); sb.AppendFormat("DAL Interface: {0} failed to generate:", info.ObjectName); sb.AppendLine(); sb.AppendLine(ex.Message); OnGenerationInformation(sb.ToString()); } if (_abortRequested) break; // DAL Objects try { DoGenerateDalObject(info); } catch (Exception ex) { _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = info.ObjectName, ObjectType = info.ObjectType.ToString(), Message = ex.Message, FileName = "unknown (DAL)" }); var sb = new StringBuilder(); sb.AppendLine("* * * Error:"); sb.AppendFormat("DAL Object: {0} failed to generate:", info.ObjectName); sb.AppendLine(); sb.AppendLine(ex.Message); OnGenerationInformation(sb.ToString()); } if (_abortRequested) break; } } var dalName = CslaTemplateHelperCS.GetDalName(_unit); // Infrastructure classes if (_generateDatabaseClass && generationParams.TargetIsCsla4) { const GenerationStep step = GenerationStep.Business; GenerateUtilityFile("Database" + _unit.GenerationParams.DatabaseConnection, false, "Database", step); } else { _fileSuccess.Add("Database", null); } GenerateUtilityFile("DataPortalHookArgs", false, "DataPortalHookArgs", GenerationStep.Business); if (generationParams.GenerateDalInterface) { GenerateUtilityFile("IDalManager" + dalName, false, "IDalManager", GenerationStep.DalInterface); GenerateUtilityFile("DalFactory" + dalName, false, "DalFactory", GenerationStep.DalInterface); GenerateUtilityFile("DataNotFoundException", false, "DataNotFoundException", GenerationStep.DalInterface); } else { _fileSuccess.Add("IDalManager", null); _fileSuccess.Add("DalFactory", null); _fileSuccess.Add("DataNotFoundException", null); } if (generationParams.GenerateDalObject) { GenerateUtilityFile("DalManager" + dalName, false, "DalManager", GenerationStep.DalObject); } else { _fileSuccess.Add("DalManager", null); } if (_abortRequested) { OnGenerationInformation(Environment.NewLine + "* * * * Code Generation Cancelled!"); } _unit.GenerationTimer.Stop(); OnFinalized(true); } public event GenerationInformationDelegate GenerationInformation; public event GenerationInformationDelegate Step; public event EventHandler Finalized; #endregion #region Constructor public AdvancedGenerator(string targetDirectory, string templatesDirectory) { TargetDirectory = targetDirectory; _templatesDirectory = templatesDirectory; _codeEncoding = ValidateEncodings("CodeEncoding"); _sprocEncoding = ValidateEncodings("SProcEncoding"); } #endregion #region Private code generatiom private FileStream OpenFile(string filename) { // leave testing code /*var dontMakeFileBusy = filename.EndsWith("Validating_Business.txt") || filename.EndsWith(".Designer.cs")|| filename.EndsWith(".sql"); var dummy = File.Open(filename, FileMode.Create); if (dontMakeFileBusy) dummy.Close();*/ while (true) { try { var fs = File.Open(filename, FileMode.Create); return fs; } catch (IOException) { /*if (!dontMakeFileBusy) dummy.Close();*/ if (_unit.GenerationParams.RetryOnFileBusy && !_abortRequested) { _retryCount++; OutputWindow.Current.AddOutputInfo("... " + filename + " is busy. Retrying..."); } else { throw; } } } } private bool GeneralValidation(GenerationStep step) { var templateName = "ProjectValidate_" + step + ".cst"; var utilityFilename = "Validating_" + step + ".txt"; var fullFilename = TargetDirectory + @"\"; CheckDirectory(fullFilename); fullFilename += utilityFilename; if (File.Exists(fullFilename)) { File.Delete(fullFilename); } // Create utility class file if it does not exist if (!File.Exists(fullFilename)) { StreamWriter sw = null; try { var tPath = _fullTemplatesPath + _unit.GenerationParams.OutputLanguage + "\\" + templateName; var template = GetTemplate(new CslaObjectInfo(), tPath); if (template != null) { var errorsOutput = new StringBuilder(); var warningsOutput = new StringBuilder(); var infosOutput = new StringBuilder(); template.SetProperty("Errors", errorsOutput); template.SetProperty("Warnings", warningsOutput); template.SetProperty("Infos", infosOutput); template.SetProperty("CurrentUnit", _unit); OnGenerationInformation("Validation: " + step); var fs = OpenFile(fullFilename); sw = new StreamWriter(fs, Encoding.GetEncoding(_codeEncoding)); template.Render(sw); errorsOutput = (StringBuilder) template.GetProperty("Errors"); warningsOutput = (StringBuilder) template.GetProperty("Warnings"); infosOutput = (StringBuilder) template.GetProperty("Infos"); if (errorsOutput.Length > 0) { _errorReport.AddMultiline(new GenerationReport { ObjectName = "General Validation", ObjectType = step.ToString(), Message = errorsOutput.ToString(), FileName = fullFilename }); OnGenerationInformation("* * Failed:" + Environment.NewLine + errorsOutput); _fileSuccess[templateName] = false; } else { if (warningsOutput != null) { if (warningsOutput.Length > 0) { _warningReport.AddMultiline(new GenerationReport { ObjectName = "General Validation", ObjectType = step.ToString(), Message = warningsOutput.ToString(), FileName = fullFilename }); OnGenerationInformation("* Warning:" + Environment.NewLine + warningsOutput); } } if (infosOutput != null) { if (infosOutput.Length > 0) { _infoReport.Add(infosOutput.ToString()); } } _fileSuccess[templateName] = true; } } } catch (Exception e) { _fileSuccess[templateName] = false; string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + fullFilename + " is busy."; else msg = ShowExceptionInformation(e); _errorReport.Add(new GenerationReport { ObjectName = "General Validation", ObjectType = step.ToString(), Message = msg, FileName = fullFilename }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } // delete validation output file if (File.Exists(fullFilename)) { File.Delete(fullFilename); } if (_fileSuccess[templateName] == true) { OnGenerationInformation("Passed."); return true; } return false; } private static string ValidateEncodings(string key) { const string defaultEncoding = "iso-8859-1"; string encoding = ConfigurationManager.AppSettings.Get(key); if (string.IsNullOrWhiteSpace(encoding)) { MessageBox.Show(@"Error in ""appSettings"" section of ""CslaGenerator.exe.config"" file." + Environment.NewLine + @"The key """ + key + @""" is empty or missing." + Environment.NewLine + @"Will use " + defaultEncoding + @" instead.", @"CslaGenFork object generation", MessageBoxButtons.OK, MessageBoxIcon.Warning); return defaultEncoding; } try { var encode = Encoding.GetEncoding(encoding); } catch (Exception) { MessageBox.Show(@"Error in ""appSettings"" section of ""CslaGenerator.exe.config"" file." + Environment.NewLine + @"The key """ + key + @"""=""" + encoding + @""" is not valid." + Environment.NewLine + @"Will use """ + defaultEncoding + @""" instead.", @"CslaGenFork object generation", MessageBoxButtons.OK, MessageBoxIcon.Warning); return defaultEncoding; } return encoding; } private bool EditableSwitchableAlert(CslaObjectInfo objInfo) { _unit.GenerationTimer.Stop(); var result = true; if (objInfo.ObjectType == CslaObjectType.EditableSwitchable) { var alert = MessageBox.Show( objInfo.ObjectName + @" is a EditableSwitchable stereotype" + Environment.NewLine + @"and isn't supported on this release of CslaGenFork." + Environment.NewLine + Environment.NewLine + "Do you want to continue?", @"CslaGenFork object generation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (alert == DialogResult.Cancel) result = false; } _unit.GenerationTimer.Start(); return result; } private bool UnitOfWorkAlert(CslaObjectInfo objInfo) { _unit.GenerationTimer.Stop(); var result = true; if (objInfo.ObjectType == CslaObjectType.UnitOfWork && (objInfo.UnitOfWorkType == UnitOfWorkFunction.Deleter || objInfo.UnitOfWorkType == UnitOfWorkFunction.Updater)) { var alert = MessageBox.Show( objInfo.ObjectName + @" is a UnitOfWork stereotype of type " + objInfo.UnitOfWorkType + Environment.NewLine + @"and isn't supported on this release of CslaGenFork." + Environment.NewLine + Environment.NewLine + "Do you want to continue?", @"CslaGenFork object generation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (alert == DialogResult.Cancel) result = false; } _unit.GenerationTimer.Start(); return result; } private void GenerateObject(CslaObjectInfo objInfo) { if (!EditableSwitchableAlert(objInfo) || !UnitOfWorkAlert(objInfo)) { _objFailed++; OnGenerationInformation("Object generation cancelled." + Environment.NewLine); return; } var generationParams = _unit.GenerationParams; var baseFileName = GetBaseFileName(objInfo, true, generationParams.BaseNamespace, false, GenerationStep.Business); var extendedFileName = GetBaseFileName(objInfo, false, generationParams.BaseNamespace, false, GenerationStep.Business); var classCommentFileName = string.Empty; if (!string.IsNullOrEmpty(generationParams.ClassCommentFilenameSuffix)) classCommentFileName = GetBaseFileName(objInfo, false, generationParams.BaseNamespace, true, GenerationStep.Business); _methodList = new List<ServiceMethod>(); StreamWriter sw = null; try { var success = false; var tPath = _fullTemplatesPath + objInfo.OutputLanguage + @"\" + GetTemplateName(objInfo, GenerationStep.Business); var template = GetTemplate(objInfo, tPath); if (template != null) { var errorsOutput = new StringBuilder(); var warningsOutput = new StringBuilder(); var infosOutput = new StringBuilder(); template.SetProperty("Errors", errorsOutput); template.SetProperty("Warnings", warningsOutput); template.SetProperty("Infos", infosOutput); template.SetProperty("MethodList", _methodList); template.SetProperty("CurrentUnit", _unit); template.SetProperty("DataSetLoadingScheme", objInfo.DataSetLoadingScheme); if (generationParams.BackupOldSource && File.Exists(baseFileName)) { var oldFile = new FileInfo(baseFileName); if (File.Exists(baseFileName + ".old")) { File.Delete(baseFileName + ".old"); } oldFile.MoveTo(baseFileName + ".old"); } OnGenerationFileName(baseFileName); var fsBase = OpenFile(baseFileName); sw = new StreamWriter(fsBase, Encoding.GetEncoding(_codeEncoding)); template.Render(sw); errorsOutput = (StringBuilder) template.GetProperty("Errors"); warningsOutput = (StringBuilder) template.GetProperty("Warnings"); infosOutput = (StringBuilder) template.GetProperty("Infos"); _methodList = (List<ServiceMethod>)template.GetProperty("MethodList"); if (errorsOutput.Length > 0) { _businessError = true; _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = errorsOutput.ToString(), FileName = baseFileName }); OnGenerationInformation("* * Failed:" + Environment.NewLine + errorsOutput); } else { success = true; if (warningsOutput != null) { if (warningsOutput.Length > 0) { _objectWarnings++; _warningReport.AddMultiline(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = warningsOutput.ToString(), FileName = baseFileName }); OnGenerationInformation("* Warning:" + Environment.NewLine + warningsOutput); } } if (infosOutput != null) { if (infosOutput.Length > 0) { _infoReport.Add(infosOutput.ToString()); } } _objSuccess++; } } if (success) { GenerateExtendedFile(extendedFileName, objInfo); if (!string.IsNullOrEmpty(generationParams.ClassCommentFilenameSuffix)) GenerateClassCommentFile(classCommentFileName, objInfo); } } catch (Exception e) { _objFailed++; string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + baseFileName + " is busy."; else msg = ShowExceptionInformation(e); _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = msg, FileName = baseFileName }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } private void GenerateExtendedFile(string fileName, CslaObjectInfo objInfo) { GenerateExtendedFile(fileName, "\\ExtendedFile.cst", objInfo); } private void GenerateDalExtendedFile(string fileName, CslaObjectInfo objInfo, GenerationStep step) { GenerateExtendedFile(fileName, "\\ExtendedFile_" + step + ".cst", objInfo); } private void GenerateExtendedFile(string fileName, string templateFile, CslaObjectInfo objInfo) { // Create Extended file if it does not exist if (!File.Exists(fileName)) { StreamWriter sw = null; try { if (templateFile != string.Empty) { var tPath = _fullTemplatesPath + objInfo.OutputLanguage + templateFile; var template = GetTemplate(objInfo, tPath); if (template != null) { var errorsOutput = new StringBuilder(); template.SetProperty("Errors", errorsOutput); template.SetProperty("CurrentUnit", _unit); if (_methodList != null) template.SetProperty("MethodList", _methodList); OnGenerationFileName(fileName); var fs = OpenFile(fileName); sw = new StreamWriter(fs, Encoding.GetEncoding(_codeEncoding)); template.Render(sw); errorsOutput = (StringBuilder) template.GetProperty("Errors"); if (errorsOutput.Length > 0) { _businessError = true; _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = errorsOutput.ToString(), FileName = fileName }); OnGenerationInformation("* * Failed:" + Environment.NewLine + errorsOutput); } } } } catch (Exception e) { _objFailed++; string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + fileName + " is busy."; else msg = ShowExceptionInformation(e); _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = msg, FileName = fileName }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } } private void GenerateClassCommentFile(string fileName, CslaObjectInfo objInfo) { GenerateExtendedFile(fileName, "\\ClassComment.cst", objInfo); } private void GenerateDalClassCommentFile(string fileName, CslaObjectInfo objInfo, GenerationStep step) { GenerateExtendedFile(fileName, "\\ClassComment_" + step + ".cst", objInfo); } private void DoGenerateDalInterface(CslaObjectInfo objInfo) { if (!GeneratorController.Current.CurrentUnit.GenerationParams.GenerateDalInterface) return; DoGenerateDal(objInfo, GenerationStep.DalInterface); } private void DoGenerateDalObject(CslaObjectInfo objInfo) { if (!GeneratorController.Current.CurrentUnit.GenerationParams.GenerateDalObject) return; DoGenerateDal(objInfo, GenerationStep.DalObject); } private void DoGenerateDal(CslaObjectInfo objInfo, GenerationStep step) { if (objInfo.ObjectType == CslaObjectType.UnitOfWork) return; if (!EditableSwitchableAlert(objInfo) || !UnitOfWorkAlert(objInfo)) { _objFailed++; OnGenerationInformation("Object generation cancelled." + Environment.NewLine); return; } var generationParams = _unit.GenerationParams; var baseFileName = GetBaseFileName(objInfo, true, GetContextBaseNamespace(_unit, step), false, step); if (_businessError) { OnGenerationFileName(baseFileName); _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = "Error on Business generation.", FileName = baseFileName }); OnGenerationInformation("* * Failed:" + Environment.NewLine + "Error on Business generation." + Environment.NewLine); return; } var extendedFileName = GetBaseFileName(objInfo, false, GetContextBaseNamespace(_unit, step), false, step); var classCommentFileName = string.Empty; if (!string.IsNullOrEmpty(generationParams.ClassCommentFilenameSuffix)) classCommentFileName = GetBaseFileName(objInfo, false, GetContextBaseNamespace(_unit, step), true, step); _methodList = new List<ServiceMethod>(); StreamWriter sw = null; try { var tPath = _fullTemplatesPath + objInfo.OutputLanguage + @"\" + GetTemplateName(objInfo, step); var template = GetTemplate(objInfo, tPath); if (template != null) { var errorsOutput = new StringBuilder(); var warningsOutput = new StringBuilder(); var infosOutput = new StringBuilder(); template.SetProperty("Errors", errorsOutput); template.SetProperty("Warnings", warningsOutput); template.SetProperty("Infos", infosOutput); template.SetProperty("MethodList", _methodList); template.SetProperty("CurrentUnit", _unit); template.SetProperty("DataSetLoadingScheme", objInfo.DataSetLoadingScheme); if (generationParams.BackupOldSource && File.Exists(baseFileName)) { var oldFile = new FileInfo(baseFileName); if (File.Exists(baseFileName + ".old")) { File.Delete(baseFileName + ".old"); } oldFile.MoveTo(baseFileName + ".old"); } OnGenerationFileName(baseFileName); var fsBase = OpenFile(baseFileName); sw = new StreamWriter(fsBase, Encoding.GetEncoding(_codeEncoding)); template.Render(sw); errorsOutput = (StringBuilder) template.GetProperty("Errors"); warningsOutput = (StringBuilder) template.GetProperty("Warnings"); infosOutput = (StringBuilder) template.GetProperty("Infos"); _methodList = (List<ServiceMethod>)template.GetProperty("MethodList"); if (errorsOutput.Length > 0) { _objFailed++; _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = errorsOutput.ToString(), FileName = baseFileName }); OnGenerationInformation("* * Failed:" + Environment.NewLine + errorsOutput); } else { if (warningsOutput != null) { if (warningsOutput.Length > 0) { _objectWarnings++; _warningReport.AddMultiline(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = warningsOutput.ToString(), FileName = baseFileName }); OnGenerationInformation("* Warning:" + Environment.NewLine + warningsOutput); } } if (infosOutput != null) { if (infosOutput.Length > 0) { _infoReport.Add(infosOutput.ToString()); } } _objSuccess++; } } GenerateDalExtendedFile(extendedFileName, objInfo, step); if (!string.IsNullOrEmpty(generationParams.ClassCommentFilenameSuffix)) GenerateDalClassCommentFile(classCommentFileName, objInfo, step); } catch (Exception e) { _objFailed++; string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + baseFileName + " is busy."; else msg = ShowExceptionInformation(e); _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = msg, FileName = baseFileName }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } private void GenerateUtilityFile(string utilityFilename, bool deleteFile, string utilityTemplate, GenerationStep step) { var outputLanguage = _unit.GenerationParams.OutputLanguage; _fileSuccess.Add(utilityFilename, null); var fullFilename = GetUtilitiesFolderPath(step); CheckDirectory(fullFilename); // filename w/o extension fullFilename += utilityFilename; // extension if (outputLanguage == CodeLanguage.CSharp) fullFilename += ".cs"; else if (outputLanguage == CodeLanguage.VB) fullFilename += ".vb"; if (File.Exists(fullFilename) && deleteFile) { File.Delete(fullFilename); } // Create utility class file if it does not exist if (!File.Exists(fullFilename)) { StreamWriter sw = null; try { if (utilityTemplate != string.Empty) { var tPath = _fullTemplatesPath + outputLanguage + "\\" + utilityTemplate + ".cst"; var template = GetTemplate(new CslaObjectInfo(), tPath); if (template != null) { var errorsOutput = new StringBuilder(); var warningsOutput = new StringBuilder(); var infosOutput = new StringBuilder(); template.SetProperty("Errors", errorsOutput); template.SetProperty("Warnings", warningsOutput); template.SetProperty("Infos", infosOutput); template.SetProperty("CurrentUnit", _unit); OnGenerationInformation(utilityFilename + " file:"); OnGenerationFileName(fullFilename); var fs = OpenFile(fullFilename); sw = new StreamWriter(fs, Encoding.GetEncoding(_codeEncoding)); template.Render(sw); errorsOutput = (StringBuilder) template.GetProperty("Errors"); warningsOutput = (StringBuilder) template.GetProperty("Warnings"); infosOutput = (StringBuilder) template.GetProperty("Infos"); if (errorsOutput.Length > 0) { _errorReport.Add(new GenerationReport { ObjectName = "Utility", ObjectType = step.ToString(), Message = errorsOutput.ToString(), FileName = fullFilename }); OnGenerationInformation("* * Failed:" + Environment.NewLine + errorsOutput); _fileSuccess[utilityFilename] = false; } else { if (warningsOutput != null) { if (warningsOutput.Length > 0) { _warningReport.AddMultiline(new GenerationReport { ObjectName = "Utility", ObjectType = step.ToString(), Message = warningsOutput.ToString(), FileName = fullFilename }); OnGenerationInformation("* Warning:" + Environment.NewLine + warningsOutput); } } if (infosOutput != null) { if (infosOutput.Length > 0) { _infoReport.Add(infosOutput.ToString()); } } _fileSuccess[utilityFilename] = true; } } } } catch (Exception e) { _fileSuccess[utilityFilename] = false; string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + fullFilename + " is busy."; else msg = ShowExceptionInformation(e); _errorReport.Add(new GenerationReport { ObjectName = "Utility", ObjectType = step.ToString(), Message = msg, FileName = fullFilename }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } } private string GetUtilitiesFolderPath(GenerationStep step) { // base directory of project var result = TargetDirectory + @"\"; if (_unit.GenerationParams.SeparateNamespaces)// use namespace as folder { result += GetContextBaseNamespace(_unit, step) + @"\"; if (_unit.GenerationParams.UtilitiesNamespace == _unit.GenerationParams.BaseNamespace) return result; return result + _unit.GenerationParams.UtilitiesNamespace.Substring(_unit.GenerationParams.BaseNamespace.Length + 1) + @"\"; } // use step for base folder to avoid the mess if (_unit.GenerationParams.TargetIsCsla4DAL) result += step + @"\"; if (!_unit.GenerationParams.UtilitiesFolder.Equals(string.Empty)) result += _unit.GenerationParams.UtilitiesFolder; if (result.EndsWith(@"\") == false) result += @"\"; return result; } private CodeTemplate GetTemplate(CslaObjectInfo objInfo, string templatePath) { CodeTemplateCompiler compiler; if (!_templates.ContainsKey(templatePath)) { if (!File.Exists(templatePath)) throw new ApplicationException("The specified template could not be found: " + templatePath); compiler = new CodeTemplateCompiler(templatePath); compiler.Compile(); _templates.Add(templatePath, compiler); var sb = new StringBuilder(); for (int i = 0; i < compiler.Errors.Count; i++) { sb.Append(compiler.Errors[i].ToString()); sb.Append(Environment.NewLine); } if (compiler.Errors.Count > 0) throw new Exception(string.Format( "Template {0} failed to compile. Objects of the same type will be ignored.", templatePath) + Environment.NewLine + sb); } else { compiler = (CodeTemplateCompiler)_templates[templatePath]; } if (compiler.Errors.Count > 0) return null; var template = compiler.CreateInstance(); template.SetProperty("Info", objInfo); return template; } private string ShowExceptionInformation(Exception e) { var sb = new StringBuilder(); sb.AppendLine("* * * Error:"); sb.AppendLine(e.Message); sb.AppendLine("Stack Trace:"); sb.AppendLine(e.StackTrace); return sb.ToString(); } private void WriteToFile(string fileName, string data, CslaObjectInfo objInfo) { if (_unit.GenerationParams.BackupOldSource && File.Exists(fileName)) { var oldFile = new FileInfo(fileName); if (File.Exists(fileName + ".old")) { File.Delete(fileName + ".old"); } oldFile.MoveTo(fileName + ".old"); } StreamWriter sw = null; try { var fs = OpenFile(fileName); sw = new StreamWriter(fs, Encoding.GetEncoding(_sprocEncoding)); sw.Write(data); } catch (Exception e) { string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + fileName + " is busy."; else msg = ShowExceptionInformation(e); if (!_currentSprocError) { _sprocFailed++; _sprocSuccess--; } _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = msg, FileName = fileName }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } #endregion #region Private Stored Procedures generation private bool NeedsDbFetch(CslaObjectInfo info) { var selfLoad = CslaTemplateHelperCS.IsChildSelfLoaded(info); return (!((info.ObjectType == CslaObjectType.EditableChildCollection || info.ObjectType == CslaObjectType.EditableChild) && !selfLoad)); } private bool HasFetchCriteria(CslaObjectInfo info) { return (info.CriteriaObjects.Any(crit => crit.GetOptions.Procedure && !string.IsNullOrEmpty(crit.GetOptions.ProcedureName))); // foreach (var crit in info.CriteriaObjects) // if (crit.GetOptions.Procedure && !string.IsNullOrEmpty(crit.GetOptions.ProcedureName)) // return true; } private bool HasInsUpdDelcriteria(CslaObjectInfo info) { return (info.InsertProcedureName != string.Empty) || (info.UpdateProcedureName != string.Empty) || (info.CriteriaObjects.Any(crit => crit.DeleteOptions.Procedure && !string.IsNullOrEmpty(crit.DeleteOptions.ProcedureName))); } private bool NeedsDbInsUpdDel(CslaObjectInfo info) { return (info.ObjectType != CslaObjectType.ReadOnlyObject && info.ObjectType != CslaObjectType.ReadOnlyCollection && info.ObjectType != CslaObjectType.EditableRootCollection && info.ObjectType != CslaObjectType.DynamicEditableRootCollection && info.ObjectType != CslaObjectType.EditableChildCollection && info.ObjectType != CslaObjectType.NameValueList && info.ObjectType != CslaObjectType.UnitOfWork); } private void GenerateAllSprocsFile(CslaObjectInfo info, string dir) { var filename = dir + @"\sprocs\" + info.ObjectName + ".sql"; var proc = new StringBuilder(); //make sure we don't generate selects when we don't need to. if (NeedsDbFetch(info)) { foreach (var crit in info.CriteriaObjects) { if (crit.GetOptions.Procedure && !string.IsNullOrEmpty(crit.GetOptions.ProcedureName)) { proc.AppendLine(GenerateProcedure(info, crit, "SelectProcedure.cst", crit.GetOptions.ProcedureName, filename)); filename = string.Empty; } } } if (NeedsDbInsUpdDel(info)) { //Insert if (info.InsertProcedureName != string.Empty) { proc.AppendLine(GenerateProcedure(info, null, "InsertProcedure.cst", info.InsertProcedureName, filename)); filename = string.Empty; } //Update if (info.UpdateProcedureName != string.Empty) { proc.AppendLine(GenerateProcedure(info, null, "UpdateProcedure.cst", info.UpdateProcedureName, filename)); filename = string.Empty; } //Delete if (info.ObjectType == CslaObjectType.EditableChild) { if (info.DeleteProcedureName != string.Empty) { proc.AppendLine(GenerateProcedure(info, null, "DeleteProcedure.cst", info.DeleteProcedureName, filename)); filename = string.Empty; } } else { foreach (var crit in info.CriteriaObjects) { if (crit.DeleteOptions.Procedure && !string.IsNullOrEmpty(crit.DeleteOptions.ProcedureName)) { proc.AppendLine(GenerateProcedure(info, crit, "DeleteProcedure.cst", crit.DeleteOptions.ProcedureName, filename)); filename = string.Empty; } } } } if (proc.Length > 0) { CheckDirectory(dir + @"\sprocs"); WriteToFile(dir + @"\sprocs\" + info.ObjectName + ".sql", proc.ToString(), info); } } private void GenerateSelectProcedure(CslaObjectInfo info, string dir) { //make sure we don't generate selects when we don't need to. if (NeedsDbFetch(info)) { foreach (var crit in info.CriteriaObjects) { if (crit.GetOptions.Procedure && !string.IsNullOrEmpty(crit.GetOptions.ProcedureName)) { var proc = GenerateProcedure(info, crit, "SelectProcedure.cst", crit.GetOptions.ProcedureName, dir + @"\sprocs\" + crit.GetOptions.ProcedureName + ".sql"); CheckDirectory(dir + @"\sprocs"); WriteToFile(dir + @"\sprocs\" + crit.GetOptions.ProcedureName + ".sql", proc, info); } } } } private void GenerateInsertProcedure(CslaObjectInfo info, string dir) { if (info.InsertProcedureName != string.Empty) { var proc = GenerateProcedure(info, null, "InsertProcedure.cst", info.InsertProcedureName, dir + @"\sprocs\" + info.InsertProcedureName + ".sql"); CheckDirectory(dir + @"\sprocs"); WriteToFile(dir + @"\sprocs\" + info.InsertProcedureName + ".sql", proc, info); } } private void GenerateUpdateProcedure(CslaObjectInfo info, string dir) { if (info.UpdateProcedureName != string.Empty) { var proc = GenerateProcedure(info, null, "UpdateProcedure.cst", info.UpdateProcedureName, dir + @"\sprocs\" + info.UpdateProcedureName + ".sql"); CheckDirectory(dir + @"\sprocs"); WriteToFile(dir + @"\sprocs\" + info.UpdateProcedureName + ".sql", proc, info); } } private void GenerateDeleteProcedure(CslaObjectInfo info, string dir) { if (info.ObjectType == CslaObjectType.EditableChild) { if (info.DeleteProcedureName != string.Empty) { var proc = GenerateProcedure(info, null, "DeleteProcedure.cst", info.DeleteProcedureName, dir + @"\sprocs\" + info.DeleteProcedureName + ".sql"); CheckDirectory(dir + @"\sprocs"); WriteToFile(dir + @"\sprocs\" + info.DeleteProcedureName + ".sql", proc, info); } } else { foreach (var crit in info.CriteriaObjects) { if (crit.DeleteOptions.Procedure && !string.IsNullOrEmpty(crit.DeleteOptions.ProcedureName)) { var proc = GenerateProcedure(info, crit, "DeleteProcedure.cst", crit.DeleteOptions.ProcedureName, dir + @"\sprocs\" + crit.DeleteOptions.ProcedureName + ".sql"); CheckDirectory(dir + @"\sprocs"); WriteToFile(dir + @"\sprocs\" + crit.DeleteOptions.ProcedureName + ".sql", proc, info); } } } } private string GenerateProcedure(CslaObjectInfo objInfo, Criteria crit, string templateName, string sprocName, string filename) { _currentSprocError = false; if (objInfo != null) { StringWriter sw = null; try { if (templateName != string.Empty) { var path = _templatesDirectory + @"SProcs4\" + templateName; var template = GetTemplate(objInfo, path); if (template != null) { var errorsOutput = new StringBuilder(); var warningsOutput = new StringBuilder(); var infosOutput = new StringBuilder(); template.SetProperty("Errors", errorsOutput); template.SetProperty("Warnings", warningsOutput); template.SetProperty("Infos", infosOutput); if (crit != null) template.SetProperty("Criteria", crit); template.SetProperty("IncludeParentProperties", objInfo.DataSetLoadingScheme); sw = new StringWriter(); if (!string.IsNullOrEmpty(filename)) OnGenerationFileName(filename); template.Render(sw); errorsOutput = (StringBuilder) template.GetProperty("Errors"); warningsOutput = (StringBuilder) template.GetProperty("Warnings"); infosOutput = (StringBuilder)template.GetProperty("Infos"); if (errorsOutput.Length > 0) { _sprocFailed++; _currentSprocError = true; _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = errorsOutput.ToString(), FileName = filename }); OnGenerationInformation("* * Failed:" + Environment.NewLine + errorsOutput); } else { if (warningsOutput != null) { if (warningsOutput.Length > 0) { _sprocWarnings++; _warningReport.AddMultiline(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = warningsOutput.ToString(), FileName = filename }); OnGenerationInformation("* Warning:" + Environment.NewLine + warningsOutput); } } if (infosOutput != null) { if (infosOutput.Length > 0) { _infoReport.Add(infosOutput.ToString()); } } _sprocSuccess++; } var sproc = sw.ToString(); sproc = sproc.Replace("\r\n\r\n\r\n\r\n", "\r\n\r\n"); sproc = sproc.Replace("\r\n\r\n\r\n", "\r\n\r\n"); return sproc; } } } catch (Exception e) { _sprocFailed++; _currentSprocError = true; string msg; if (e.GetBaseException() as IOException != null) msg = "* Failed: " + filename + " is busy."; else msg = ShowExceptionInformation(e); _errorReport.Add(new GenerationReport { ObjectName = objInfo.ObjectName, ObjectType = objInfo.ObjectType.ToString(), Message = msg, FileName = filename }); OnGenerationInformation(msg); } finally { if (sw != null) sw.Close(); } } return string.Empty; } #endregion #region Private File / Directory related methods internal static string GetContextBaseNamespace(CslaGeneratorUnit unit, GenerationStep step) { if (step == GenerationStep.Business) return unit.GenerationParams.BaseNamespace; if (step == GenerationStep.DalInterface || step == GenerationStep.DalInterfaceDto) return unit.GenerationParams.DalInterfaceNamespace; //if (step == GenerationStep.DalObject) return unit.GenerationParams.DalObjectNamespace; } private static void CheckDirectory(string dir) { if (!Directory.Exists(dir)) { if (dir.StartsWith(@"\\")) { throw new ApplicationException("Illegal path: UNC paths are not supported."); } // Recursion // If this folder doesn't exists, check the parent folder if (dir.EndsWith(@"\")) { dir = dir.Substring(0, dir.Length - 1); } else if (dir.IndexOf(@"\") == -1) throw new ApplicationException(string.Format("The output path could not be created. Check that the \"{0}\" unit exists.", dir)); CheckDirectory(dir.Substring(0, dir.LastIndexOf(@"\"))); Directory.CreateDirectory(dir); } } private string GetDirectoryForNamespace(string targetDir, CslaObjectInfo info, bool isBaseClass, string baseNamespace, bool isClassComment, GenerationStep step) { if (targetDir.EndsWith(@"\") == false) targetDir += @"\"; if (_unit.GenerationParams.SeparateNamespaces) // use namespace as folder { var objectNamespace = info.ObjectNamespace; targetDir += baseNamespace; objectNamespace = objectNamespace.Substring(_unit.GenerationParams.BaseNamespace.Length); targetDir += objectNamespace.Replace(".", @"\"); if (targetDir.EndsWith(@"\") == false) { targetDir += @"\"; } } else if (_unit.GenerationParams.TargetIsCsla4DAL) { targetDir += step + @"\"; } if (!info.Folder.Trim().Equals(string.Empty)) targetDir += info.Folder + @"\"; if (isBaseClass) { targetDir += @"Base\"; } if (isClassComment) { targetDir += @"Comment\"; } CheckDirectory(targetDir); return targetDir; } private string GetBaseFileName(CslaObjectInfo info, bool isBaseClass, string baseNamespace, bool isClassComment, GenerationStep step) { var fileNoExtension = GetFileNameWithoutExtension(info.FileName); if (step != GenerationStep.Business) { if (step == GenerationStep.DalInterfaceDto) { if (info.ObjectType == CslaObjectType.NameValueList) fileNoExtension += "ItemDto"; else fileNoExtension += "Dto"; } else { fileNoExtension += "Dal"; if (step == GenerationStep.DalInterface) fileNoExtension = "I" + fileNoExtension; } } if (isBaseClass) { if (!string.IsNullOrEmpty(_unit.GenerationParams.BaseFilenameSuffix)) fileNoExtension += _unit.GenerationParams.BaseFilenameSuffix; } else if (isClassComment) { if (!string.IsNullOrEmpty(_unit.GenerationParams.ClassCommentFilenameSuffix)) fileNoExtension += _unit.GenerationParams.ClassCommentFilenameSuffix; } else { if (!string.IsNullOrEmpty(_unit.GenerationParams.ExtendedFilenameSuffix)) fileNoExtension += _unit.GenerationParams.ExtendedFilenameSuffix; } var fileExtension = GetFileExtension(info.FileName); if (fileExtension == string.Empty) { if (info.OutputLanguage == CodeLanguage.CSharp) fileNoExtension += ".cs"; if (info.OutputLanguage == CodeLanguage.VB) fileNoExtension += ".vb"; } else { fileNoExtension += fileExtension; } return GetDirectoryForNamespace(TargetDirectory, info, (isBaseClass && _unit.GenerationParams.SeparateBaseClasses), baseNamespace, (isClassComment && _unit.GenerationParams.SeparateClassComment), step) + fileNoExtension; } private static string GetFileNameWithoutExtension(string fileName) { var index = fileName.LastIndexOf("."); if (index >= 0) { return fileName.Substring(0, index); } return fileName; } private static string GetFileExtension(string fileName) { var index = fileName.LastIndexOf("."); if (index >= 0) { return fileName.Substring(index + 1); } return string.Empty; } private static string GetTemplateName(CslaObjectInfo info, GenerationStep step) { return GetTemplateName(info.ObjectType, step ); } private static string GetTemplateName(CslaObjectType type, GenerationStep step) { if (step == GenerationStep.Business) return string.Format("{0}.cst", type); return string.Format("{0}_{1}.cst", type, step); } #endregion #region Event triggers private void OnGenerationFileName(string e) { if (GenerationInformation != null) GenerationInformation(e); OutputWindow.Current.AddOutputInfo("\tFile: " + e); } private void OnGenerationInformation(string e) { if (GenerationInformation != null) GenerationInformation(e); OutputWindow.Current.AddOutputInfo(e, 1); } private void OnStep(string objectName) { if (Step != null) Step(objectName); OutputWindow.Current.AddOutputInfo(string.Format("{0}:", objectName)); } private void OnFinalized(bool isProjectValid) { if (Finalized != null) Finalized(this, new EventArgs()); OutputWindow.Current.AddOutputInfo("\r\nDone"); if (isProjectValid) { var dbConnection = _unit.GenerationParams.DatabaseConnection; var dalName = CslaTemplateHelperCS.GetDalName(_unit); if (_generateDatabaseClass) { if (_fileSuccess["Database" + dbConnection] == null) OutputWindow.Current.AddOutputInfo(string.Format("Database" + dbConnection + " class: already exists.")); else if (_fileSuccess["Database" + dbConnection] == false) OutputWindow.Current.AddOutputInfo(string.Format("Database" + dbConnection + " class: failed.")); } if (_fileSuccess["DataPortalHookArgs"] == null) OutputWindow.Current.AddOutputInfo(string.Format("DataPortalHookArgs class: already exists.")); else if (_fileSuccess["DataPortalHookArgs"] == false) OutputWindow.Current.AddOutputInfo(string.Format("DataPortalHookArgs class: failed.")); if (GeneratorController.Current.CurrentUnit.GenerationParams.GenerateDalInterface) { if (_fileSuccess["IDalManager" + dalName] == null) OutputWindow.Current.AddOutputInfo(string.Format("IDalManager" + dalName + " class: already exists.")); else if (_fileSuccess["IDalManager" + dalName] == false) OutputWindow.Current.AddOutputInfo(string.Format("IDalManager" + dalName + " class: failed.")); if (_fileSuccess["DalFactory" + dalName] == null) OutputWindow.Current.AddOutputInfo(string.Format("DalFactory" + dalName + " class: already exists.")); else if (_fileSuccess["DalFactory" + dalName] == false) OutputWindow.Current.AddOutputInfo(string.Format("DalFactory" + dalName + " class: failed.")); if (_fileSuccess["DataNotFoundException"] == null) OutputWindow.Current.AddOutputInfo(string.Format("DataNotFoundException class: already exists.")); else if (_fileSuccess["DataNotFoundException"] == false) OutputWindow.Current.AddOutputInfo(string.Format("DataNotFoundException class: failed.")); } if (GeneratorController.Current.CurrentUnit.GenerationParams.GenerateDalObject) { if (_fileSuccess["DalManager" + dalName] == null) OutputWindow.Current.AddOutputInfo(string.Format("DalManager" + dalName + " class: already exists.")); else if (_fileSuccess["DalManager" + dalName] == false) OutputWindow.Current.AddOutputInfo(string.Format("DalManager" + dalName + " class: failed.")); } if (_sprocWarnings > 0 || _objectWarnings > 0) OutputWindow.Current.AddOutputInfo(""); if (_sprocWarnings > 0) OutputWindow.Current.AddOutputInfo(string.Format("SProc warnings: {0} object{1}.", _sprocWarnings, _sprocWarnings > 1 ? "s" : "")); if (_objectWarnings > 0) OutputWindow.Current.AddOutputInfo(string.Format("Object warnings: {0} object{1}.", _objectWarnings, _objectWarnings > 1 ? "s" : "")); OutputWindow.Current.AddOutputInfo(string.Format("\r\nClasses: {0} generated. {1} failed.", (_objFailed + _objSuccess), _objFailed)); OutputWindow.Current.AddOutputInfo(string.Format("Stored Procs: {0} generated. {1} failed.", (_sprocFailed + _sprocSuccess), _sprocFailed)); if (_retryCount > 0) OutputWindow.Current.AddOutputInfo("File busy retries: " + _retryCount); if (InfoReport.Count > 0) { OutputWindow.Current.AddOutputInfo("\r\nINFORMATION"); foreach (var line in InfoReport) { OutputWindow.Current.AddOutputInfo(line); } } } GeneratorController.Current.HasErrors = _errorReport.Count > 0; GeneratorController.Current.HasWarnings = _warningReport.Count > 0; } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.IO; using System.Text; using System.Drawing; using System.Data; using System.Windows.Forms; using PdfSharp.Explorer.Pages; using PdfSharp.Drawing; using PdfSharp.Pdf; using PdfSharp.Pdf.Advanced; namespace PdfSharp.Explorer { /// <summary> /// /// </summary> public class ExplorerPanel : System.Windows.Forms.UserControl { private System.Windows.Forms.ColumnHeader id; private System.Windows.Forms.ColumnHeader type; internal System.Windows.Forms.ListView lvObjects; private System.Windows.Forms.TabPage tpObjects; private System.Windows.Forms.TabPage tpInfo; internal System.Windows.Forms.ListBox lbxInfo; private System.Windows.Forms.TabControl tbcNavigation; private System.Windows.Forms.TabPage tpPages; internal System.Windows.Forms.ListView lvPages; private System.Windows.Forms.ColumnHeader clmPage; private System.Windows.Forms.Panel pnlNavigation; private System.Windows.Forms.Splitter splitter; private System.Windows.Forms.Panel pnlWorkArea; private System.Windows.Forms.TabPage tpPdf; private System.Windows.Forms.TabPage tpData; private System.Windows.Forms.ColumnHeader clmSize; private System.Windows.Forms.TabControl tbcMain; private System.ComponentModel.Container components = null; public ExplorerPanel(MainForm mainForm) { this.mainForm = mainForm; this.process = mainForm.Process; InitializeComponent(); PageBase page = new PdfTextPage(this); this.tbcMain.TabPages[1].Controls.Add(page); page.Dock = DockStyle.Fill; } public MainForm MainForm { get {return this.mainForm;} } MainForm mainForm; public void OnNewDocument() { this.process = this.mainForm.Process; PdfObject[] objects = this.process.Document.Internals.GetAllObjects(); this.lvObjects.Items.Clear(); for (int idx = 0; idx < objects.Length; idx++) { PdfObject obj = objects[idx]; ListViewItem item = new ListViewItem(new string[2]{PdfInternals.GetObjectID(obj).ToString(), ExplorerProcess.GetTypeName(obj)}); item.Tag = obj; this.lvObjects.Items.Add(item); } PdfPages pages = this.process.Document.Pages; this.lvPages.Items.Clear(); for (int idx = 0; idx < pages.Count; idx++) { PdfPage page = pages[idx]; ListViewItem item = new ListViewItem(new string[2]{(idx + 1).ToString(), ExplorerHelper.PageSize(page, this.mainForm.Process.IsMetric)}); //String.Format("{0:0} x {1:0} mm", XUnit.FromPoint(page.Width).Millimeter,XUnit.FromPoint(page.Height).Millimeter)}); item.Tag = page; this.lvPages.Items.Add(item); } this.process.Navigator.SetNext(this.process.Document.Info); ActivatePage("Info"); } public ExplorerProcess Process { get { return this.process; } } ExplorerProcess process; public void NavigateTo(PdfItem item) { } void ActivatePage(string name) { if (this.currentPage != null) { if (this.currentPage.Tag.Equals(name)) { this.currentPage.UpdateDocument(); return; } this.tpData.Controls.Remove(this.currentPage); this.currentPage = null; } switch (name) { case "Info": if (this.infoPage == null) this.infoPage = new MainInformationPage(this); this.currentPage = this.infoPage; break; case "Pages": if (this.pagesPage == null) this.pagesPage = new MainPagesPage(this); this.currentPage = this.pagesPage; this.currentPage.Dock = DockStyle.Fill; break; case "Objects": if (this.objectsPage == null) this.objectsPage = new MainObjectsPage(this); this.currentPage = this.objectsPage; this.currentPage.Dock = DockStyle.Fill; break; //case "Tree": // if (this.treePage == null) // this.treePage = new MainTreePage(this); // this.currentPage = this.treePage; // this.currentPage.Dock = DockStyle.Fill; // break; default: throw new NotImplementedException("tag: " + name); } this.tpData.Controls.Add(this.currentPage); } PageBase currentPage; PageBase infoPage; PageBase pagesPage; PageBase objectsPage; //PageBase treePage; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } protected override void OnLoad(EventArgs e) { base.OnLoad (e); ActivatePage("Info"); } void ActivateTab(PdfObject value) { switch (this.tbcMain.SelectedIndex) { // Data case 0: if (this.tbcMain.TabPages[0].Controls[0] is MainObjectsPageBase) ((MainObjectsPageBase)this.tbcMain.TabPages[0].Controls[0]).ActivatePage(value); break; // PDF case 1: ((PdfTextPage)this.tbcMain.TabPages[1].Controls[0]).SetObject(value); break; } } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tbcNavigation = new System.Windows.Forms.TabControl(); this.tpInfo = new System.Windows.Forms.TabPage(); this.lbxInfo = new System.Windows.Forms.ListBox(); this.tpObjects = new System.Windows.Forms.TabPage(); this.lvObjects = new System.Windows.Forms.ListView(); this.id = new System.Windows.Forms.ColumnHeader(); this.type = new System.Windows.Forms.ColumnHeader(); this.tpPages = new System.Windows.Forms.TabPage(); this.lvPages = new System.Windows.Forms.ListView(); this.clmPage = new System.Windows.Forms.ColumnHeader(); this.clmSize = new System.Windows.Forms.ColumnHeader(); this.pnlNavigation = new System.Windows.Forms.Panel(); this.splitter = new System.Windows.Forms.Splitter(); this.pnlWorkArea = new System.Windows.Forms.Panel(); this.tbcMain = new System.Windows.Forms.TabControl(); this.tpData = new System.Windows.Forms.TabPage(); this.tpPdf = new System.Windows.Forms.TabPage(); this.tbcNavigation.SuspendLayout(); this.tpInfo.SuspendLayout(); this.tpObjects.SuspendLayout(); this.tpPages.SuspendLayout(); this.pnlNavigation.SuspendLayout(); this.pnlWorkArea.SuspendLayout(); this.tbcMain.SuspendLayout(); this.SuspendLayout(); // // tbcNavigation // this.tbcNavigation.Alignment = System.Windows.Forms.TabAlignment.Left; this.tbcNavigation.Controls.Add(this.tpInfo); this.tbcNavigation.Controls.Add(this.tpObjects); this.tbcNavigation.Controls.Add(this.tpPages); this.tbcNavigation.Dock = System.Windows.Forms.DockStyle.Fill; this.tbcNavigation.Font = new System.Drawing.Font("Verdana", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbcNavigation.Location = new System.Drawing.Point(3, 0); this.tbcNavigation.Multiline = true; this.tbcNavigation.Name = "tbcNavigation"; this.tbcNavigation.SelectedIndex = 0; this.tbcNavigation.Size = new System.Drawing.Size(195, 630); this.tbcNavigation.TabIndex = 0; this.tbcNavigation.SelectedIndexChanged += new System.EventHandler(this.tbcNavigation_SelectedIndexChanged); // // tpInfo // this.tpInfo.Controls.Add(this.lbxInfo); this.tpInfo.Location = new System.Drawing.Point(24, 4); this.tpInfo.Name = "tpInfo"; this.tpInfo.Size = new System.Drawing.Size(167, 622); this.tpInfo.TabIndex = 2; this.tpInfo.Tag = "Info"; this.tpInfo.Text = "Information"; // // lbxInfo // this.lbxInfo.Dock = System.Windows.Forms.DockStyle.Fill; this.lbxInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.lbxInfo.Items.AddRange(new object[] { "Description", "Security", "Initial View", "(Fonts)", "(Annotations)", "(Images)", "ect..."}); this.lbxInfo.Location = new System.Drawing.Point(0, 0); this.lbxInfo.Name = "lbxInfo"; this.lbxInfo.Size = new System.Drawing.Size(167, 615); this.lbxInfo.TabIndex = 0; // // tpObjects // this.tpObjects.Controls.Add(this.lvObjects); this.tpObjects.Location = new System.Drawing.Point(24, 4); this.tpObjects.Name = "tpObjects"; this.tpObjects.Size = new System.Drawing.Size(167, 622); this.tpObjects.TabIndex = 0; this.tpObjects.Tag = "Objects"; this.tpObjects.Text = "Objects"; // // lvObjects // this.lvObjects.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.id, this.type}); this.lvObjects.Dock = System.Windows.Forms.DockStyle.Fill; this.lvObjects.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.lvObjects.FullRowSelect = true; this.lvObjects.GridLines = true; this.lvObjects.HideSelection = false; this.lvObjects.Location = new System.Drawing.Point(0, 0); this.lvObjects.MultiSelect = false; this.lvObjects.Name = "lvObjects"; this.lvObjects.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lvObjects.Size = new System.Drawing.Size(167, 622); this.lvObjects.TabIndex = 0; this.lvObjects.UseCompatibleStateImageBehavior = false; this.lvObjects.View = System.Windows.Forms.View.Details; this.lvObjects.SelectedIndexChanged += new System.EventHandler(this.lvObjects_SelectedIndexChanged); // // id // this.id.Text = "ID"; this.id.Width = 57; // // type // this.type.Text = "Type"; this.type.Width = 72; // // tpPages // this.tpPages.Controls.Add(this.lvPages); this.tpPages.Location = new System.Drawing.Point(24, 4); this.tpPages.Name = "tpPages"; this.tpPages.Size = new System.Drawing.Size(167, 622); this.tpPages.TabIndex = 3; this.tpPages.Tag = "Pages"; this.tpPages.Text = "Pages"; // // lvPages // this.lvPages.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.clmPage, this.clmSize}); this.lvPages.Dock = System.Windows.Forms.DockStyle.Fill; this.lvPages.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.lvPages.FullRowSelect = true; this.lvPages.HideSelection = false; this.lvPages.Location = new System.Drawing.Point(0, 0); this.lvPages.MultiSelect = false; this.lvPages.Name = "lvPages"; this.lvPages.Size = new System.Drawing.Size(167, 622); this.lvPages.TabIndex = 0; this.lvPages.UseCompatibleStateImageBehavior = false; this.lvPages.View = System.Windows.Forms.View.Details; this.lvPages.SelectedIndexChanged += new System.EventHandler(this.lvPages_SelectedIndexChanged); // // clmPage // this.clmPage.Text = "Page"; // // clmSize // this.clmSize.Text = "Size"; this.clmSize.Width = 100; // // pnlNavigation // this.pnlNavigation.Controls.Add(this.tbcNavigation); this.pnlNavigation.Dock = System.Windows.Forms.DockStyle.Left; this.pnlNavigation.Location = new System.Drawing.Point(0, 0); this.pnlNavigation.Name = "pnlNavigation"; this.pnlNavigation.Padding = new System.Windows.Forms.Padding(3, 0, 2, 0); this.pnlNavigation.Size = new System.Drawing.Size(200, 630); this.pnlNavigation.TabIndex = 1; // // splitter // this.splitter.BackColor = System.Drawing.SystemColors.Control; this.splitter.Location = new System.Drawing.Point(200, 0); this.splitter.Name = "splitter"; this.splitter.Size = new System.Drawing.Size(3, 630); this.splitter.TabIndex = 2; this.splitter.TabStop = false; // // pnlWorkArea // this.pnlWorkArea.BackColor = System.Drawing.SystemColors.Control; this.pnlWorkArea.Controls.Add(this.tbcMain); this.pnlWorkArea.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlWorkArea.Location = new System.Drawing.Point(203, 0); this.pnlWorkArea.Name = "pnlWorkArea"; this.pnlWorkArea.Padding = new System.Windows.Forms.Padding(2, 0, 4, 0); this.pnlWorkArea.Size = new System.Drawing.Size(787, 630); this.pnlWorkArea.TabIndex = 3; // // tbcMain // this.tbcMain.Controls.Add(this.tpData); this.tbcMain.Controls.Add(this.tpPdf); this.tbcMain.Dock = System.Windows.Forms.DockStyle.Fill; this.tbcMain.Location = new System.Drawing.Point(2, 0); this.tbcMain.Name = "tbcMain"; this.tbcMain.SelectedIndex = 0; this.tbcMain.Size = new System.Drawing.Size(781, 630); this.tbcMain.TabIndex = 0; this.tbcMain.SelectedIndexChanged += new System.EventHandler(this.tbcMain_SelectedIndexChanged); // // tpData // this.tpData.Location = new System.Drawing.Point(4, 22); this.tpData.Name = "tpData"; this.tpData.Size = new System.Drawing.Size(773, 604); this.tpData.TabIndex = 0; this.tpData.Text = "Data"; // // tpPdf // this.tpPdf.Location = new System.Drawing.Point(4, 22); this.tpPdf.Name = "tpPdf"; this.tpPdf.Size = new System.Drawing.Size(773, 604); this.tpPdf.TabIndex = 1; this.tpPdf.Text = "PDF"; // // ExplorerPanel // this.BackColor = System.Drawing.SystemColors.Control; this.Controls.Add(this.pnlWorkArea); this.Controls.Add(this.splitter); this.Controls.Add(this.pnlNavigation); this.Name = "ExplorerPanel"; this.Size = new System.Drawing.Size(990, 630); this.tbcNavigation.ResumeLayout(false); this.tpInfo.ResumeLayout(false); this.tpObjects.ResumeLayout(false); this.tpPages.ResumeLayout(false); this.pnlNavigation.ResumeLayout(false); this.pnlWorkArea.ResumeLayout(false); this.tbcMain.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void tbcNavigation_SelectedIndexChanged(object sender, System.EventArgs e) { ActivatePage(this.tbcNavigation.SelectedTab.Tag.ToString()); } private void lvObjects_SelectedIndexChanged(object sender, System.EventArgs e) { ListView.SelectedListViewItemCollection items = this.lvObjects.SelectedItems; if (items.Count > 0) { ListViewItem item = items[0]; this.process.Navigator.SetNext((PdfObject)item.Tag); ActivateTab((PdfObject)item.Tag); } } private void lvPages_SelectedIndexChanged(object sender, System.EventArgs e) { ListView.SelectedListViewItemCollection items = this.lvPages.SelectedItems; if (items.Count > 0) { ListViewItem item = items[0]; this.process.Navigator.SetNext((PdfObject)item.Tag); ActivateTab((PdfObject)item.Tag); } } private void tbcMain_SelectedIndexChanged(object sender, System.EventArgs e) { ActivateTab((PdfObject)Process.Navigator.Current); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Wintellect.PowerCollections; public class Event : IComparable { public DateTime date; public String title; public String location; public Event(DateTime date, String title, String location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + title); if (location != null && location != "") toString.Append(" | " + location); return toString.ToString(); } } public class Program { public static StringBuilder output = new StringBuilder(); public static EventHolder events = new EventHolder(); static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } public class EventHolder { MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); byTitle.Add(title.ToLower(), newEvent); byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in byTitle[title]) { removed++; byDate.Remove(eventToRemove); } byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.VieweventsToShow = byDate.RangeFrom(new Event(date, "", ""), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); switch (command[0]) { case 'A': AddEvent(command); return true; case 'D': DeleteEvents(command); return true; case 'L': ListEvents(command); return true; default: return false; } } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = ""; } else { eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApiVersionDefaultOperations operations. /// </summary> internal partial class ApiVersionDefaultOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionDefaultOperations { /// <summary> /// Initializes a new instance of the ApiVersionDefaultOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApiVersionDefaultOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalNotProvidedValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPathGlobalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerGlobalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class FindTests { private static void RunTest(Action<X509Certificate2Collection> test) { RunTest((msCer, pfxCer, col1) => test(col1)); } private static void RunTest(Action<X509Certificate2, X509Certificate2, X509Certificate2Collection> test) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection col1 = new X509Certificate2Collection(new[] { msCer, pfxCer }); test(msCer, pfxCer, col1); } } private static void RunExceptionTest<TException>(X509FindType findType, object findValue) where TException : Exception { RunTest( (msCer, pfxCer, col1) => { Assert.Throws<TException>(() => col1.Find(findType, findValue, validOnly: false)); }); } private static void RunZeroMatchTest(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); Assert.Equal(0, col2.Count); }); } private static void RunSingleMatchTest_MsCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(msCer, col1, findType, findValue); }); } private static void RunSingleMatchTest_PfxCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(pfxCer, col1, findType, findValue); }); } private static void EvaluateSingleMatch( X509Certificate2 expected, X509Certificate2Collection col1, X509FindType findType, object findValue) { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); Assert.Equal(1, col2.Count); byte[] serialNumber; using (X509Certificate2 match = col2[0]) { Assert.Equal(expected, match); Assert.NotSame(expected, match); // FriendlyName is Windows-only. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Verify that the find result and original are linked, not just equal. match.FriendlyName = "HAHA"; Assert.Equal("HAHA", expected.FriendlyName); } serialNumber = match.GetSerialNumber(); } // Check that disposing match didn't dispose expected Assert.Equal(serialNumber, expected.GetSerialNumber()); } [Theory] [MemberData(nameof(GenerateInvalidInputs))] public static void FindWithWrongTypeValue(X509FindType findType, Type badValueType) { object badValue; if (badValueType == typeof(object)) { badValue = new object(); } else if (badValueType == typeof(DateTime)) { badValue = DateTime.Now; } else if (badValueType == typeof(byte[])) { badValue = Array.Empty<byte>(); } else if (badValueType == typeof(string)) { badValue = "Hello, world"; } else { throw new InvalidOperationException("No creator exists for type " + badValueType); } RunExceptionTest<CryptographicException>(findType, badValue); } [Theory] [MemberData(nameof(GenerateInvalidOidInputs))] public static void FindWithBadOids(X509FindType findType, string badOid) { RunExceptionTest<ArgumentException>(findType, badOid); } [Fact] public static void FindByNullName() { RunExceptionTest<ArgumentNullException>(X509FindType.FindBySubjectName, null); } [Fact] public static void FindByInvalidThumbprint() { RunZeroMatchTest(X509FindType.FindByThumbprint, "Nothing"); } [Fact] public static void FindByInvalidThumbprint_RightLength() { RunZeroMatchTest(X509FindType.FindByThumbprint, "ffffffffffffffffffffffffffffffffffffffff"); } [Fact] public static void FindByValidThumbprint() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( pfxCer, col1, X509FindType.FindByThumbprint, pfxCer.Thumbprint); }); } [Theory] [InlineData(false)] [InlineData(true)] public static void FindByValidThumbprint_ValidOnly(bool validOnly) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { var col1 = new X509Certificate2Collection(msCer); X509Certificate2Collection col2 = col1.Find(X509FindType.FindByThumbprint, msCer.Thumbprint, validOnly); // The certificate is expired. Unless we invent time travel // (or roll the computer clock back significantly), the validOnly // criteria should filter it out. // // This test runs both ways to make sure that the precondition of // "would match otherwise" is met (in the validOnly=false case it is // effectively the same as FindByValidThumbprint, but does less inspection) int expectedMatchCount = validOnly ? 0 : 1; Assert.Equal(expectedMatchCount, col2.Count); if (!validOnly) { // Double check that turning on validOnly doesn't prevent the cloning // behavior of Find. using (X509Certificate2 match = col2[0]) { Assert.Equal(msCer, match); Assert.NotSame(msCer, match); } } } } [Theory] [InlineData("Nothing")] [InlineData("US, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] public static void TestSubjectName_NoMatch(string subjectQualifier) { RunZeroMatchTest(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("Microsoft Corporation")] [InlineData("MOPR")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] [InlineData("us, washington, redmond, microsoft corporation, mopr, microsoft corporation")] public static void TestSubjectName_Match(string subjectQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("ou=mopr, o=microsoft corporation")] [InlineData("CN=Microsoft Corporation")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedSubjectName_NoMatch(string distinguishedSubjectName) { RunZeroMatchTest(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Theory] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft corporation, ou=mopr, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedSubjectName_Match(string distinguishedSubjectName) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Fact] public static void TestIssuerName_NoMatch() { RunZeroMatchTest(X509FindType.FindByIssuerName, "Nothing"); } [Theory] [InlineData("Microsoft Code Signing PCA")] [InlineData("Microsoft Corporation")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, Microsoft Code Signing PCA")] [InlineData("us, washington, redmond, microsoft corporation, microsoft code signing pca")] public static void TestIssuerName_Match(string issuerQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerName, issuerQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("CN=Microsoft Code Signing PCA")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedIssuerName_NoMatch(string issuerDistinguishedName) { RunZeroMatchTest(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Theory] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft Code signing pca, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft code signing pca, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedIssuerName_Match(string issuerDistinguishedName) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Fact] public static void TestByTimeValid_Before() { RunTest( (msCer, pfxCer, col1) => { DateTime earliest = new[] { msCer.NotBefore, pfxCer.NotBefore }.Min(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, earliest - TimeSpan.FromSeconds(1), validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestByTimeValid_After() { RunTest( (msCer, pfxCer, col1) => { DateTime latest = new[] { msCer.NotAfter, pfxCer.NotAfter }.Max(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, latest + TimeSpan.FromSeconds(1), validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestByTimeValid_Between() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); DateTime noMatchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, noMatchTime, validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestByTimeValid_Match() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( msCer, col1, X509FindType.FindByTimeValid, msCer.NotBefore + TimeSpan.FromSeconds(1)); }); } [Fact] public static void TestFindByTimeNotYetValid_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the latest NotBefore, so one is valid, the other is not yet valid. DateTime matchTime = latestNotBefore - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, matchTime, validOnly: false); Assert.Equal(1, col2.Count); }); } [Fact] public static void TestFindByTimeNotYetValid_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the latest NotBefore, both certificates are time-valid DateTime noMatchTime = latestNotBefore + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, noMatchTime, validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestFindByTimeExpired_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the earliest NotAfter, so one is valid, the other is no longer valid. DateTime matchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, matchTime, validOnly: false); Assert.Equal(1, col2.Count); }); } [Fact] public static void TestFindByTimeExpired_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the earliest NotAfter, so both certificates are valid DateTime noMatchTime = earliestNotAfter - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, noMatchTime, validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestBySerialNumber_Decimal() { // Decimal string is an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "284069184166497622998429950103047369500"); } [Fact] public static void TestBySerialNumber_DecimalLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "000" + "284069184166497622998429950103047369500"); } [Theory] [InlineData("1137338006039264696476027508428304567989436592")] // Leading zeroes are fine/ignored [InlineData("0001137338006039264696476027508428304567989436592")] // Compat: Minus signs are ignored [InlineData("-1137338006039264696476027508428304567989436592")] public static void TestBySerialNumber_Decimal_CertB(string serialNumber) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, serialNumber); } [Fact] public static void TestBySerialNumber_Hex() { // Hex string is also an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_HexIgnoreCase() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "d5b5bc1c458a558845bff51cb4dff31c"); } [Fact] public static void TestBySerialNumber_HexLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "0000" + "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_NoMatch() { RunZeroMatchTest( X509FindType.FindBySerialNumber, "23000000B011AF0A8BD03B9FDD0001000000B0"); } [Theory] [MemberData(nameof(GenerateWorkingFauxSerialNumbers))] public static void TestBySerialNumber_Match_NonDecimalInput(string input) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, input); } [Fact] public static void TestByExtension_FriendlyName() { // Cannot just say "Enhanced Key Usage" here because the extension name is localized. // Instead, look it up via the OID. RunSingleMatchTest_MsCer(X509FindType.FindByExtension, new Oid("2.5.29.37").FriendlyName); } [Fact] public static void TestByExtension_OidValue() { RunSingleMatchTest_MsCer(X509FindType.FindByExtension, "2.5.29.37"); } [Fact] // Compat: Non-ASCII digits don't throw, but don't match. public static void TestByExtension_OidValue_ArabicNumericChar() { // This uses the same OID as TestByExtension_OidValue, but uses "Arabic-Indic Digit Two" instead // of "Digit Two" in the third segment. This value can't possibly ever match, but it doesn't throw // as an illegal OID value. RunZeroMatchTest(X509FindType.FindByExtension, "2.5.\u06629.37"); } [Fact] public static void TestByExtension_UnknownFriendlyName() { RunExceptionTest<ArgumentException>(X509FindType.FindByExtension, "BOGUS"); } [Fact] public static void TestByExtension_NoMatch() { RunZeroMatchTest(X509FindType.FindByExtension, "2.9"); } [Fact] public static void TestBySubjectKeyIdentifier_UsingFallback() { RunSingleMatchTest_PfxCer( X509FindType.FindBySubjectKeyIdentifier, "B4D738B2D4978AFF290A0B02987BABD114FEE9C7"); } [Theory] [InlineData("5971A65A334DDA980780FF841EBE87F9723241F2")] // Whitespace is allowed [InlineData("59 71\tA6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")] // Lots of kinds of whitespace (does not include \u000b or \u000c, because those // produce a build warning (which becomes an error): // EXEC : warning : '(not included here)', hexadecimal value 0x0C, is an invalid character. [InlineData( "59\u000971\u000aA6\u30005A\u205f33\u000d4D\u0020DA\u008598\u00a007\u1680" + "80\u2000FF\u200184\u20021E\u2003BE\u200487\u2005F9\u200672\u200732\u2008" + "4\u20091\u200aF\u20282\u2029\u202f")] // Non-byte-aligned whitespace is allowed [InlineData("597 1A6 5A3 34D DA9 807 80F F84 1EB E87 F97 232 41F 2")] // Non-symmetric whitespace is allowed [InlineData(" 5971A65 A334DDA980780FF84 1EBE87F97 23241F 2")] public static void TestBySubjectKeyIdentifier_ExtensionPresent(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Theory] // Compat: Lone trailing nybbles are ignored [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")] // Compat: Lone trailing nybbles are ignored, even if not hex [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")] // Compat: A non-hex character as the high nybble makes that nybble be F [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 p9 72 32 41 F2")] // Compat: A non-hex character as the low nybble makes the whole byte FF. [InlineData("59 71 A6 5A 33 4D DA 98 07 80 0p 84 1E BE 87 F9 72 32 41 F2")] public static void TestBySubjectKeyIdentifier_Compat(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch() { RunZeroMatchTest(X509FindType.FindBySubjectKeyIdentifier, ""); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch_RightLength() { RunZeroMatchTest( X509FindType.FindBySubjectKeyIdentifier, "5971A65A334DDA980780FF841EBE87F9723241F0"); } [Fact] public static void TestByApplicationPolicy_MatchAll() { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", false); Assert.Equal(2, results.Count); Assert.True(results.Contains(msCer)); Assert.True(results.Contains(pfxCer)); foreach (X509Certificate2 match in results) { match.Dispose(); } }); } [Fact] public static void TestByApplicationPolicy_NoPolicyAlwaysMatches() { // PfxCer doesn't have any application policies which means it's good for all usages (even nonsensical ones.) RunSingleMatchTest_PfxCer(X509FindType.FindByApplicationPolicy, "2.2"); } [Fact] public static void TestByApplicationPolicy_NoMatch() { RunTest( (msCer, pfxCer, col1) => { // Per TestByApplicationPolicy_NoPolicyAlwaysMatches we know that pfxCer will match, so remove it. col1.Remove(pfxCer); X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "2.2", false); Assert.Equal(0, results.Count); }); } [Fact] public static void TestByCertificatePolicies_MatchA() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.18.19"); } } [Fact] public static void TestByCertificatePolicies_MatchB() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.32.33"); } } [Fact] public static void TestByCertificatePolicies_NoMatch() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { X509Certificate2Collection col1 = new X509Certificate2Collection(policyCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByCertificatePolicy, "2.999", false); Assert.Equal(0, results.Count); } } [Fact] public static void TestByTemplate_MatchA() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "Hello"); } } [Fact] public static void TestByTemplate_MatchB() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "2.7.8.9"); } } [Fact] public static void TestByTemplate_NoMatch() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { X509Certificate2Collection col1 = new X509Certificate2Collection(templatedCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByTemplateName, "2.999", false); Assert.Equal(0, results.Count); } } [Theory] [InlineData((int)0x80)] [InlineData((uint)0x80)] [InlineData(X509KeyUsageFlags.DigitalSignature)] [InlineData("DigitalSignature")] [InlineData("digitalSignature")] public static void TestFindByKeyUsage_Match(object matchCriteria) { TestFindByKeyUsage(true, matchCriteria); } [Theory] [InlineData((int)0x20)] [InlineData((uint)0x20)] [InlineData(X509KeyUsageFlags.KeyEncipherment)] [InlineData("KeyEncipherment")] [InlineData("KEYEncipherment")] public static void TestFindByKeyUsage_NoMatch(object matchCriteria) { TestFindByKeyUsage(false, matchCriteria); } private static void TestFindByKeyUsage(bool shouldMatch, object matchCriteria) { using (var noKeyUsages = new X509Certificate2(TestData.MsCertificate)) using (var noKeyUsages2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) using (var keyUsages = new X509Certificate2(Path.Combine("TestData", "microsoft.cer"))) { var coll = new X509Certificate2Collection { noKeyUsages, noKeyUsages2, keyUsages, }; X509Certificate2Collection results = coll.Find(X509FindType.FindByKeyUsage, matchCriteria, false); // The two certificates with no KeyUsages extension will always match, the real question is about the third. int matchCount = shouldMatch ? 3 : 2; Assert.Equal(matchCount, results.Count); if (shouldMatch) { bool found = false; foreach (X509Certificate2 cert in results) { if (keyUsages.Equals(cert)) { Assert.NotSame(cert, keyUsages); found = true; break; } } Assert.True(found, "Certificate with key usages was found in the collection"); } else { Assert.False(results.Contains(keyUsages), "KeyUsages certificate is not present in the collection"); } } } public static IEnumerable<object[]> GenerateWorkingFauxSerialNumbers { get { const string seedDec = "1137338006039264696476027508428304567989436592"; string[] nonHexWords = { "wow", "its", "tough", "using", "only", "high", "lttr", "vlus" }; string gluedTogether = string.Join("", nonHexWords); string withSpaces = string.Join(" ", nonHexWords); yield return new object[] { gluedTogether + seedDec }; yield return new object[] { seedDec + gluedTogether }; yield return new object[] { withSpaces + seedDec }; yield return new object[] { seedDec + withSpaces }; StringBuilder builderDec = new StringBuilder(512); int offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; } builderDec.Append(nonHexWords[i]); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; builderDec.Length = 0; offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; builderDec.Append(' '); } builderDec.Append(nonHexWords[i]); builderDec.Append(' '); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; } } public static IEnumerable<object[]> GenerateInvalidOidInputs { get { X509FindType[] oidTypes = { X509FindType.FindByApplicationPolicy, }; string[] invalidOids = { "", "This Is Not An Oid", "1", "95.22", ".1", "1..1", "1.", "1.2.", }; List<object[]> combinations = new List<object[]>(oidTypes.Length * invalidOids.Length); for (int findTypeIndex = 0; findTypeIndex < oidTypes.Length; findTypeIndex++) { for (int oidIndex = 0; oidIndex < invalidOids.Length; oidIndex++) { combinations.Add(new object[] { oidTypes[findTypeIndex], invalidOids[oidIndex] }); } } return combinations; } } public static IEnumerable<object[]> GenerateInvalidInputs { get { Type[] allTypes = { typeof(object), typeof(DateTime), typeof(byte[]), typeof(string), }; Tuple<X509FindType, Type>[] legalInputs = { Tuple.Create(X509FindType.FindByThumbprint, typeof(string)), Tuple.Create(X509FindType.FindBySubjectName, typeof(string)), Tuple.Create(X509FindType.FindBySubjectDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindBySerialNumber, typeof(string)), Tuple.Create(X509FindType.FindByTimeValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeNotYetValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeExpired, typeof(DateTime)), Tuple.Create(X509FindType.FindByTemplateName, typeof(string)), Tuple.Create(X509FindType.FindByApplicationPolicy, typeof(string)), Tuple.Create(X509FindType.FindByCertificatePolicy, typeof(string)), Tuple.Create(X509FindType.FindByExtension, typeof(string)), // KeyUsage supports int/uint/KeyUsage/string, but only one of those is in allTypes. Tuple.Create(X509FindType.FindByKeyUsage, typeof(string)), Tuple.Create(X509FindType.FindBySubjectKeyIdentifier, typeof(string)), }; List<object[]> invalidCombinations = new List<object[]>(); for (int findTypesIndex = 0; findTypesIndex < legalInputs.Length; findTypesIndex++) { Tuple<X509FindType, Type> tuple = legalInputs[findTypesIndex]; for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) { Type t = allTypes[typeIndex]; if (t != tuple.Item2) { invalidCombinations.Add(new object[] { tuple.Item1, t }); } } } return invalidCombinations; } } } }
//------------------------------------------------------------------------------ // <copyright file="HtmlControl.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * HtmlControl.cs * * Copyright (c) 2000 Microsoft Corporation */ namespace System.Web.UI.HtmlControls { using System; using System.Globalization; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.IO; using System.Web.Util; using System.Web.UI; using AttributeCollection = System.Web.UI.AttributeCollection; using System.Security.Permissions; /* * An abstract base class representing an intrinsic Html tag that * is not represented by both a begin and end tag, for example * INPUT or IMG. */ /// <devdoc> /// <para> /// The <see langword='HtmlControl'/> /// class defines the methods, properties, and events /// common to all HTML Server controls in the Web Forms page framework. /// </para> /// </devdoc> [ Designer("System.Web.UI.Design.HtmlIntrinsicControlDesigner, " + AssemblyRef.SystemDesign), ToolboxItem(false) ] abstract public class HtmlControl : Control, IAttributeAccessor { internal string _tagName; private AttributeCollection _attributes; /// <devdoc> /// </devdoc> protected HtmlControl() : this("span") { } /// <devdoc> /// </devdoc> protected HtmlControl(string tag) { _tagName = tag; } /* * Access to collection of Attributes. */ /// <devdoc> /// <para> /// Gets all attribute name/value pairs expressed on a /// server control tag within a selected ASP.NET page. /// </para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public AttributeCollection Attributes { get { if (_attributes == null) _attributes = new AttributeCollection(ViewState); return _attributes; } } /* * Access to collection of styles. */ /// <devdoc> /// <para> /// Gets all /// cascading style sheet (CSS) properties that /// are applied /// to a specified HTML Server control in an .aspx /// file. /// </para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public CssStyleCollection Style { get { return Attributes.CssStyle; } } /* * Property to get name of tag. */ /// <devdoc> /// <para> /// Gets the element name of a tag that contains a runat=server /// attribute/value pair. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public virtual string TagName { get { return _tagName;} } /* * Disabled property. */ /// <devdoc> /// <para> /// Gets or sets /// a value indicating whether ---- attribute is included when a server /// control is rendered. /// </para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), TypeConverter(typeof(MinimizableAttributeTypeConverter)) ] public bool Disabled { get { string s = Attributes["disabled"]; return((s != null) ? (s.Equals("disabled")) : false); } set { if (value) Attributes["disabled"] = "disabled"; else Attributes["disabled"] = null; } } /// <devdoc> /// </devdoc> /// <internalonly/> protected override bool ViewStateIgnoresCase { get { return true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override ControlCollection CreateControlCollection() { return new EmptyControlCollection(this); } /* * Render the control into the given writer. */ /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void Render(HtmlTextWriter writer) { RenderBeginTag(writer); } /* * Render only the attributes, attr1=value1 attr2=value2 ... */ /// <internalonly/> /// <devdoc> /// </devdoc> protected virtual void RenderAttributes(HtmlTextWriter writer) { if (ID != null) writer.WriteAttribute("id", ClientID); Attributes.Render(writer); } /* * Render the begin tag and its attributes, &lt;TAGNAME attr1=value1 attr2=value2&gt;. */ /// <internalonly/> /// <devdoc> /// </devdoc> protected virtual void RenderBeginTag(HtmlTextWriter writer) { writer.WriteBeginTag(TagName); RenderAttributes(writer); writer.Write(HtmlTextWriter.TagRightChar); } /* * HtmlControls support generic access to Attributes. */ /// <internalonly/> /// <devdoc> /// </devdoc> string IAttributeAccessor.GetAttribute(string name) { return GetAttribute(name); } /// <internalonly/> /// <devdoc> /// </devdoc> protected virtual string GetAttribute(string name) { return Attributes[name]; } /* * HtmlControls support generic access to Attributes. */ /// <internalonly/> /// <devdoc> /// </devdoc> void IAttributeAccessor.SetAttribute(string name, string value) { SetAttribute(name, value); } /// <internalonly/> /// <devdoc> /// </devdoc> protected virtual void SetAttribute(string name, string value) { Attributes[name] = value; } internal void PreProcessRelativeReferenceAttribute(HtmlTextWriter writer, string attribName) { string url = Attributes[attribName]; // Don't do anything if it's not specified if (String.IsNullOrEmpty(url)) return; try { url = ResolveClientUrl(url); } catch (Exception e) { throw new HttpException(SR.GetString(SR.Property_Had_Malformed_Url, attribName, e.Message)); } writer.WriteAttribute(attribName, url); Attributes.Remove(attribName); } internal static string MapStringAttributeToString(string s) { // If it's an empty string, change it to null if (s != null && s.Length == 0) return null; // Otherwise, just return the input return s; } internal static string MapIntegerAttributeToString(int n) { // If it's -1, change it to null if (n == -1) return null; // Otherwise, convert the integer to a string return n.ToString(NumberFormatInfo.InvariantInfo); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Allows developers to view the base data types as ** an arbitrary array of bits. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. // // Only statics, does not need to be marked with the serializable attribute public static class BitConverter { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; #endif // Converts a byte into an array of bytes with length one. public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False ); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts a short into an array of bytes with length // two. public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed(byte* b = &bytes[0]) *((short*)b) = value; return bytes; } // Converts an int into an array of bytes with length // four. public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed(byte* b = &bytes[0]) *((int*)b) = value; return bytes; } // Converts a long into an array of bytes with length // eight. public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed(byte* b = &bytes[0]) *((long*)b) = value; return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } // Converts a float into an array of bytes with length // four. public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } // Converts a double into an array of bytes with length // eight. public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } // Converts an array of bytes into a char. public static char ToChar(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint)startIndex >= value.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (startIndex > value.Length - 2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); return (char)ToInt16(value, startIndex); } // Converts an array of bytes into a short. public static unsafe short ToInt16(byte[] value, int startIndex) { if( value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (startIndex > value.Length -2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 2 == 0) { // data is aligned return *((short *) pbyte); } else { if( IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)) ; } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } } // Converts an array of bytes into an int. public static unsafe int ToInt32 (byte[] value, int startIndex) { if( value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (startIndex > value.Length -4) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 4 == 0) { // data is aligned return *((int *) pbyte); } else { if( IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } } // Converts an array of bytes into a long. public static unsafe long ToInt64 (byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (startIndex > value.Length -8) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 8 == 0) { // data is aligned return *((long *) pbyte); } else { if( IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } } // Converts an array of bytes into an ushort. // [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (startIndex > value.Length - 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ushort)ToInt16(value, startIndex); } // Converts an array of bytes into an uint. // [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (startIndex > value.Length - 4) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (uint)ToInt32(value, startIndex); } // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (startIndex > value.Length - 8) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ulong)ToInt64(value, startIndex); } // Converts an array of bytes into a float. unsafe public static float ToSingle (byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (startIndex > value.Length - 4) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); int val = ToInt32(value, startIndex); return *(float*)&val; } // Converts an array of bytes into a double. unsafe public static double ToDouble (byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (startIndex > value.Length - 8) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static char GetHexValue(int i) { Debug.Assert( i >=0 && i <16, "i is out of range."); if (i<10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static String ToString (byte[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array. throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } if (startIndex > value.Length - length) { throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall")); } Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (Int32.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3))); } int chArrayLength = length * 3; char[] chArray = new char[chArrayLength]; int i = 0; int index = startIndex; for (i = 0; i < chArrayLength; i += 3) { byte b = value[index++]; chArray[i]= GetHexValue(b/16); chArray[i+1] = GetHexValue(b%16); chArray[i+2] = '-'; } // We don't need the last '-' character return new String(chArray, 0, chArray.Length - 1); } // Converts an array of bytes into a String. public static String ToString(byte [] value) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } // Converts an array of bytes into a String. public static String ToString (byte [] value, int startIndex) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean(byte[] value, int startIndex) { if (value==null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (startIndex > value.Length - 1) throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); return (value[startIndex]==0)?false:true; } public static unsafe long DoubleToInt64Bits(double value) { return *((long *)&value); } public static unsafe double Int64BitsToDouble(long value) { return *((double*)&value); } public static unsafe int SingleToInt32Bits(float value) { return *((int*)&value); } public static unsafe float Int32BitsToSingle(int value) { return *((float*)&value); } } }
/* * Copyright (c) 2007-2009, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Diagnostics; using System.Threading; using System.Text; namespace OpenMetaverse.Voice { public partial class VoiceGateway { public delegate void DaemonRunningCallback(); public delegate void DaemonExitedCallback(); public delegate void DaemonCouldntRunCallback(); public delegate void DaemonConnectedCallback(); public delegate void DaemonDisconnectedCallback(); public delegate void DaemonCouldntConnectCallback(); public event DaemonRunningCallback OnDaemonRunning; public event DaemonExitedCallback OnDaemonExited; public event DaemonCouldntRunCallback OnDaemonCouldntRun; public event DaemonConnectedCallback OnDaemonConnected; public event DaemonDisconnectedCallback OnDaemonDisconnected; public event DaemonCouldntConnectCallback OnDaemonCouldntConnect; public bool DaemonIsRunning { get { return daemonIsRunning; } } public bool DaemonIsConnected { get { return daemonIsConnected; } } public int RequestId { get { return requestId; } } protected Process daemonProcess; protected ManualResetEvent daemonLoopSignal = new ManualResetEvent(false); protected TCPPipe daemonPipe; protected bool daemonIsRunning = false; protected bool daemonIsConnected = false; protected int requestId = 0; #region Daemon Management /// <summary> /// Starts a thread that keeps the daemon running /// </summary> /// <param name="path"></param> /// <param name="args"></param> public void StartDaemon(string path, string args) { StopDaemon(); daemonLoopSignal.Set(); Thread thread = new Thread(new ThreadStart(delegate() { while (daemonLoopSignal.WaitOne(500, false)) { daemonProcess = new Process(); daemonProcess.StartInfo.FileName = path; daemonProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(path); daemonProcess.StartInfo.Arguments = args; daemonProcess.StartInfo.UseShellExecute = false; if (Environment.OSVersion.Platform == PlatformID.Unix) { string ldPath = string.Empty; try { ldPath = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH"); } catch { } string newLdPath = daemonProcess.StartInfo.WorkingDirectory; if (!string.IsNullOrEmpty(ldPath)) newLdPath += ":" + ldPath; daemonProcess.StartInfo.EnvironmentVariables.Add("LD_LIBRARY_PATH", newLdPath); } Logger.DebugLog("Voice folder: " + daemonProcess.StartInfo.WorkingDirectory); Logger.DebugLog(path + " " + args); bool ok = true; if (!File.Exists(path)) ok = false; if (ok) { // Attempt to start the process if (!daemonProcess.Start()) ok = false; } if (!ok) { daemonIsRunning = false; daemonLoopSignal.Reset(); if (OnDaemonCouldntRun != null) { try { OnDaemonCouldntRun(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } return; } else { Thread.Sleep(2000); daemonIsRunning = true; if (OnDaemonRunning != null) { try { OnDaemonRunning(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } Logger.DebugLog("Started voice daemon, waiting for exit..."); daemonProcess.WaitForExit(); Logger.DebugLog("Voice daemon exited"); daemonIsRunning = false; if (OnDaemonExited != null) { try { OnDaemonExited(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } } } })); thread.Start(); } /// <summary> /// Stops the daemon and the thread keeping it running /// </summary> public void StopDaemon() { daemonLoopSignal.Reset(); if (daemonProcess != null) { try { daemonProcess.Kill(); } catch (InvalidOperationException ex) { Logger.Log("Failed to stop the voice daemon", Helpers.LogLevel.Error, ex); } } } /// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="port"></param> /// <returns></returns> public bool ConnectToDaemon(string address, int port) { daemonIsConnected = false; daemonPipe = new TCPPipe(); daemonPipe.OnDisconnected += delegate(SocketException e) { if (OnDaemonDisconnected != null) { try { OnDaemonDisconnected(); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, null, ex); } } }; daemonPipe.OnReceiveLine += new TCPPipe.OnReceiveLineCallback(daemonPipe_OnReceiveLine); SocketException se = daemonPipe.Connect(address, port); if (se == null) { daemonIsConnected = true; if (OnDaemonConnected != null) { try { OnDaemonConnected(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } return true; } else { daemonIsConnected = false; if (OnDaemonCouldntConnect != null) { try { OnDaemonCouldntConnect(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } Logger.Log("Voice daemon connection failed: " + se.Message, Helpers.LogLevel.Error); return false; } } #endregion Daemon Management public int Request(string action) { return Request(action, null); } public int Request(string action, string requestXML) { int returnId = requestId; if (daemonIsConnected) { StringBuilder sb = new StringBuilder(); sb.Append(String.Format("<Request requestId=\"{0}\" action=\"{1}\"", requestId++, action)); if (string.IsNullOrEmpty(requestXML)) { sb.Append(" />"); } else { sb.Append(">"); sb.Append(requestXML); sb.Append("</Request>"); } sb.Append("\n\n\n"); #if DEBUG Logger.Log("Request: " + sb.ToString(), Helpers.LogLevel.Debug); #endif try { daemonPipe.SendData(Encoding.ASCII.GetBytes(sb.ToString())); } catch { returnId = -1; } return returnId; } else { return -1; } } public static string MakeXML(string name, string text) { if (string.IsNullOrEmpty(text)) return string.Format("<{0} />", name); else return string.Format("<{0}>{1}</{0}>", name, text); } private void daemonPipe_OnReceiveLine(string line) { #if DEBUG Logger.Log(line, Helpers.LogLevel.Debug); #endif if (line.Substring(0, 10) == "<Response ") { VoiceResponse rsp = null; try { rsp = (VoiceResponse)ResponseSerializer.Deserialize(new StringReader(line)); } catch (Exception e) { Logger.Log("Failed to deserialize voice daemon response", Helpers.LogLevel.Error, e); return; } ResponseType genericResponse = ResponseType.None; switch (rsp.Action) { // These first responses carry useful information beyond simple status, // so they each have a specific Event. case "Connector.Create.1": if (OnConnectorCreateResponse != null) { OnConnectorCreateResponse( rsp.InputXml.Request, new VoiceConnectorEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.VersionID, rsp.Results.ConnectorHandle)); } break; case "Aux.GetCaptureDevices.1": inputDevices = new List<string>(); foreach (CaptureDevice device in rsp.Results.CaptureDevices) inputDevices.Add(device.Device); currentCaptureDevice = rsp.Results.CurrentCaptureDevice.Device; if (OnAuxGetCaptureDevicesResponse != null && rsp.Results.CaptureDevices.Count > 0) { OnAuxGetCaptureDevicesResponse( rsp.InputXml.Request, new VoiceDevicesEventArgs( ResponseType.GetCaptureDevices, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.CurrentCaptureDevice.Device, inputDevices)); } break; case "Aux.GetRenderDevices.1": outputDevices = new List<string>(); foreach (RenderDevice device in rsp.Results.RenderDevices) outputDevices.Add(device.Device); currentPlaybackDevice = rsp.Results.CurrentRenderDevice.Device; if (OnAuxGetRenderDevicesResponse != null) { OnAuxGetRenderDevicesResponse( rsp.InputXml.Request, new VoiceDevicesEventArgs( ResponseType.GetCaptureDevices, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.CurrentRenderDevice.Device, outputDevices)); } break; case "Account.Login.1": if (OnAccountLoginResponse != null) { OnAccountLoginResponse(rsp.InputXml.Request, new VoiceAccountEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.AccountHandle)); } break; case "Session.Create.1": if (OnSessionCreateResponse != null) { OnSessionCreateResponse( rsp.InputXml.Request, new VoiceSessionEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.SessionHandle)); } break; // All the remaining responses below this point just report status, // so they all share the same Event. Most are useful only for // detecting coding errors. case "Connector.InitiateShutdown.1": genericResponse = ResponseType.ConnectorInitiateShutdown; break; case "Aux.SetRenderDevice.1": genericResponse = ResponseType.SetRenderDevice; break; case "Connector.MuteLocalMic.1": genericResponse = ResponseType.MuteLocalMic; break; case "Connector.MuteLocalSpeaker.1": genericResponse = ResponseType.MuteLocalSpeaker; break; case "Connector.SetLocalMicVolume.1": genericResponse = ResponseType.SetLocalMicVolume; break; case "Connector.SetLocalSpeakerVolume.1": genericResponse = ResponseType.SetLocalSpeakerVolume; break; case "Aux.SetCaptureDevice.1": genericResponse = ResponseType.SetCaptureDevice; break; case "Session.RenderAudioStart.1": genericResponse = ResponseType.RenderAudioStart; break; case "Session.RenderAudioStop.1": genericResponse = ResponseType.RenderAudioStop; break; case "Aux.CaptureAudioStart.1": genericResponse = ResponseType.CaptureAudioStart; break; case "Aux.CaptureAudioStop.1": genericResponse = ResponseType.CaptureAudioStop; break; case "Aux.SetMicLevel.1": genericResponse = ResponseType.SetMicLevel; break; case "Aux.SetSpeakerLevel.1": genericResponse = ResponseType.SetSpeakerLevel; break; case "Account.Logout.1": genericResponse = ResponseType.AccountLogout; break; case "Session.Connect.1": genericResponse = ResponseType.SessionConnect; break; case "Session.Terminate.1": genericResponse = ResponseType.SessionTerminate; break; case "Session.SetParticipantVolumeForMe.1": genericResponse = ResponseType.SetParticipantVolumeForMe; break; case "Session.SetParticipantMuteForMe.1": genericResponse = ResponseType.SetParticipantMuteForMe; break; case "Session.Set3DPosition.1": genericResponse = ResponseType.Set3DPosition; break; default: Logger.Log("Unimplemented response from the voice daemon: " + line, Helpers.LogLevel.Error); break; } // Send the Response Event for all the simple cases. if (genericResponse != ResponseType.None && OnVoiceResponse != null) { OnVoiceResponse(rsp.InputXml.Request, new VoiceResponseEventArgs( genericResponse, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString)); } } else if (line.Substring(0, 7) == "<Event ") { VoiceEvent evt = null; try { evt = (VoiceEvent)EventSerializer.Deserialize(new StringReader(line)); } catch (Exception e) { Logger.Log("Failed to deserialize voice daemon event", Helpers.LogLevel.Error, e); return; } switch (evt.Type) { case "LoginStateChangeEvent": case "AccountLoginStateChangeEvent": if (OnAccountLoginStateChangeEvent != null) { OnAccountLoginStateChangeEvent(this, new AccountLoginStateChangeEventArgs( evt.AccountHandle, int.Parse(evt.StatusCode), evt.StatusString, (LoginState)int.Parse(evt.State))); } break; case "SessionNewEvent": if (OnSessionNewEvent != null) { OnSessionNewEvent(this, new NewSessionEventArgs( evt.AccountHandle, evt.SessionHandle, evt.URI, bool.Parse(evt.IsChannel), evt.Name, evt.AudioMedia)); } break; case "SessionStateChangeEvent": if (OnSessionStateChangeEvent != null) { OnSessionStateChangeEvent(this, new SessionStateChangeEventArgs( evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (SessionState)int.Parse(evt.State), evt.URI, bool.Parse(evt.IsChannel), evt.ChannelName)); } break; case "ParticipantAddedEvent": Logger.Log("Add participant " + evt.ParticipantUri, Helpers.LogLevel.Debug); if (OnSessionParticipantAddedEvent != null) { OnSessionParticipantAddedEvent(this, new ParticipantAddedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.ParticipantUri, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType), evt.Application)); } break; case "ParticipantRemovedEvent": if (OnSessionParticipantRemovedEvent != null) { OnSessionParticipantRemovedEvent(this, new ParticipantRemovedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.ParticipantUri, evt.AccountName, evt.Reason)); } break; case "ParticipantStateChangeEvent": // Useful in person-to-person calls if (OnSessionParticipantStateChangeEvent != null) { OnSessionParticipantStateChangeEvent(this, new ParticipantStateChangeEventArgs( evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (ParticipantState)int.Parse(evt.State), // Ringing, Connected, etc evt.ParticipantUri, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType))); } break; case "ParticipantPropertiesEvent": if (OnSessionParticipantPropertiesEvent != null) { OnSessionParticipantPropertiesEvent(this, new ParticipantPropertiesEventArgs( evt.SessionHandle, evt.ParticipantUri, bool.Parse(evt.IsLocallyMuted), bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy))); } break; case "ParticipantUpdatedEvent": if (OnSessionParticipantUpdatedEvent != null) { OnSessionParticipantUpdatedEvent(this, new ParticipantUpdatedEventArgs( evt.SessionHandle, evt.ParticipantUri, bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy))); } break; case "SessionGroupAddedEvent": if (OnSessionGroupAddedEvent != null) { OnSessionGroupAddedEvent(this, new SessionGroupAddedEventArgs( evt.AccountHandle, evt.SessionGroupHandle, evt.Type)); } break; case "SessionAddedEvent": if (OnSessionAddedEvent != null) { OnSessionAddedEvent(this, new SessionAddedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri, bool.Parse(evt.IsChannel), bool.Parse(evt.Incoming))); } break; case "SessionRemovedEvent": if (OnSessionRemovedEvent != null) { OnSessionRemovedEvent(this, new SessionRemovedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri)); } break; case "SessionUpdatedEvent": if (OnSessionRemovedEvent != null) { OnSessionUpdatedEvent(this, new SessionUpdatedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri, int.Parse(evt.IsMuted) != 0, int.Parse(evt.Volume), int.Parse(evt.TransmitEnabled) != 0, + int.Parse(evt.IsFocused) != 0)); } break; case "AuxAudioPropertiesEvent": if (OnAuxAudioPropertiesEvent != null) { OnAuxAudioPropertiesEvent(this, new AudioPropertiesEventArgs( bool.Parse(evt.MicIsActive), float.Parse(evt.MicEnergy), int.Parse(evt.MicVolume), int.Parse(evt.SpeakerVolume))); } break; case "SessionMediaEvent": if (OnSessionMediaEvent != null) { OnSessionMediaEvent(this, new SessionMediaEventArgs( evt.SessionHandle, bool.Parse(evt.HasText), bool.Parse(evt.HasAudio), bool.Parse(evt.HasVideo), bool.Parse(evt.Terminated))); } break; case "BuddyAndGroupListChangedEvent": // TODO * <AccountHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==</AccountHandle><Buddies /><Groups /> break; case "MediaStreamUpdatedEvent": // TODO <SessionGroupHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==_sg0</SessionGroupHandle> // <SessionHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==0</SessionHandle> //<StatusCode>0</StatusCode><StatusString /><State>1</State><Incoming>false</Incoming> break; default: Logger.Log("Unimplemented event from the voice daemon: " + line, Helpers.LogLevel.Error); break; } } else { Logger.Log("Unrecognized data from the voice daemon: " + line, Helpers.LogLevel.Error); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using DotJEM.AspNetCore.FluentRouting.Invoker.MSInternal; using DotJEM.AspNetCore.FluentRouting.Routing.Lambdas; namespace DotJEM.AspNetCore.FluentRouting.Invoker.Execution { public delegate void VoidActionExecutorDelegate(Delegate target, object[] parameters); public delegate object ActionExecutorDelegate(Delegate target, object[] parameters); public delegate LambdaExecutorAwaitable AsyncActionExecutorDelegate(Delegate target, object[] parameters); public interface ILambdaExecutorDelegateFactory { ActionExecutorDelegate Create(Delegate target); AsyncActionExecutorDelegate CreateAsync(Delegate target, CoercedAwaitableInfo coercedAwaitableInfo); } public class LambdaExecutorDelegateFactory : ILambdaExecutorDelegateFactory { public ActionExecutorDelegate Create(Delegate target) { // Parameters for the delegate: ParameterExpression targetParameter = Expression.Parameter(typeof(Delegate), "target"); ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); MethodCallExpression methodCall = CreateMethodCall(target, targetParameter, parametersParameter); // Create function if (methodCall.Type == typeof(void)) { //TODO: Void support for Action<T, ..> although we might be able to wrap that in a Func<Task> (async) //var lambda = Expression.Lambda<VoidMethodExecutor>(methodCall, targetParameter, parametersParameter); //var voidExecutor = lambda.Compile(); //return WrapVoidMethod(voidExecutor); return null; } // Create function // must coerce methodCall to match ActionExecutorDelegate signature UnaryExpression castMethodCall = Expression.Convert(methodCall, typeof(object)); Expression<ActionExecutorDelegate> lambda = Expression.Lambda<ActionExecutorDelegate>(castMethodCall, targetParameter, parametersParameter); return lambda.Compile(); } public AsyncActionExecutorDelegate CreateAsync(Delegate target, CoercedAwaitableInfo coercedAwaitableInfo) { // Parameters for the delegate: ParameterExpression targetParameter = Expression.Parameter(typeof(Delegate), "target"); ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); MethodCallExpression methodCall = CreateMethodCall(target, targetParameter, parametersParameter); // Using the method return value, construct an ObjectMethodExecutorAwaitable based on // the info we have about its implementation of the awaitable pattern. Note that all // the funcs/actions we construct here are precompiled, so that only one instance of // each is preserved throughout the lifetime of the ObjectMethodExecutor. // var getAwaiterFunc = (object awaitable) => (object)((CustomAwaitableType)awaitable).GetAwaiter(); ParameterExpression customAwaitableParam = Expression.Parameter(typeof(object), "awaitable"); AwaitableInfo awaitableInfo = coercedAwaitableInfo.AwaitableInfo; Type postCoercionMethodReturnType = coercedAwaitableInfo.CoercerResultType ?? target.Method.ReturnType; Func<object, object> getAwaiterFunc = Expression.Lambda<Func<object, object>>( Expression.Convert( Expression.Call( Expression.Convert(customAwaitableParam, postCoercionMethodReturnType), awaitableInfo.GetAwaiterMethod), typeof(object)), customAwaitableParam).Compile(); // var isCompletedFunc = (object awaiter) => ((CustomAwaiterType)awaiter).IsCompleted; ParameterExpression isCompletedParam = Expression.Parameter(typeof(object), "awaiter"); Func<object, bool> isCompletedFunc = Expression.Lambda<Func<object, bool>>( Expression.MakeMemberAccess( Expression.Convert(isCompletedParam, awaitableInfo.AwaiterType), awaitableInfo.AwaiterIsCompletedProperty), isCompletedParam).Compile(); ParameterExpression getResultParam = Expression.Parameter(typeof(object), "awaiter"); Func<object, object> getResultFunc; if (awaitableInfo.ResultType == typeof(void)) { // var getResultFunc = (object awaiter) => { // ((CustomAwaiterType)awaiter).GetResult(); // We need to invoke this to surface any exceptions // return (object)null; // }; getResultFunc = Expression.Lambda<Func<object, object>>( Expression.Block( Expression.Call( Expression.Convert(getResultParam, awaitableInfo.AwaiterType), awaitableInfo.AwaiterGetResultMethod), Expression.Constant(null) ), getResultParam).Compile(); } else { // var getResultFunc = (object awaiter) => (object)((CustomAwaiterType)awaiter).GetResult(); getResultFunc = Expression.Lambda<Func<object, object>>( Expression.Convert( Expression.Call( Expression.Convert(getResultParam, awaitableInfo.AwaiterType), awaitableInfo.AwaiterGetResultMethod), typeof(object)), getResultParam).Compile(); } // var onCompletedFunc = (object awaiter, Action continuation) => { // ((CustomAwaiterType)awaiter).OnCompleted(continuation); // }; ParameterExpression onCompletedParam1 = Expression.Parameter(typeof(object), "awaiter"); ParameterExpression onCompletedParam2 = Expression.Parameter(typeof(Action), "continuation"); Action<object, Action> onCompletedFunc = Expression.Lambda<Action<object, Action>>( Expression.Call( Expression.Convert(onCompletedParam1, awaitableInfo.AwaiterType), awaitableInfo.AwaiterOnCompletedMethod, onCompletedParam2), onCompletedParam1, onCompletedParam2).Compile(); Action<object, Action> unsafeOnCompletedFunc = null; if (awaitableInfo.AwaiterUnsafeOnCompletedMethod != null) { // var unsafeOnCompletedFunc = (object awaiter, Action continuation) => { // ((CustomAwaiterType)awaiter).UnsafeOnCompleted(continuation); // }; ParameterExpression unsafeOnCompletedParam1 = Expression.Parameter(typeof(object), "awaiter"); ParameterExpression unsafeOnCompletedParam2 = Expression.Parameter(typeof(Action), "continuation"); unsafeOnCompletedFunc = Expression.Lambda<Action<object, Action>>( Expression.Call( Expression.Convert(unsafeOnCompletedParam1, awaitableInfo.AwaiterType), awaitableInfo.AwaiterUnsafeOnCompletedMethod, unsafeOnCompletedParam2), unsafeOnCompletedParam1, unsafeOnCompletedParam2).Compile(); } // If we need to pass the method call result through a coercer function to get an // awaitable, then do so. Expression coercedMethodCall = coercedAwaitableInfo.RequiresCoercion ? Expression.Invoke(coercedAwaitableInfo.CoercerExpression, methodCall) : (Expression)methodCall; // return new ObjectMethodExecutorAwaitable( // (object)coercedMethodCall, // getAwaiterFunc, // isCompletedFunc, // getResultFunc, // onCompletedFunc, // unsafeOnCompletedFunc); NewExpression returnValueExpression = Expression.New( lambdaExecutorAwaitableConstructor, Expression.Convert(coercedMethodCall, typeof(object)), Expression.Constant(getAwaiterFunc), Expression.Constant(isCompletedFunc), Expression.Constant(getResultFunc), Expression.Constant(onCompletedFunc), Expression.Constant(unsafeOnCompletedFunc, typeof(Action<object, Action>))); Expression<AsyncActionExecutorDelegate> lambda = Expression.Lambda<AsyncActionExecutorDelegate>(returnValueExpression, targetParameter, parametersParameter); return lambda.Compile(); } private static readonly ConstructorInfo lambdaExecutorAwaitableConstructor = typeof(LambdaExecutorAwaitable).GetConstructor(new[] { typeof(object), // customAwaitable typeof(Func<object, object>), // getAwaiterMethod typeof(Func<object, bool>), // isCompletedMethod typeof(Func<object, object>), // getResultMethod typeof(Action<object, Action>), // onCompletedMethod typeof(Action<object, Action>) // unsafeOnCompletedMethod }); private UnaryExpression CreateParameterCast(BinaryExpression accessor, Type type) { if (type.IsGenericType) { Type firstInnerType = type.GenericTypeArguments.First(); Type bindingSourceParameterType = typeof(BindingSourceParameter<>).MakeGenericType(firstInnerType); if (bindingSourceParameterType.IsAssignableFrom(type)) { // castParameter: "(Ti) (FromBody<T..>) parameters[i]" return Expression.Convert(Expression.Convert(accessor, firstInnerType), type); } } // castParameter: "(Ti) parameters[i]" return Expression.Convert(accessor, type); } private MethodCallExpression CreateMethodCall(Delegate target, ParameterExpression targetParameter, ParameterExpression parametersParameter) { List<Expression> parameters = BuildParameterList(target.Method, parametersParameter); Type delegateType = target.GetType(); UnaryExpression instanceCast = Expression.Convert(targetParameter, delegateType); // methodCall: ((Func<...>/Action<...>) target) @delegate.Invoke((T0) parameters[0], (T1) parameters[1], ...) return Expression.Call(instanceCast, delegateType.GetMethod("Invoke"), parameters); } private List<Expression> BuildParameterList(MethodInfo method, ParameterExpression source) { List<Expression> parameters = new List<Expression>(); ParameterInfo[] infos = method.GetParameters(); for (int i = 0; i < infos.Length; i++) { ParameterInfo info = infos[i]; // arrayIndexAccessor: parameters[i] BinaryExpression arrayIndexAccessor = Expression.ArrayIndex(source, Expression.Constant(i)); // castParameter: "(Ti) (FromBody<T..>) parameters[i]" or "(Ti) parameters[i]". UnaryExpression castParameter = CreateParameterCast(arrayIndexAccessor, info.ParameterType); parameters.Add(castParameter); } return parameters; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Diagnostics.CodeAnalysis; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using static QuantConnect.StringExtensions; namespace QuantConnect.Securities { /// <summary> /// Provides a base class for all buying power models /// </summary> public class BuyingPowerModel : IBuyingPowerModel { private decimal _initialMarginRequirement; private decimal _maintenanceMarginRequirement; /// <summary> /// The percentage used to determine the required unused buying power for the account. /// </summary> protected decimal RequiredFreeBuyingPowerPercent; /// <summary> /// Initializes a new instance of the <see cref="BuyingPowerModel"/> with no leverage (1x) /// </summary> public BuyingPowerModel() : this(1m) { } /// <summary> /// Initializes a new instance of the <see cref="BuyingPowerModel"/> /// </summary> /// <param name="initialMarginRequirement">The percentage of an order's absolute cost /// that must be held in free cash in order to place the order</param> /// <param name="maintenanceMarginRequirement">The percentage of the holding's absolute /// cost that must be held in free cash in order to avoid a margin call</param> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required /// unused buying power for the account.</param> public BuyingPowerModel( decimal initialMarginRequirement, decimal maintenanceMarginRequirement, decimal requiredFreeBuyingPowerPercent ) { if (initialMarginRequirement < 0 || initialMarginRequirement > 1) { throw new ArgumentException("Initial margin requirement must be between 0 and 1"); } if (maintenanceMarginRequirement < 0 || maintenanceMarginRequirement > 1) { throw new ArgumentException("Maintenance margin requirement must be between 0 and 1"); } if (requiredFreeBuyingPowerPercent < 0 || requiredFreeBuyingPowerPercent > 1) { throw new ArgumentException("Free Buying Power Percent requirement must be between 0 and 1"); } _initialMarginRequirement = initialMarginRequirement; _maintenanceMarginRequirement = maintenanceMarginRequirement; RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; } /// <summary> /// Initializes a new instance of the <see cref="BuyingPowerModel"/> /// </summary> /// <param name="leverage">The leverage</param> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required /// unused buying power for the account.</param> public BuyingPowerModel(decimal leverage, decimal requiredFreeBuyingPowerPercent = 0) { if (leverage < 1) { throw new ArgumentException("Leverage must be greater than or equal to 1."); } if (requiredFreeBuyingPowerPercent < 0 || requiredFreeBuyingPowerPercent > 1) { throw new ArgumentException("Free Buying Power Percent requirement must be between 0 and 1"); } _initialMarginRequirement = 1 / leverage; _maintenanceMarginRequirement = 1 / leverage; RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; } /// <summary> /// Gets the current leverage of the security /// </summary> /// <param name="security">The security to get leverage for</param> /// <returns>The current leverage in the security</returns> public virtual decimal GetLeverage(Security security) { return 1 / _initialMarginRequirement; } /// <summary> /// Sets the leverage for the applicable securities, i.e, equities /// </summary> /// <remarks> /// This is added to maintain backwards compatibility with the old margin/leverage system /// </remarks> /// <param name="security"></param> /// <param name="leverage">The new leverage</param> public virtual void SetLeverage(Security security, decimal leverage) { if (leverage < 1) { throw new ArgumentException("Leverage must be greater than or equal to 1."); } var margin = 1 / leverage; _initialMarginRequirement = margin; _maintenanceMarginRequirement = margin; } /// <summary> /// Gets the total margin required to execute the specified order in units of the account currency including fees /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>The total margin in terms of the currency quoted in the order</returns> public virtual InitialMargin GetInitialMarginRequiredForOrder( InitialMarginRequiredForOrderParameters parameters ) { //Get the order value from the non-abstract order classes (MarketOrder, LimitOrder, StopMarketOrder) //Market order is approximated from the current security price and set in the MarketOrder Method in QCAlgorithm. var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, parameters.Order)).Value; var feesInAccountCurrency = parameters.CurrencyConverter. ConvertToAccountCurrency(fees).Amount; var orderMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Order.Quantity); return orderMargin + Math.Sign(orderMargin) * feesInAccountCurrency; } /// <summary> /// Gets the margin currently allocated to the specified holding /// </summary> /// <param name="parameters">An object containing the security and holdings quantity/cost/value</param> /// <returns>The maintenance margin required for the provided holdings quantity/cost/value</returns> public virtual MaintenanceMargin GetMaintenanceMargin(MaintenanceMarginParameters parameters) { return parameters.AbsoluteHoldingsValue * _maintenanceMarginRequirement; } /// <summary> /// Gets the margin cash available for a trade /// </summary> /// <param name="portfolio">The algorithm's portfolio</param> /// <param name="security">The security to be traded</param> /// <param name="direction">The direction of the trade</param> /// <returns>The margin available for the trade</returns> protected virtual decimal GetMarginRemaining( SecurityPortfolioManager portfolio, Security security, OrderDirection direction ) { var totalPortfolioValue = portfolio.TotalPortfolioValue; var result = portfolio.GetMarginRemaining(totalPortfolioValue); if (direction != OrderDirection.Hold) { var holdings = security.Holdings; //If the order is in the same direction as holdings, our remaining cash is our cash //In the opposite direction, our remaining cash is 2 x current value of assets + our cash if (holdings.IsLong) { switch (direction) { case OrderDirection.Sell: result += // portion of margin to close the existing position this.GetMaintenanceMargin(security) + // portion of margin to open the new position this.GetInitialMarginRequirement(security, security.Holdings.AbsoluteQuantity); break; } } else if (holdings.IsShort) { switch (direction) { case OrderDirection.Buy: result += // portion of margin to close the existing position this.GetMaintenanceMargin(security) + // portion of margin to open the new position this.GetInitialMarginRequirement(security, security.Holdings.AbsoluteQuantity); break; } } } result -= totalPortfolioValue * RequiredFreeBuyingPowerPercent; return result < 0 ? 0 : result; } /// <summary> /// The margin that must be held in order to increase the position by the provided quantity /// </summary> /// <param name="parameters">An object containing the security and quantity of shares</param> /// <returns>The initial margin required for the provided security and quantity</returns> public virtual InitialMargin GetInitialMarginRequirement(InitialMarginParameters parameters) { var security = parameters.Security; var quantity = parameters.Quantity; return security.QuoteCurrency.ConversionRate * security.SymbolProperties.ContractMultiplier * security.Price * quantity * _initialMarginRequirement; } /// <summary> /// Check if there is sufficient buying power to execute this order. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>Returns buying power information for an order</returns> public virtual HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(HasSufficientBuyingPowerForOrderParameters parameters) { // short circuit the div 0 case if (parameters.Order.Quantity == 0) { return parameters.Sufficient(); } var ticket = parameters.Portfolio.Transactions.GetOrderTicket(parameters.Order.Id); if (ticket == null) { return parameters.Insufficient( $"Null order ticket for id: {parameters.Order.Id}" ); } if (parameters.Order.Type == OrderType.OptionExercise) { // for option assignment and exercise orders we look into the requirements to process the underlying security transaction var option = (Option.Option) parameters.Security; var underlying = option.Underlying; if (option.IsAutoExercised(underlying.Close) && underlying.IsTradable) { var quantity = option.GetExerciseQuantity(parameters.Order.Quantity); var newOrder = new LimitOrder { Id = parameters.Order.Id, Time = parameters.Order.Time, LimitPrice = option.StrikePrice, Symbol = underlying.Symbol, Quantity = quantity }; // we continue with this call for underlying var parametersForUnderlying = parameters.ForUnderlying(newOrder); var freeMargin = underlying.BuyingPowerModel.GetBuyingPower(parametersForUnderlying.Portfolio, parametersForUnderlying.Security, parametersForUnderlying.Order.Direction); // we add the margin used by the option itself freeMargin += GetMaintenanceMargin(MaintenanceMarginParameters.ForQuantityAtCurrentPrice(option, -parameters.Order.Quantity)); var initialMarginRequired = underlying.BuyingPowerModel.GetInitialMarginRequiredForOrder( new InitialMarginRequiredForOrderParameters(parameters.Portfolio.CashBook, underlying, newOrder)); return HasSufficientBuyingPowerForOrder(parametersForUnderlying, ticket, freeMargin, initialMarginRequired); } return parameters.Sufficient(); } return HasSufficientBuyingPowerForOrder(parameters, ticket); } private HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(HasSufficientBuyingPowerForOrderParameters parameters, OrderTicket ticket, decimal? freeMarginToUse = null, decimal? initialMarginRequired = null) { // When order only reduces or closes a security position, capital is always sufficient if (parameters.Security.Holdings.Quantity * parameters.Order.Quantity < 0 && Math.Abs(parameters.Security.Holdings.Quantity) >= Math.Abs(parameters.Order.Quantity)) { return parameters.Sufficient(); } var freeMargin = freeMarginToUse ?? GetMarginRemaining(parameters.Portfolio, parameters.Security, parameters.Order.Direction); var initialMarginRequiredForOrder = initialMarginRequired ?? GetInitialMarginRequiredForOrder( new InitialMarginRequiredForOrderParameters( parameters.Portfolio.CashBook, parameters.Security, parameters.Order )); // pro-rate the initial margin required for order based on how much has already been filled var percentUnfilled = (Math.Abs(parameters.Order.Quantity) - Math.Abs(ticket.QuantityFilled)) / Math.Abs(parameters.Order.Quantity); var initialMarginRequiredForRemainderOfOrder = percentUnfilled * initialMarginRequiredForOrder; if (Math.Abs(initialMarginRequiredForRemainderOfOrder) > freeMargin) { return parameters.Insufficient(Invariant($"Id: {parameters.Order.Id}, ") + Invariant($"Initial Margin: {initialMarginRequiredForRemainderOfOrder.Normalize()}, ") + Invariant($"Free Margin: {freeMargin.Normalize()}") ); } return parameters.Sufficient(); } /// <summary> /// Get the maximum market order quantity to obtain a delta in the buying power used by a security. /// The deltas sign defines the position side to apply it to, positive long, negative short. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the delta buying power</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> /// <remarks>Used by the margin call model to reduce the position by a delta percent.</remarks> public virtual GetMaximumOrderQuantityResult GetMaximumOrderQuantityForDeltaBuyingPower( GetMaximumOrderQuantityForDeltaBuyingPowerParameters parameters) { var usedBuyingPower = parameters.Security.BuyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(parameters.Security)).AbsoluteUsedBuyingPower; var signedUsedBuyingPower = usedBuyingPower * (parameters.Security.Holdings.IsLong ? 1 : -1); var targetBuyingPower = signedUsedBuyingPower + parameters.DeltaBuyingPower; var target = 0m; if (parameters.Portfolio.TotalPortfolioValue != 0) { target = targetBuyingPower / parameters.Portfolio.TotalPortfolioValue; } return GetMaximumOrderQuantityForTargetBuyingPower( new GetMaximumOrderQuantityForTargetBuyingPowerParameters(parameters.Portfolio, parameters.Security, target, parameters.MinimumOrderMarginPortfolioPercentage, parameters.SilenceNonErrorReasons)); } /// <summary> /// Get the maximum market order quantity to obtain a position with a given buying power percentage. /// Will not take into account free buying power. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the target signed buying power percentage</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> /// <remarks>This implementation ensures that our resulting holdings is less than the target, but it does not necessarily /// maximize the holdings to meet the target. To do that we need a minimizing algorithm that reduces the difference between /// the target final margin value and the target holdings margin.</remarks> public virtual GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower(GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { // this is expensive so lets fetch it once var totalPortfolioValue = parameters.Portfolio.TotalPortfolioValue; // adjust target buying power to comply with required Free Buying Power Percent var signedTargetFinalMarginValue = parameters.TargetBuyingPower * (totalPortfolioValue - totalPortfolioValue * RequiredFreeBuyingPowerPercent); // if targeting zero, simply return the negative of the quantity if (signedTargetFinalMarginValue == 0) { return new GetMaximumOrderQuantityResult(-parameters.Security.Holdings.Quantity, string.Empty, false); } // we use initial margin requirement here to avoid the duplicate PortfolioTarget.Percent situation: // PortfolioTarget.Percent(1) -> fills -> PortfolioTarget.Percent(1) _could_ detect free buying power if we use Maintenance requirement here var signedCurrentUsedMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Security.Holdings.Quantity); // determine the unit price in terms of the account currency var utcTime = parameters.Security.LocalTime.ConvertToUtc(parameters.Security.Exchange.TimeZone); // determine the margin required for 1 unit var absUnitMargin = this.GetInitialMarginRequirement(parameters.Security, 1); if (absUnitMargin == 0) { return new GetMaximumOrderQuantityResult(0, parameters.Security.Symbol.GetZeroPriceMessage()); } // Check that the change of margin is above our models minimum percentage change var absDifferenceOfMargin = Math.Abs(signedTargetFinalMarginValue - signedCurrentUsedMargin); if (!BuyingPowerModelExtensions.AboveMinimumOrderMarginPortfolioPercentage(parameters.Portfolio, parameters.MinimumOrderMarginPortfolioPercentage, absDifferenceOfMargin)) { string reason = null; if (!parameters.SilenceNonErrorReasons) { var minimumValue = totalPortfolioValue * parameters.MinimumOrderMarginPortfolioPercentage; reason = $"The target order margin {absDifferenceOfMargin} is less than the minimum {minimumValue}."; } return new GetMaximumOrderQuantityResult(0, reason, false); } // Use the following loop to converge on a value that places us under our target allocation when adjusted for fees var lastOrderQuantity = 0m; // For safety check decimal orderFees = 0m; decimal signedTargetHoldingsMargin; decimal orderQuantity; do { // Calculate our order quantity orderQuantity = GetAmountToOrder(parameters.Security, signedTargetFinalMarginValue, absUnitMargin, out signedTargetHoldingsMargin); if (orderQuantity == 0) { string reason = null; if (!parameters.SilenceNonErrorReasons) { reason = Invariant($"The order quantity is less than the lot size of {parameters.Security.SymbolProperties.LotSize} ") + Invariant($"and has been rounded to zero. Target order margin {signedTargetFinalMarginValue - signedCurrentUsedMargin}. "); } return new GetMaximumOrderQuantityResult(0, reason, false); } // generate the order var order = new MarketOrder(parameters.Security.Symbol, orderQuantity, utcTime); var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, order)).Value; orderFees = parameters.Portfolio.CashBook.ConvertToAccountCurrency(fees).Amount; // Update our target portfolio margin allocated when considering fees, then calculate the new FinalOrderMargin signedTargetFinalMarginValue = (totalPortfolioValue - orderFees - totalPortfolioValue * RequiredFreeBuyingPowerPercent) * parameters.TargetBuyingPower; // Start safe check after first loop, stops endless recursion if (lastOrderQuantity == orderQuantity) { var message = Invariant($"GetMaximumOrderQuantityForTargetBuyingPower failed to converge on the target margin: {signedTargetFinalMarginValue}; ") + Invariant($"the following information can be used to reproduce the issue. Total Portfolio Cash: {parameters.Portfolio.Cash}; Security : {parameters.Security.Symbol.ID}; ") + Invariant($"Price : {parameters.Security.Close}; Leverage: {parameters.Security.Leverage}; Order Fee: {orderFees}; Lot Size: {parameters.Security.SymbolProperties.LotSize}; ") + Invariant($"Current Holdings: {parameters.Security.Holdings.Quantity} @ {parameters.Security.Holdings.AveragePrice}; Target Percentage: %{parameters.TargetBuyingPower * 100};"); // Need to add underlying value to message to reproduce with options if (parameters.Security is Option.Option option && option.Underlying != null) { var underlying = option.Underlying; message += Invariant($" Underlying Security: {underlying.Symbol.ID}; Underlying Price: {underlying.Close}; Underlying Holdings: {underlying.Holdings.Quantity} @ {underlying.Holdings.AveragePrice};"); } throw new ArgumentException(message); } lastOrderQuantity = orderQuantity; } // Ensure that our target holdings margin will be less than or equal to our target allocated margin while (Math.Abs(signedTargetHoldingsMargin) > Math.Abs(signedTargetFinalMarginValue)); // add directionality back in return new GetMaximumOrderQuantityResult(orderQuantity); } /// <summary> /// Helper function that determines the amount to order to get to a given target safely. /// Meaning it will either be at or just below target always. /// </summary> /// <param name="security">Security we are to determine order size for</param> /// <param name="targetMargin">Target margin allocated</param> /// <param name="marginForOneUnit">Margin requirement for one unit; used in our initial order guess</param> /// <param name="finalMargin">Output the final margin allocated to this security</param> /// <returns>The size of the order to get safely to our target</returns> public decimal GetAmountToOrder([NotNull]Security security, decimal targetMargin, decimal marginForOneUnit, out decimal finalMargin) { var lotSize = security.SymbolProperties.LotSize; // Start with order size that puts us back to 0, in theory this means current margin is 0 // so we can calculate holdings to get to the new target margin directly. This is very helpful for // odd cases where margin requirements aren't linear. var orderSize = -security.Holdings.Quantity; // Use the margin for one unit to make our initial guess. orderSize += targetMargin / marginForOneUnit; // Determine the rounding mode for this order size var roundingMode = targetMargin < 0 // Ending in short position; orders need to be rounded towards positive so we end up under our target ? MidpointRounding.ToPositiveInfinity // Ending in long position; orders need to be rounded towards negative so we end up under our target : MidpointRounding.ToNegativeInfinity; // Round this order size appropriately orderSize = orderSize.DiscretelyRoundBy(lotSize, roundingMode); // Use our model to calculate this final margin as a final check finalMargin = this.GetInitialMarginRequirement(security, orderSize + security.Holdings.Quantity); // Until our absolute final margin is equal to or below target we need to adjust; ensures we don't overshoot target // This isn't usually the case, but for non-linear margin per unit cases this may be necessary. // For example https://www.quantconnect.com/forum/discussion/12470, (covered in OptionMarginBuyingPowerModelTests) var marginDifference = finalMargin - targetMargin; while ((targetMargin < 0 && marginDifference < 0) || (targetMargin > 0 && marginDifference > 0)) { // TODO: Can this be smarter about its adjustment, instead of just stepping by lotsize? // We adjust according to the target margin being a short or long orderSize += targetMargin < 0 ? lotSize : -lotSize; // Recalculate final margin with this adjusted orderSize finalMargin = this.GetInitialMarginRequirement(security, orderSize + security.Holdings.Quantity); // Safety check, does not occur in any of our testing, but to be sure we don't enter a endless loop // have this guy check that the difference between the two is not growing. var newDifference = finalMargin - targetMargin; if (Math.Abs(newDifference) > Math.Abs(marginDifference) && Math.Sign(newDifference) == Math.Sign(marginDifference)) { // We have a problem and are correcting in the wrong direction var errorMessage = "BuyingPowerModel().GetAmountToOrder(): Margin is being adjusted in the wrong direction." + $"Reproduce this issue with the following variables, Target Margin: {targetMargin}; MarginForOneUnit: {marginForOneUnit};" + $"Security Holdings: {security.Holdings.Quantity} @ {security.Holdings.AveragePrice};" + $"LotSize: {security.SymbolProperties.LotSize}; Price: {security.Close}; Leverage: {security.Leverage}"; // Need to add underlying value to message to reproduce with options if (security is Option.Option option && option.Underlying != null) { var underlying = option.Underlying; errorMessage += $" Underlying Security: {underlying.Symbol.ID}; Underlying Price: {underlying.Close};" + $" Underlying Holdings: {underlying.Holdings.Quantity} @ {underlying.Holdings.AveragePrice};"; } throw new ArgumentException(errorMessage); } marginDifference = newDifference; } return orderSize; } /// <summary> /// Gets the amount of buying power reserved to maintain the specified position /// </summary> /// <param name="parameters">A parameters object containing the security</param> /// <returns>The reserved buying power in account currency</returns> public virtual ReservedBuyingPowerForPosition GetReservedBuyingPowerForPosition(ReservedBuyingPowerForPositionParameters parameters) { var maintenanceMargin = this.GetMaintenanceMargin(parameters.Security); return parameters.ResultInAccountCurrency(maintenanceMargin); } /// <summary> /// Gets the buying power available for a trade /// </summary> /// <param name="parameters">A parameters object containing the algorithm's portfolio, security, and order direction</param> /// <returns>The buying power available for the trade</returns> public virtual BuyingPower GetBuyingPower(BuyingPowerParameters parameters) { var marginRemaining = GetMarginRemaining(parameters.Portfolio, parameters.Security, parameters.Direction); return parameters.ResultInAccountCurrency(marginRemaining); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedComparisonNotEqualNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableBoolTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableBool(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonNotEqualNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyComparisonNotEqualNullableBool(bool? a, bool? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonNotEqualNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.NotEqual( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a != b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class represents the software preferences of a particular // culture or community. It includes information such as the // language, writing system, and a calendar used by the culture // as well as methods for common operations such as printing // dates and sorting strings. // // // // !!!! NOTE WHEN CHANGING THIS CLASS !!!! // // If adding or removing members to this class, please update CultureInfoBaseObject // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be // different than the order in which members are declared. For instance, all // reference types will come first in the class before value types (like ints, bools, etc) // regardless of the order in which they are declared. The best way to see the // actual order of the class is to do a !dumpobj on an instance of the managed // object inside of the debugger. // //////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; using System.Threading; #if ENABLE_WINRT using Internal.Runtime.Augments; #endif namespace System.Globalization { public partial class CultureInfo : IFormatProvider, ICloneable { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // We use an RFC4646 type string to construct CultureInfo. // This string is stored in _name and is authoritative. // We use the _cultureData to get the data for our object private bool _isReadOnly; private CompareInfo _compareInfo; private TextInfo _textInfo; internal NumberFormatInfo _numInfo; internal DateTimeFormatInfo _dateTimeInfo; private Calendar _calendar; // // The CultureData instance that we are going to read data from. // For supported culture, this will be the CultureData instance that read data from mscorlib assembly. // For customized culture, this will be the CultureData instance that read data from user customized culture binary file. // internal CultureData _cultureData; internal bool _isInherited; private CultureInfo _consoleFallbackCulture; // Names are confusing. Here are 3 names we have: // // new CultureInfo() _name _nonSortName _sortName // en-US en-US en-US en-US // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US) // en en // // Note that in Silverlight we ask the OS for the text and sort behavior, so the // textinfo and compareinfo names are the same as the name // This has a de-DE, de-DE_phoneb or fj-FJ style name internal string _name; // This will hold the non sorting name to be returned from CultureInfo.Name property. // This has a de-DE style name even for de-DE_phoneb type cultures private string _nonSortName; // This will hold the sorting name to be returned from CultureInfo.SortName property. // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ. // Otherwise its the sort name, ie: de-DE or de-DE_phoneb private string _sortName; //--------------------------------------------------------------------// // // Static data members // //--------------------------------------------------------------------// //Get the current user default culture. This one is almost always used, so we create it by default. private static volatile CultureInfo s_userDefaultCulture; //The culture used in the user interface. This is mostly used to load correct localized resources. private static volatile CultureInfo s_userDefaultUICulture; // // All of the following will be created on demand. // // WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. //The Invariant culture; private static readonly CultureInfo s_InvariantCultureInfo = new CultureInfo(CultureData.Invariant, isReadOnly: true); //These are defaults that we use if a thread has not opted into having an explicit culture private static volatile CultureInfo s_DefaultThreadCurrentUICulture; private static volatile CultureInfo s_DefaultThreadCurrentCulture; [ThreadStatic] private static CultureInfo s_currentThreadCulture; [ThreadStatic] private static CultureInfo s_currentThreadUICulture; private static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture; private static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture; private static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args) { s_currentThreadCulture = args.CurrentValue; } private static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args) { s_currentThreadUICulture = args.CurrentValue; } private static readonly object _lock = new object(); private static volatile Dictionary<string, CultureInfo> s_NameCachedCultures; private static volatile Dictionary<int, CultureInfo> s_LcidCachedCultures; //The parent culture. private CultureInfo _parent; // LOCALE constants of interest to us internally and privately for LCID functions // (ie: avoid using these and use names if possible) internal const int LOCALE_NEUTRAL = 0x0000; private const int LOCALE_USER_DEFAULT = 0x0400; private const int LOCALE_SYSTEM_DEFAULT = 0x0800; internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000; internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00; internal const int LOCALE_INVARIANT = 0x007F; private static CultureInfo InitializeUserDefaultCulture() { Interlocked.CompareExchange(ref s_userDefaultCulture, GetUserDefaultCulture(), null); return s_userDefaultCulture; } private static CultureInfo InitializeUserDefaultUICulture() { Interlocked.CompareExchange(ref s_userDefaultUICulture, GetUserDefaultUICulture(), null); return s_userDefaultUICulture; } //////////////////////////////////////////////////////////////////////// // // CultureInfo Constructors // //////////////////////////////////////////////////////////////////////// public CultureInfo(string name) : this(name, true) { } public CultureInfo(string name, bool useUserOverride) { if (name == null) { throw new ArgumentNullException(nameof(name), SR.ArgumentNull_String); } // Get our data providing record _cultureData = CultureData.GetCultureData(name, useUserOverride); if (_cultureData == null) { throw new CultureNotFoundException(nameof(name), name, SR.Argument_CultureNotSupported); } _name = _cultureData.CultureName; _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo)); } private CultureInfo(CultureData cultureData, bool isReadOnly = false) { Debug.Assert(cultureData != null); _cultureData = cultureData; _name = cultureData.CultureName; _isInherited = false; _isReadOnly = isReadOnly; } private static CultureInfo CreateCultureInfoNoThrow(string name, bool useUserOverride) { Debug.Assert(name != null); CultureData cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { return null; } return new CultureInfo(cultureData); } public CultureInfo(int culture) : this(culture, true) { } public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... if (culture < 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } switch (culture) { case LOCALE_CUSTOM_DEFAULT: case LOCALE_SYSTEM_DEFAULT: case LOCALE_NEUTRAL: case LOCALE_USER_DEFAULT: case LOCALE_CUSTOM_UNSPECIFIED: // Can't support unknown custom cultures and we do not support neutral or // non-custom user locales. throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); default: // Now see if this LCID is supported in the system default CultureData table. _cultureData = CultureData.GetCultureData(culture, useUserOverride); break; } _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo)); _name = _cultureData.CultureName; } // Constructor called by SQL Server's special munged culture - creates a culture with // a TextInfo and CompareInfo that come from a supplied alternate source. This object // is ALWAYS read-only. // Note that we really cannot use an LCID version of this override as the cached // name we create for it has to include both names, and the logic for this is in // the GetCultureInfo override *only*. internal CultureInfo(string cultureName, string textAndCompareCultureName) { if (cultureName == null) { throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); } _cultureData = CultureData.GetCultureData(cultureName, false); if (_cultureData == null) throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported); _name = _cultureData.CultureName; CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName); _compareInfo = altCulture.CompareInfo; _textInfo = altCulture.TextInfo; } // We do this to try to return the system UI language and the default user languages // This method will fallback if this fails (like Invariant) // private static CultureInfo GetCultureByName(string name) { CultureInfo ci = null; // Try to get our culture try { ci = new CultureInfo(name); ci._isReadOnly = true; } catch (ArgumentException) { } if (ci == null) { ci = InvariantCulture; } return ci; } // // Return a specific culture. A tad irrelevent now since we always return valid data // for neutral locales. // // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647, // if we can't find a bigger name. That doesn't help with things like "zh" though, so // the approach is of questionable value // public static CultureInfo CreateSpecificCulture(string name) { CultureInfo culture; try { culture = new CultureInfo(name); } catch (ArgumentException) { // When CultureInfo throws this exception, it may be because someone passed the form // like "az-az" because it came out of an http accept lang. We should try a little // parsing to perhaps fall back to "az" here and use *it* to create the neutral. int idx; culture = null; for (idx = 0; idx < name.Length; idx++) { if ('-' == name[idx]) { try { culture = new CultureInfo(name.Substring(0, idx)); break; } catch (ArgumentException) { // throw the original exception so the name in the string will be right throw; } } } if (culture == null) { // nothing to save here; throw the original exception throw; } } // In the most common case, they've given us a specific culture, so we'll just return that. if (!(culture.IsNeutralCulture)) { return culture; } return new CultureInfo(culture._cultureData.SSPECIFICCULTURE); } internal static bool VerifyCultureName(string cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, // so we should check against CultureInfo.Name. for (int i = 0; i < cultureName.Length; i++) { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } if (throwException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName)); } return false; } return true; } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { //If we have an instance of one of our CultureInfos, the user can't have changed the //name and we know that all names are valid in files. if (!culture._isInherited) { return true; } return VerifyCultureName(culture.Name, throwException); } //////////////////////////////////////////////////////////////////////// // // CurrentCulture // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// // // We use the following order to return CurrentCulture and CurrentUICulture // o Use WinRT to return the current user profile language // o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture // o use thread culture if the user already set one using DefaultThreadCurrentCulture // or DefaultThreadCurrentUICulture // o Use NLS default user culture // o Use NLS default system culture // o Use Invariant culture // public static CultureInfo CurrentCulture { get { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { return (CultureInfo)callbacks.GetUserDefaultCulture(); } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX(); if (culture != null) return culture; } #endif if (s_currentThreadCulture != null) { return s_currentThreadCulture; } CultureInfo ci = s_DefaultThreadCurrentCulture; if (ci != null) { return ci; } return s_userDefaultCulture ?? InitializeUserDefaultCulture(); } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { if (SetCultureInfoForUserPreferredLanguageInAppX(value)) { // successfully set the culture, otherwise fallback to legacy path return; } } #endif if (s_asyncLocalCurrentCulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentCulture), null); } s_asyncLocalCurrentCulture.Value = value; } } public static CultureInfo CurrentUICulture { get { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { return (CultureInfo)callbacks.GetUserDefaultCulture(); } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX(); if (culture != null) return culture; } #endif if (s_currentThreadUICulture != null) { return s_currentThreadUICulture; } CultureInfo ci = s_DefaultThreadCurrentUICulture; if (ci != null) { return ci; } return UserDefaultUICulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } CultureInfo.VerifyCultureName(value, true); #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { if (SetCultureInfoForUserPreferredLanguageInAppX(value)) { // successfully set the culture, otherwise fallback to legacy path return; } } #endif if (s_asyncLocalCurrentUICulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentUICulture), null); } // this one will set s_currentThreadUICulture too s_asyncLocalCurrentUICulture.Value = value; } } internal static CultureInfo UserDefaultUICulture => s_userDefaultUICulture ?? InitializeUserDefaultUICulture(); public static CultureInfo InstalledUICulture => s_userDefaultCulture ?? InitializeUserDefaultCulture(); public static CultureInfo DefaultThreadCurrentCulture { get { return s_DefaultThreadCurrentCulture; } set { // If you add pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentCulture.set. s_DefaultThreadCurrentCulture = value; } } public static CultureInfo DefaultThreadCurrentUICulture { get { return s_DefaultThreadCurrentUICulture; } set { //If they're trying to use a Culture with a name that we can't use in resource lookup, //don't even let them set it on the thread. // If you add more pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentUICulture.set. if (value != null) { CultureInfo.VerifyCultureName(value, true); } s_DefaultThreadCurrentUICulture = value; } } //////////////////////////////////////////////////////////////////////// // // InvariantCulture // // This instance provides methods, for example for casing and sorting, // that are independent of the system and current user settings. It // should be used only by processes such as some system services that // require such invariant results (eg. file systems). In general, // the results are not linguistically correct and do not match any // culture info. // //////////////////////////////////////////////////////////////////////// public static CultureInfo InvariantCulture { get { Debug.Assert(s_InvariantCultureInfo != null); return s_InvariantCultureInfo; } } //////////////////////////////////////////////////////////////////////// // // Parent // // Return the parent CultureInfo for the current instance. // //////////////////////////////////////////////////////////////////////// public virtual CultureInfo Parent { get { if (null == _parent) { CultureInfo culture = null; string parentName = _cultureData.SPARENT; if (string.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } else { culture = CreateCultureInfoNoThrow(parentName, _cultureData.UseUserOverride); if (culture == null) { // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant // We can't allow ourselves to fail. In case of custom cultures the parent of the // current custom culture isn't installed. culture = InvariantCulture; } } Interlocked.CompareExchange<CultureInfo>(ref _parent, culture, null); } return _parent; } } public virtual int LCID { get { return _cultureData.ILANGUAGE; } } public virtual int KeyboardLayoutId { get { return _cultureData.IINPUTLANGUAGEHANDLE; } } public static CultureInfo[] GetCultures(CultureTypes types) { // internally we treat UserCustomCultures as Supplementals but v2 // treats as Supplementals and Replacements if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) { types |= CultureTypes.ReplacementCultures; } return CultureData.GetCultures(types); } //////////////////////////////////////////////////////////////////////// // // Name // // Returns the full name of the CultureInfo. The name is in format like // "en-US" This version does NOT include sort information in the name. // //////////////////////////////////////////////////////////////////////// public virtual string Name { get { // We return non sorting name here. if (_nonSortName == null) { _nonSortName = _cultureData.SNAME; if (_nonSortName == null) { _nonSortName = string.Empty; } } return _nonSortName; } } // This one has the sort information (ie: de-DE_phoneb) internal string SortName { get { if (_sortName == null) { _sortName = _cultureData.SCOMPAREINFO; } return _sortName; } } public string IetfLanguageTag { get { // special case the compatibility cultures switch (this.Name) { case "zh-CHT": return "zh-Hant"; case "zh-CHS": return "zh-Hans"; default: return this.Name; } } } //////////////////////////////////////////////////////////////////////// // // DisplayName // // Returns the full name of the CultureInfo in the localized language. // For example, if the localized language of the runtime is Spanish and the CultureInfo is // US English, "Ingles (Estados Unidos)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual string DisplayName { get { Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set"); return _cultureData.SLOCALIZEDDISPLAYNAME; } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the full name of the CultureInfo in the native language. // For example, if the CultureInfo is US English, "English // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual string NativeName { get { return _cultureData.SNATIVEDISPLAYNAME; } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the full name of the CultureInfo in English. // For example, if the CultureInfo is US English, "English // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual string EnglishName { get { return _cultureData.SENGDISPLAYNAME; } } // ie: en public virtual string TwoLetterISOLanguageName { get { return _cultureData.SISO639LANGNAME; } } // ie: eng public virtual string ThreeLetterISOLanguageName { get { return _cultureData.SISO639LANGNAME2; } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsLanguageName // // Returns the 3 letter windows language name for the current instance. eg: "ENU" // The ISO names are much preferred // //////////////////////////////////////////////////////////////////////// public virtual string ThreeLetterWindowsLanguageName { get { return _cultureData.SABBREVLANGNAME; } } //////////////////////////////////////////////////////////////////////// // // CompareInfo Read-Only Property // // Gets the CompareInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual CompareInfo CompareInfo { get { if (_compareInfo == null) { // Since CompareInfo's don't have any overrideable properties, get the CompareInfo from // the Non-Overridden CultureInfo so that we only create one CompareInfo per culture _compareInfo = UseUserOverride ? GetCultureInfo(_name).CompareInfo : new CompareInfo(this); } return _compareInfo; } } //////////////////////////////////////////////////////////////////////// // // TextInfo // // Gets the TextInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual TextInfo TextInfo { get { if (_textInfo == null) { // Make a new textInfo TextInfo tempTextInfo = new TextInfo(_cultureData); tempTextInfo.SetReadOnlyState(_isReadOnly); _textInfo = tempTextInfo; } return _textInfo; } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements object.Equals(). Returns a boolean indicating whether // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(object value) { if (object.ReferenceEquals(this, value)) return true; if (value is CultureInfo that) { // using CompareInfo to verify the data passed through the constructor // CultureInfo(String cultureName, String textAndCompareCultureName) return this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo); } return false; } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A // and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return this.Name.GetHashCode() + this.CompareInfo.GetHashCode(); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements object.ToString(). Returns the name of the CultureInfo, // eg. "de-DE_phoneb", "en-US", or "fj-FJ". // //////////////////////////////////////////////////////////////////////// public override string ToString() { return _name; } public virtual object GetFormat(Type formatType) { if (formatType == typeof(NumberFormatInfo)) return NumberFormat; if (formatType == typeof(DateTimeFormatInfo)) return DateTimeFormat; return null; } public virtual bool IsNeutralCulture { get { return _cultureData.IsNeutralCulture; } } public CultureTypes CultureTypes { get { CultureTypes types = 0; if (_cultureData.IsNeutralCulture) types |= CultureTypes.NeutralCultures; else types |= CultureTypes.SpecificCultures; types |= _cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0; // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete #pragma warning disable 618 types |= _cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0; #pragma warning restore 618 types |= _cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0; types |= _cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0; return types; } } public virtual NumberFormatInfo NumberFormat { get { if (_numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo(_cultureData); temp.isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _numInfo, temp, null); } return _numInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _numInfo = value; } } //////////////////////////////////////////////////////////////////////// // // GetDateTimeFormatInfo // // Create a DateTimeFormatInfo, and fill in the properties according to // the CultureID. // //////////////////////////////////////////////////////////////////////// public virtual DateTimeFormatInfo DateTimeFormat { get { if (_dateTimeInfo == null) { // Change the calendar of DTFI to the specified calendar of this CultureInfo. DateTimeFormatInfo temp = new DateTimeFormatInfo(_cultureData, this.Calendar); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _dateTimeInfo, temp, null); } return _dateTimeInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _dateTimeInfo = value; } } public void ClearCachedData() { // reset the default culture values s_userDefaultCulture = GetUserDefaultCulture(); s_userDefaultUICulture = GetUserDefaultUICulture(); RegionInfo.s_currentRegionInfo = null; #pragma warning disable 0618 // disable the obsolete warning TimeZone.ResetTimeZone(); #pragma warning restore 0618 TimeZoneInfo.ClearCachedData(); s_LcidCachedCultures = null; s_NameCachedCultures = null; CultureData.ClearCachedData(); } /*=================================GetCalendarInstance========================== **Action: Map a Win32 CALID to an instance of supported calendar. **Returns: An instance of calendar. **Arguments: calType The Win32 CALID **Exceptions: ** Shouldn't throw exception since the calType value is from our data table or from Win32 registry. ** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar. ============================================================================*/ internal static Calendar GetCalendarInstance(CalendarId calType) { if (calType == CalendarId.GREGORIAN) { return new GregorianCalendar(); } return GetCalendarInstanceRare(calType); } //This function exists as a shortcut to prevent us from loading all of the non-gregorian //calendars unless they're required. internal static Calendar GetCalendarInstanceRare(CalendarId calType) { Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); switch (calType) { case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar return new GregorianCalendar((GregorianCalendarTypes)calType); case CalendarId.TAIWAN: // Taiwan Era calendar return new TaiwanCalendar(); case CalendarId.JAPAN: // Japanese Emperor Era calendar return new JapaneseCalendar(); case CalendarId.KOREA: // Korean Tangun Era calendar return new KoreanCalendar(); case CalendarId.THAI: // Thai calendar return new ThaiBuddhistCalendar(); case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar return new HijriCalendar(); case CalendarId.HEBREW: // Hebrew (Lunar) calendar return new HebrewCalendar(); case CalendarId.UMALQURA: return new UmAlQuraCalendar(); case CalendarId.PERSIAN: return new PersianCalendar(); } return new GregorianCalendar(); } /*=================================Calendar========================== **Action: Return/set the default calendar used by this culture. ** This value can be overridden by regional option if this is a current culture. **Returns: **Arguments: **Exceptions: ============================================================================*/ public virtual Calendar Calendar { get { if (_calendar == null) { Debug.Assert(_cultureData.CalendarIds.Length > 0, "_cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = _cultureData.DefaultCalendar; System.Threading.Interlocked.MemoryBarrier(); newObj.SetReadOnlyState(_isReadOnly); _calendar = newObj; } return _calendar; } } /*=================================OptionCalendars========================== **Action: Return an array of the optional calendar for this culture. **Returns: an array of Calendar. **Arguments: **Exceptions: ============================================================================*/ public virtual Calendar[] OptionalCalendars { get { // // This property always returns a new copy of the calendar array. // CalendarId[] calID = _cultureData.CalendarIds; Calendar[] cals = new Calendar[calID.Length]; for (int i = 0; i < cals.Length; i++) { cals[i] = GetCalendarInstance(calID[i]); } return cals; } } public bool UseUserOverride { get { return _cultureData.UseUserOverride; } } public CultureInfo GetConsoleFallbackUICulture() { CultureInfo temp = _consoleFallbackCulture; if (temp == null) { temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); temp._isReadOnly = true; _consoleFallbackCulture = temp; } return temp; } public virtual object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!_isInherited) { if (_dateTimeInfo != null) { ci._dateTimeInfo = (DateTimeFormatInfo)_dateTimeInfo.Clone(); } if (_numInfo != null) { ci._numInfo = (NumberFormatInfo)_numInfo.Clone(); } } else { ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone(); ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone(); } if (_textInfo != null) { ci._textInfo = (TextInfo)_textInfo.Clone(); } if (_calendar != null) { ci._calendar = (Calendar)_calendar.Clone(); } return ci; } public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { throw new ArgumentNullException(nameof(ci)); } if (ci.IsReadOnly) { return ci; } CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone()); if (!ci.IsNeutralCulture) { //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!ci._isInherited) { if (ci._dateTimeInfo != null) { newInfo._dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci._dateTimeInfo); } if (ci._numInfo != null) { newInfo._numInfo = NumberFormatInfo.ReadOnly(ci._numInfo); } } else { newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat); newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat); } } if (ci._textInfo != null) { newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo); } if (ci._calendar != null) { newInfo._calendar = Calendar.ReadOnly(ci._calendar); } // Don't set the read-only flag too early. // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set. newInfo._isReadOnly = true; return newInfo; } public bool IsReadOnly { get { return _isReadOnly; } } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } // For resource lookup, we consider a culture the invariant culture by name equality. // We perform this check frequently during resource lookup, so adding a property for // improved readability. internal bool HasInvariantCultureName { get { return Name == CultureInfo.InvariantCulture.Name; } } // Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name. // If lcid is -1, use the altName and create one of those special SQL cultures. internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName) { // retval is our return value. CultureInfo retval; // Temporary hashtable for the names. Dictionary<string, CultureInfo> tempNameHT = s_NameCachedCultures; if (name != null) { name = CultureData.AnsiToLower(name); } if (altName != null) { altName = CultureData.AnsiToLower(altName); } // We expect the same result for both hashtables, but will test individually for added safety. if (tempNameHT == null) { tempNameHT = new Dictionary<string, CultureInfo>(); } else { // If we are called by name, check if the object exists in the hashtable. If so, return it. if (lcid == -1 || lcid == 0) { bool ret; lock (_lock) { ret = tempNameHT.TryGetValue(lcid == 0 ? name : name + '\xfffd' + altName, out retval); } if (ret && retval != null) { return retval; } } } // Next, the Lcid table. Dictionary<int, CultureInfo> tempLcidHT = s_LcidCachedCultures; if (tempLcidHT == null) { // Case insensitive is not an issue here, save the constructor call. tempLcidHT = new Dictionary<int, CultureInfo>(); } else { // If we were called by Lcid, check if the object exists in the table. If so, return it. if (lcid > 0) { bool ret; lock (_lock) { ret = tempLcidHT.TryGetValue(lcid, out retval); } if (ret && retval != null) { return retval; } } } // We now have two temporary hashtables and the desired object was not found. // We'll construct it. We catch any exceptions from the constructor call and return null. try { switch (lcid) { case -1: // call the private constructor retval = new CultureInfo(name, altName); break; case 0: retval = new CultureInfo(name, false); break; default: retval = new CultureInfo(lcid, false); break; } } catch (ArgumentException) { return null; } // Set it to read-only retval._isReadOnly = true; if (lcid == -1) { lock (_lock) { // This new culture will be added only to the name hash table. tempNameHT[name + '\xfffd' + altName] = retval; } // when lcid == -1 then TextInfo object is already get created and we need to set it as read only. retval.TextInfo.SetReadOnlyState(true); } else if (lcid == 0) { // Remember our name (as constructed). Do NOT use alternate sort name versions because // we have internal state representing the sort. (So someone would get the wrong cached version) string newName = CultureData.AnsiToLower(retval._name); // We add this new culture info object to both tables. lock (_lock) { tempNameHT[newName] = retval; } } else { lock (_lock) { tempLcidHT[lcid] = retval; } } // Copy the two hashtables to the corresponding member variables. This will potentially overwrite // new tables simultaneously created by a new thread, but maximizes thread safety. if (-1 != lcid) { // Only when we modify the lcid hash table, is there a need to overwrite. s_LcidCachedCultures = tempLcidHT; } s_NameCachedCultures = tempNameHT; // Finally, return our new CultureInfo object. return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). (LCID version)... use named version public static CultureInfo GetCultureInfo(int culture) { // Must check for -1 now since the helper function uses the value to signal // the altCulture code path for SQL Server. // Also check for zero as this would fail trying to add as a key to the hash. if (culture <= 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } CultureInfo retval = GetCultureInfoHelper(culture, null, null); if (null == retval) { throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); } return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). (Named version) public static CultureInfo GetCultureInfo(string name) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } CultureInfo retval = GetCultureInfoHelper(0, name, null); if (retval == null) { throw new CultureNotFoundException( nameof(name), name, SR.Argument_CultureNotSupported); } return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). public static CultureInfo GetCultureInfo(string name, string altName) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } if (altName == null) { throw new ArgumentNullException(nameof(altName)); } CultureInfo retval = GetCultureInfoHelper(-1, name, altName); if (retval == null) { throw new CultureNotFoundException("name or altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); } return retval; } // This function is deprecated, we don't like it public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { // Disallow old zh-CHT/zh-CHS names if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } CultureInfo ci = GetCultureInfo(name); // Disallow alt sorts and es-es_TS if (ci.LCID > 0xffff || ci.LCID == 0x040a) { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } return ci; } } }
using System; using System.Collections; namespace BinxEd { /// <summary> /// Summary description for DimNode. /// </summary> public class DimNode : ComplexNode { private string name_; //name of dimension private int count_; //=indexTo + 1 private DimNode child_; //embedded dim public DimNode(string name, int count) : base("dim") { this.name_ = name; this.count_ = count; this.child_ = null; } public DimNode(string name, string scount) : base("dim") { this.name_ = name; try { this.count_ = Convert.ToInt32(scount); } catch (Exception ex) { Console.WriteLine(ex.Message); } this.child_ = null; } /// <summary> /// Property to get or set the name of the dimension /// </summary> public string getDimName() { return this.name_; } public void setDimName(string name) { this.name_ = name; } /// <summary> /// Property to get or set the count parameter for the dimension /// </summary> public int count() { return this.count_; } public void setCount(int count) { this.count_ = count; } /// <summary> /// Property to get child dimension /// </summary> public DimNode getChild() { return this.child_; } public void setChild(DimNode node) { this.child_ = node; } /// <summary> /// Property to check whether this dimension has a child /// </summary> public bool hasChild() { return this.child_ != null; } /// <summary> /// Add or replace a child DimNode to this one, demote its child if available. /// </summary> /// <remarks>A DimNode can have only one child DimNode node. When this DimNode already has a child DimNode, /// the new child DimNode is set as the only child node and the old child node becomes the child node of the /// added child node (grandchild of this node). Note that if the given child node already has a child node, /// it will be lost in this case.</remarks> /// <param name="child"></param> public override void addChild(AbstractNode child) { if (child.GetType().Equals(typeof(DimNode))) { DimNode c = this.child_; this.child_ = (DimNode)child; if (c != null) { this.child_.setChild(c); } } } /// <summary> /// Insert child DimNode as the only child node with position ignored, same as addChild. /// </summary> /// <param name="child"></param> /// <param name="at">ignored here</param> public override void insertChild(AbstractNode child, int at) { addChild(child); // if (child.GetType().Equals(typeof(DimNode))) // { // setChild((DimNode)child); // } } /// <summary> /// Remove the only child node and promote the child's child node. /// </summary> /// <param name="at">ignored here</param> public override void removeChild(int at) { DimNode d = this.child_; if (d != null) { this.child_ = d.getChild(); } } /// <summary> /// Add a Dimension node to the leaf (lowest child) /// </summary> /// <param name="d"></param> public void addDescendant(DimNode d) { if (child_ != null) { child_.addDescendant(d); } else { child_ = d; } } /// <summary> /// Format a stack of dim elements in a hierarchy /// </summary> /// <returns></returns> public override string toXmlString() { string s = "<dim"; if (name_ != null && name_.Length > 0) { s += " name=\""+name_+"\""; } if (count_>0) { s += " indexTo=\""+Convert.ToString(count_-1)+"\""; } s += ">"; if (child_ != null) { Console.WriteLine("DimNode.toXmlString {0}", s); s += child_.toXmlString(); } s += "</dim>"; return s; } /// <summary> /// Format a string for display in the document treeview. /// </summary> /// <returns></returns> public override string toNodeText() { string s = "Dimension"; if (name_ != null && name_.Length > 0) { s += " " + name_; } if (count_ > 0) { s += " [" + Convert.ToString(count_) + "]"; } return s; } public override ArrayList validChildTypes() { ArrayList ar = new ArrayList(); ar.Add("dim"); return ar; } /* public override ArrayList validSiblingTypes() { return null; } public override bool canDelete() { return true; } */ public override ArrayList getProperties() { ArrayList props = new ArrayList(); props.Add(new Property("name", 1, name_)); props.Add(new Property("count", 1, Convert.ToString(count_))); return props; } public override void setProperty(string propertyName, string propertyValue) { //base.setProperty (propertyName, propertyValue); if (propertyName.Equals("name")) { this.name_ = propertyValue; } else if (propertyName.Equals("count")) { try { this.count_ = Convert.ToInt32(propertyValue); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } }
using System; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; // extra added for HID API // Marshal functions //using System.Collections; //using System.Data; //using System.Diagnostics; //using System.Drawing; //using System.Runtime.InteropServices; //using System.Windows.Forms; namespace DelcomSupport.LowLevel { public class DelcomHID { [StructLayout(LayoutKind.Sequential, Pack=1)] public struct HidTxPacketStruct { public Byte MajorCmd; public Byte MinorCmd; public Byte LSBData; public Byte MSBData; public Byte HidData0; public Byte HidData1; public Byte HidData2; public Byte HidData3; public Byte ExtData0; public Byte ExtData1; public Byte ExtData2; public Byte ExtData3; public Byte ExtData4; public Byte ExtData5; public Byte ExtData6; public Byte ExtData7; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct HidRxPacketStruct { public Byte Data0; public Byte Data1; public Byte Data2; public Byte Data3; public Byte Data4; public Byte Data5; public Byte Data6; public Byte Data7; //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] //public byte[] Data; //Data 1 .. 8 } // Class variables private SafeFileHandle myDeviceHandle; private Boolean myDeviceDetected; private String myDevicePathName; private DeviceManagement MyDeviceManagement = new DeviceManagement(); private Hid MyHid = new Hid(); private const String MODULE_NAME = "Delcom HID USB CS"; private UInt32 MatchingDevicesFound = 0; private HidTxPacketStruct myTxHidPacket; private HidRxPacketStruct myRxHidPacket; /// <summary> /// Initializes the class /// </summary> public DelcomHID() { //System.Windows.Forms.MessageBox.Show("Initializing DelcomHID"); } /// <summary> /// Reads the serial Number /// returns zero on sucess, else non-zero erro /// </summary> public UInt32 GetDeviceInfo(ref UInt32 SerialNumber, ref UInt32 Version, ref UInt32 Date, ref UInt32 Month, ref UInt32 Year ) { try { Byte[] Ans = new Byte[16]; Ans[0] = 10; if (Hid.HidD_GetFeature(myDeviceHandle, Ans, 8) == false) return (1); SerialNumber = Convert.ToUInt32(Ans[0]); SerialNumber += Convert.ToUInt32(Ans[1] <<8); SerialNumber += Convert.ToUInt32(Ans[2] << 16); SerialNumber += Convert.ToUInt32(Ans[3] << 24); Version = Convert.ToUInt32(Convert.ToByte(Ans[4])); Date = Convert.ToUInt32(Convert.ToByte(Ans[5])); Month = Convert.ToUInt32(Convert.ToByte(Ans[6])); Year = Convert.ToUInt32(Convert.ToByte(Ans[7])); return (0); } catch (Exception ex) { DisplayException(MODULE_NAME, ex); //throw; return (2); } } /// <summary> /// Writes the ports values /// returns zero on sucess, else non-zero erro /// </summary> public UInt32 SendCommand( HidTxPacketStruct TxCmd) { try { int Length; if (TxCmd.MajorCmd == 102) Length = 16; else Length = 8; if (Hid.HidD_SetFeature(myDeviceHandle, StructureToByteArray(TxCmd), Length) == false) return (1); else return (0); } catch (Exception ex) { DisplayException(MODULE_NAME, ex); //throw; return (2); } } /// <summary> /// Writes the ports values /// returns zero on sucess, else non-zero erro /// </summary> public UInt32 WritePorts(UInt32 Port0, UInt32 Port1) { try { myTxHidPacket.MajorCmd = 101; myTxHidPacket.MinorCmd = 10; myTxHidPacket.LSBData = Convert.ToByte(Port0); myTxHidPacket.MSBData = Convert.ToByte(Port1); if (Hid.HidD_SetFeature(myDeviceHandle, StructureToByteArray(myTxHidPacket), 8) == false) return (1); else return (0); } catch (Exception ex) { DisplayException(MODULE_NAME, ex); //throw; return (2); } } /// <summary> /// Reads the currenly value at port zero /// returns zero on sucess, else non-zero erro /// </summary> public UInt32 ReadPort0(ref UInt32 Port0) { try { Byte[] Ans = new Byte[16]; Ans[0] = 100; if (Hid.HidD_GetFeature(myDeviceHandle, Ans, 8) == false) return (1); Port0 = Convert.ToUInt32(Ans[0]); return (0); } catch (Exception ex) { DisplayException(MODULE_NAME, ex); //throw; return (2); } } /// <summary> /// Reads the currenly value at both ports /// returns zero on sucess, else non-zero erro /// </summary> public UInt32 ReadPorts(ref UInt32 Port0, ref UInt32 Port1) { try { Byte[] Ans = new Byte[16]; Ans[0] = 100; if (Hid.HidD_GetFeature(myDeviceHandle, Ans, 8) == false) return (1); Port0 = Convert.ToUInt32(Ans[0]); Port1 = Convert.ToUInt32(Ans[1]); return (0); } catch (Exception ex) { DisplayException(MODULE_NAME, ex); //throw; return (2); } } /// <summary> /// Closed the USB HID devicde /// </summary> public UInt32 Close() { try { if (!myDeviceHandle.IsClosed) { myDeviceHandle.Close(); } } catch (Exception ex) { //throw; return (2); } return (0); } /// <summary> /// Opens the first matching device found /// Return zero on success, /// otherwise non-zero error /// </summary> public UInt32 Open() { return (OpenNthDevice(1)); } /// <summary> /// Return non-zero if openned /// otherwise non-zero error /// </summary> public bool IsOpen() { if (myDeviceHandle==null || myDeviceHandle.IsClosed || myDeviceHandle.IsClosed) return (false); else return (true); } /// <summary> /// Opens the Nth matching device found /// Return zero on success, /// otherwise non-zero error /// </summary> public UInt32 OpenNthDevice(UInt32 NthDevice) { if (myDeviceHandle != null) Close(); // if the device is already open, then close it first. if (!FindTheHid(NthDevice)) return (1); myDeviceHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ | FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); if (myDeviceHandle.IsInvalid) return (2); return (0); // device found } // Get the device name of the current device public string GetDeviceName() { return (myDevicePathName); } // Returns a count of the matching device on the current system public UInt32 GetDevicesCount() { FindTheHid(0); return (MatchingDevicesFound); } /// <summary> /// Uses a series of API calls to locate a HID-class device /// by its Vendor ID, Product ID and by the Nth number on the list. /// NthDevice: 0=none, used to determine how many matching device are currently /// installed on the system. 1=Find the first matching device, 2=the second matching device, /// and so on... /// </summary> /// /// <returns> /// True if the device is detected, False if not detected. /// </returns> private Boolean FindTheHid(UInt32 NthDevice) { Boolean deviceFound = false; String[] devicePathName = new String[512]; // Apr 20, 2009 - Increase size from 128 to 512. SafeFileHandle hidHandle; Guid hidGuid = Guid.Empty; Int32 memberIndex = 0; UInt16 myProductID = 0xB080; UInt16 myVendorID = 0x0FC5; Boolean success = false; UInt32 MatchingDevices = 0; try { myDeviceDetected = false; Hid.HidD_GetHidGuid(ref hidGuid); //Retrieves the interface class GUID for the HID class. // Fill an array with the device path names of all attached HIDs. deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. if (deviceFound) { memberIndex = 0; do { // Open the device hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); if (!hidHandle.IsInvalid) { // Device openned, now find out if it's the device we want. MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes); // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, // Product ID, and Product Version Number for a device. success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if (success) { // Find out if the device matches the one we're looking for. if ((MyHid.DeviceAttributes.VendorID == myVendorID) & (MyHid.DeviceAttributes.ProductID == myProductID)) { MatchingDevices++; myDeviceDetected = true; } if( myDeviceDetected && (MatchingDevices == NthDevice ) ) { // Device found // Save the DevicePathName myDevicePathName = devicePathName[memberIndex]; hidHandle.Close(); } else { // It's not a match, so close the handle. try the next one myDeviceDetected = false; hidHandle.Close(); } } else { // There was a problem in retrieving the information. myDeviceDetected = false; hidHandle.Close(); } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; } while (!((myDeviceDetected | (memberIndex == devicePathName.Length)))); } MatchingDevicesFound = MatchingDevices; // save the device found count return myDeviceDetected; } catch (Exception ex) { DisplayException(MODULE_NAME, ex); throw; } } /// <summary> /// Provides a central mechanism for exception handling. /// Displays a message box that describes the exception. /// </summary> /// /// <param name="moduleName"> the module where the exception occurred. </param> /// <param name="e"> the exception </param> //TODO: Fix public static void DisplayException(String moduleName, Exception e) { String message = null; String caption = null; // Create an error message. message = "Exception: " + e.Message + "\r\n" + "Module: " + moduleName + "\r\n" + "Method: " + e.TargetSite.Name; caption = "Unexpected Exception"; //System.Windows.Forms.MessageBox.Show(message, caption, System.Windows.Forms.MessageBoxButtons.OK); //throw; } // Converts a Structure to byte[] static byte[] StructureToByteArray(object obj) { int len = Marshal.SizeOf(obj); byte[] arr = new byte[len]; IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, len); Marshal.FreeHGlobal(ptr); return arr; } // Converts a byte[] to Structure static void ByteArrayToStructure(byte[] bytearray, ref object obj) { int len = Marshal.SizeOf(obj); IntPtr i = Marshal.AllocHGlobal(len); Marshal.Copy(bytearray, 0, i, len); obj = Marshal.PtrToStructure(i, obj.GetType()); Marshal.FreeHGlobal(i); } } // end of the DelcomHID class }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnIngreso class. /// </summary> [Serializable] public partial class PnIngresoCollection : ActiveList<PnIngreso, PnIngresoCollection> { public PnIngresoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnIngresoCollection</returns> public PnIngresoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnIngreso o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_ingreso table. /// </summary> [Serializable] public partial class PnIngreso : ActiveRecord<PnIngreso>, IActiveRecord { #region .ctors and Default Settings public PnIngreso() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnIngreso(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnIngreso(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnIngreso(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_ingreso", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdIngreso = new TableSchema.TableColumn(schema); colvarIdIngreso.ColumnName = "id_ingreso"; colvarIdIngreso.DataType = DbType.Int32; colvarIdIngreso.MaxLength = 0; colvarIdIngreso.AutoIncrement = true; colvarIdIngreso.IsNullable = false; colvarIdIngreso.IsPrimaryKey = true; colvarIdIngreso.IsForeignKey = false; colvarIdIngreso.IsReadOnly = false; colvarIdIngreso.DefaultSetting = @""; colvarIdIngreso.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdIngreso); TableSchema.TableColumn colvarCuie = new TableSchema.TableColumn(schema); colvarCuie.ColumnName = "cuie"; colvarCuie.DataType = DbType.AnsiString; colvarCuie.MaxLength = 10; colvarCuie.AutoIncrement = false; colvarCuie.IsNullable = true; colvarCuie.IsPrimaryKey = false; colvarCuie.IsForeignKey = false; colvarCuie.IsReadOnly = false; colvarCuie.DefaultSetting = @""; colvarCuie.ForeignKeyTableName = ""; schema.Columns.Add(colvarCuie); TableSchema.TableColumn colvarMontoPrefactura = new TableSchema.TableColumn(schema); colvarMontoPrefactura.ColumnName = "monto_prefactura"; colvarMontoPrefactura.DataType = DbType.Decimal; colvarMontoPrefactura.MaxLength = 0; colvarMontoPrefactura.AutoIncrement = false; colvarMontoPrefactura.IsNullable = true; colvarMontoPrefactura.IsPrimaryKey = false; colvarMontoPrefactura.IsForeignKey = false; colvarMontoPrefactura.IsReadOnly = false; colvarMontoPrefactura.DefaultSetting = @""; colvarMontoPrefactura.ForeignKeyTableName = ""; schema.Columns.Add(colvarMontoPrefactura); TableSchema.TableColumn colvarFechaPrefactura = new TableSchema.TableColumn(schema); colvarFechaPrefactura.ColumnName = "fecha_prefactura"; colvarFechaPrefactura.DataType = DbType.DateTime; colvarFechaPrefactura.MaxLength = 0; colvarFechaPrefactura.AutoIncrement = false; colvarFechaPrefactura.IsNullable = true; colvarFechaPrefactura.IsPrimaryKey = false; colvarFechaPrefactura.IsForeignKey = false; colvarFechaPrefactura.IsReadOnly = false; colvarFechaPrefactura.DefaultSetting = @""; colvarFechaPrefactura.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaPrefactura); TableSchema.TableColumn colvarMontoFactura = new TableSchema.TableColumn(schema); colvarMontoFactura.ColumnName = "monto_factura"; colvarMontoFactura.DataType = DbType.Decimal; colvarMontoFactura.MaxLength = 0; colvarMontoFactura.AutoIncrement = false; colvarMontoFactura.IsNullable = true; colvarMontoFactura.IsPrimaryKey = false; colvarMontoFactura.IsForeignKey = false; colvarMontoFactura.IsReadOnly = false; colvarMontoFactura.DefaultSetting = @""; colvarMontoFactura.ForeignKeyTableName = ""; schema.Columns.Add(colvarMontoFactura); TableSchema.TableColumn colvarFechaFactura = new TableSchema.TableColumn(schema); colvarFechaFactura.ColumnName = "fecha_factura"; colvarFechaFactura.DataType = DbType.DateTime; colvarFechaFactura.MaxLength = 0; colvarFechaFactura.AutoIncrement = false; colvarFechaFactura.IsNullable = true; colvarFechaFactura.IsPrimaryKey = false; colvarFechaFactura.IsForeignKey = false; colvarFechaFactura.IsReadOnly = false; colvarFechaFactura.DefaultSetting = @""; colvarFechaFactura.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaFactura); TableSchema.TableColumn colvarComentario = new TableSchema.TableColumn(schema); colvarComentario.ColumnName = "comentario"; colvarComentario.DataType = DbType.AnsiString; colvarComentario.MaxLength = -1; colvarComentario.AutoIncrement = false; colvarComentario.IsNullable = true; colvarComentario.IsPrimaryKey = false; colvarComentario.IsForeignKey = false; colvarComentario.IsReadOnly = false; colvarComentario.DefaultSetting = @""; colvarComentario.ForeignKeyTableName = ""; schema.Columns.Add(colvarComentario); TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema); colvarUsuario.ColumnName = "usuario"; colvarUsuario.DataType = DbType.AnsiString; colvarUsuario.MaxLength = -1; colvarUsuario.AutoIncrement = false; colvarUsuario.IsNullable = true; colvarUsuario.IsPrimaryKey = false; colvarUsuario.IsForeignKey = false; colvarUsuario.IsReadOnly = false; colvarUsuario.DefaultSetting = @""; colvarUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarUsuario); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = true; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarNumeroFactura = new TableSchema.TableColumn(schema); colvarNumeroFactura.ColumnName = "numero_factura"; colvarNumeroFactura.DataType = DbType.Int32; colvarNumeroFactura.MaxLength = 0; colvarNumeroFactura.AutoIncrement = false; colvarNumeroFactura.IsNullable = true; colvarNumeroFactura.IsPrimaryKey = false; colvarNumeroFactura.IsForeignKey = false; colvarNumeroFactura.IsReadOnly = false; colvarNumeroFactura.DefaultSetting = @""; colvarNumeroFactura.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumeroFactura); TableSchema.TableColumn colvarFechaDeposito = new TableSchema.TableColumn(schema); colvarFechaDeposito.ColumnName = "fecha_deposito"; colvarFechaDeposito.DataType = DbType.DateTime; colvarFechaDeposito.MaxLength = 0; colvarFechaDeposito.AutoIncrement = false; colvarFechaDeposito.IsNullable = true; colvarFechaDeposito.IsPrimaryKey = false; colvarFechaDeposito.IsForeignKey = false; colvarFechaDeposito.IsReadOnly = false; colvarFechaDeposito.DefaultSetting = @""; colvarFechaDeposito.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaDeposito); TableSchema.TableColumn colvarMontoDeposito = new TableSchema.TableColumn(schema); colvarMontoDeposito.ColumnName = "monto_deposito"; colvarMontoDeposito.DataType = DbType.Decimal; colvarMontoDeposito.MaxLength = 0; colvarMontoDeposito.AutoIncrement = false; colvarMontoDeposito.IsNullable = true; colvarMontoDeposito.IsPrimaryKey = false; colvarMontoDeposito.IsForeignKey = false; colvarMontoDeposito.IsReadOnly = false; colvarMontoDeposito.DefaultSetting = @""; colvarMontoDeposito.ForeignKeyTableName = ""; schema.Columns.Add(colvarMontoDeposito); TableSchema.TableColumn colvarIdServicio = new TableSchema.TableColumn(schema); colvarIdServicio.ColumnName = "id_servicio"; colvarIdServicio.DataType = DbType.Int32; colvarIdServicio.MaxLength = 0; colvarIdServicio.AutoIncrement = false; colvarIdServicio.IsNullable = true; colvarIdServicio.IsPrimaryKey = false; colvarIdServicio.IsForeignKey = false; colvarIdServicio.IsReadOnly = false; colvarIdServicio.DefaultSetting = @""; colvarIdServicio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdServicio); TableSchema.TableColumn colvarFechaNotificacion = new TableSchema.TableColumn(schema); colvarFechaNotificacion.ColumnName = "fecha_notificacion"; colvarFechaNotificacion.DataType = DbType.DateTime; colvarFechaNotificacion.MaxLength = 0; colvarFechaNotificacion.AutoIncrement = false; colvarFechaNotificacion.IsNullable = true; colvarFechaNotificacion.IsPrimaryKey = false; colvarFechaNotificacion.IsForeignKey = false; colvarFechaNotificacion.IsReadOnly = false; colvarFechaNotificacion.DefaultSetting = @""; colvarFechaNotificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaNotificacion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_ingreso",schema); } } #endregion #region Props [XmlAttribute("IdIngreso")] [Bindable(true)] public int IdIngreso { get { return GetColumnValue<int>(Columns.IdIngreso); } set { SetColumnValue(Columns.IdIngreso, value); } } [XmlAttribute("Cuie")] [Bindable(true)] public string Cuie { get { return GetColumnValue<string>(Columns.Cuie); } set { SetColumnValue(Columns.Cuie, value); } } [XmlAttribute("MontoPrefactura")] [Bindable(true)] public decimal? MontoPrefactura { get { return GetColumnValue<decimal?>(Columns.MontoPrefactura); } set { SetColumnValue(Columns.MontoPrefactura, value); } } [XmlAttribute("FechaPrefactura")] [Bindable(true)] public DateTime? FechaPrefactura { get { return GetColumnValue<DateTime?>(Columns.FechaPrefactura); } set { SetColumnValue(Columns.FechaPrefactura, value); } } [XmlAttribute("MontoFactura")] [Bindable(true)] public decimal? MontoFactura { get { return GetColumnValue<decimal?>(Columns.MontoFactura); } set { SetColumnValue(Columns.MontoFactura, value); } } [XmlAttribute("FechaFactura")] [Bindable(true)] public DateTime? FechaFactura { get { return GetColumnValue<DateTime?>(Columns.FechaFactura); } set { SetColumnValue(Columns.FechaFactura, value); } } [XmlAttribute("Comentario")] [Bindable(true)] public string Comentario { get { return GetColumnValue<string>(Columns.Comentario); } set { SetColumnValue(Columns.Comentario, value); } } [XmlAttribute("Usuario")] [Bindable(true)] public string Usuario { get { return GetColumnValue<string>(Columns.Usuario); } set { SetColumnValue(Columns.Usuario, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime? Fecha { get { return GetColumnValue<DateTime?>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("NumeroFactura")] [Bindable(true)] public int? NumeroFactura { get { return GetColumnValue<int?>(Columns.NumeroFactura); } set { SetColumnValue(Columns.NumeroFactura, value); } } [XmlAttribute("FechaDeposito")] [Bindable(true)] public DateTime? FechaDeposito { get { return GetColumnValue<DateTime?>(Columns.FechaDeposito); } set { SetColumnValue(Columns.FechaDeposito, value); } } [XmlAttribute("MontoDeposito")] [Bindable(true)] public decimal? MontoDeposito { get { return GetColumnValue<decimal?>(Columns.MontoDeposito); } set { SetColumnValue(Columns.MontoDeposito, value); } } [XmlAttribute("IdServicio")] [Bindable(true)] public int? IdServicio { get { return GetColumnValue<int?>(Columns.IdServicio); } set { SetColumnValue(Columns.IdServicio, value); } } [XmlAttribute("FechaNotificacion")] [Bindable(true)] public DateTime? FechaNotificacion { get { return GetColumnValue<DateTime?>(Columns.FechaNotificacion); } set { SetColumnValue(Columns.FechaNotificacion, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCuie,decimal? varMontoPrefactura,DateTime? varFechaPrefactura,decimal? varMontoFactura,DateTime? varFechaFactura,string varComentario,string varUsuario,DateTime? varFecha,int? varNumeroFactura,DateTime? varFechaDeposito,decimal? varMontoDeposito,int? varIdServicio,DateTime? varFechaNotificacion) { PnIngreso item = new PnIngreso(); item.Cuie = varCuie; item.MontoPrefactura = varMontoPrefactura; item.FechaPrefactura = varFechaPrefactura; item.MontoFactura = varMontoFactura; item.FechaFactura = varFechaFactura; item.Comentario = varComentario; item.Usuario = varUsuario; item.Fecha = varFecha; item.NumeroFactura = varNumeroFactura; item.FechaDeposito = varFechaDeposito; item.MontoDeposito = varMontoDeposito; item.IdServicio = varIdServicio; item.FechaNotificacion = varFechaNotificacion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdIngreso,string varCuie,decimal? varMontoPrefactura,DateTime? varFechaPrefactura,decimal? varMontoFactura,DateTime? varFechaFactura,string varComentario,string varUsuario,DateTime? varFecha,int? varNumeroFactura,DateTime? varFechaDeposito,decimal? varMontoDeposito,int? varIdServicio,DateTime? varFechaNotificacion) { PnIngreso item = new PnIngreso(); item.IdIngreso = varIdIngreso; item.Cuie = varCuie; item.MontoPrefactura = varMontoPrefactura; item.FechaPrefactura = varFechaPrefactura; item.MontoFactura = varMontoFactura; item.FechaFactura = varFechaFactura; item.Comentario = varComentario; item.Usuario = varUsuario; item.Fecha = varFecha; item.NumeroFactura = varNumeroFactura; item.FechaDeposito = varFechaDeposito; item.MontoDeposito = varMontoDeposito; item.IdServicio = varIdServicio; item.FechaNotificacion = varFechaNotificacion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdIngresoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CuieColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn MontoPrefacturaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn FechaPrefacturaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn MontoFacturaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn FechaFacturaColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn ComentarioColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn UsuarioColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn NumeroFacturaColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn FechaDepositoColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn MontoDepositoColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn IdServicioColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn FechaNotificacionColumn { get { return Schema.Columns[13]; } } #endregion #region Columns Struct public struct Columns { public static string IdIngreso = @"id_ingreso"; public static string Cuie = @"cuie"; public static string MontoPrefactura = @"monto_prefactura"; public static string FechaPrefactura = @"fecha_prefactura"; public static string MontoFactura = @"monto_factura"; public static string FechaFactura = @"fecha_factura"; public static string Comentario = @"comentario"; public static string Usuario = @"usuario"; public static string Fecha = @"fecha"; public static string NumeroFactura = @"numero_factura"; public static string FechaDeposito = @"fecha_deposito"; public static string MontoDeposito = @"monto_deposito"; public static string IdServicio = @"id_servicio"; public static string FechaNotificacion = @"fecha_notificacion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Globalization; /// <summary> /// Clone /// </summary> public class DateTimeFormatInfoClone { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Clone method on a instance created from Ctor"); try { DateTimeFormatInfo expected = new DateTimeFormatInfo(); retVal = VerificationHelper(expected, expected.Clone(), "001.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Clone method on a instance created from several cultures"); try { DateTimeFormatInfo expected = new CultureInfo("en-us").DateTimeFormat; retVal = VerificationHelper(expected, expected.Clone(), "002.1") && retVal; expected = new CultureInfo("fr-FR").DateTimeFormat; retVal = VerificationHelper(expected, expected.Clone(), "002.2") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call Clone method on a readonly instance created from several cultures"); try { DateTimeFormatInfo expected = CultureInfo.InvariantCulture.DateTimeFormat; retVal = VerificationHelper(expected, expected.Clone(), "003.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DateTimeFormatInfoClone test = new DateTimeFormatInfoClone(); TestLibrary.TestFramework.BeginTestCase("DateTimeFormatInfoClone"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerificationHelper(DateTimeFormatInfo expected, Object obj, string errorno) { bool retval = true; if (!(obj is DateTimeFormatInfo)) { TestLibrary.TestFramework.LogError(errorno + ".1", "Calling Clone method does not return an DateTimeFormatInfo copy"); retval = false; } DateTimeFormatInfo actual = obj as DateTimeFormatInfo; if ( actual.IsReadOnly ) { TestLibrary.TestFramework.LogError(errorno + ".2", "Calling Clone method makes DateTimeFormatInfo copy read only"); retval = false; } retval = IsEquals(actual.AbbreviatedDayNames, expected.AbbreviatedDayNames, errorno + ".3") && IsEquals(actual.AbbreviatedMonthGenitiveNames, expected.AbbreviatedMonthGenitiveNames, errorno + ".4") && IsEquals(actual.AbbreviatedMonthNames, expected.AbbreviatedMonthNames, errorno + ".5") && IsEquals(actual.DayNames, expected.DayNames, errorno + ".6") && IsEquals(actual.MonthGenitiveNames, expected.MonthGenitiveNames, errorno + ".7") && IsEquals(actual.MonthNames, expected.MonthNames, errorno + ".8") && IsEquals(actual.ShortestDayNames, expected.ShortestDayNames, errorno + ".9") && IsEquals(actual.AMDesignator, expected.AMDesignator, errorno + ".10") && //DateTimeFormatInfo.DateSeparator property has been removed IsEquals(actual.FullDateTimePattern, expected.FullDateTimePattern, errorno + ".12") && IsEquals(actual.LongDatePattern, expected.LongDatePattern, errorno + ".13") && IsEquals(actual.LongTimePattern, expected.LongTimePattern, errorno + ".14") && IsEquals(actual.MonthDayPattern, expected.MonthDayPattern, errorno + ".15") && IsEquals(actual.PMDesignator, expected.PMDesignator, errorno + ".17") && IsEquals(actual.RFC1123Pattern, expected.RFC1123Pattern, errorno + ".18") && IsEquals(actual.ShortDatePattern, expected.ShortDatePattern, errorno + ".19") && IsEquals(actual.ShortTimePattern, expected.ShortTimePattern, errorno + ".20") && IsEquals(actual.SortableDateTimePattern, expected.SortableDateTimePattern, errorno + ".21") && //DateTimeFormatInfo.TimeSeparator property has been removed IsEquals(actual.UniversalSortableDateTimePattern, expected.UniversalSortableDateTimePattern, errorno + ".23") && IsEquals(actual.YearMonthPattern, expected.YearMonthPattern, errorno + ".24") && IsEquals(actual.CalendarWeekRule, expected.CalendarWeekRule, errorno + ".25") && IsEquals(actual.FirstDayOfWeek, expected.FirstDayOfWeek, errorno + ".26") && retval; return retval; } private bool IsEquals(string str1, string str2, string errorno) { bool retVal = true; if (str1 != str2) { TestLibrary.TestFramework.LogError(errorno, "Two string are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] str1 = " + str1 + ", str2 = " + str2); retVal = false; } return retVal; } private bool IsEquals(DayOfWeek value1, DayOfWeek value2, string errorno) { bool retVal = true; if (value1 != value2) { TestLibrary.TestFramework.LogError(errorno, "Two values are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] value1 = " + value1 + ", value2 = " + value2); retVal = false; } return retVal; } private bool IsEquals(CalendarWeekRule value1, CalendarWeekRule value2, string errorno) { bool retVal = true; if (value1 != value2) { TestLibrary.TestFramework.LogError(errorno, "Two values are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] value1 = " + value1 + ", value2 = " + value2); retVal = false; } return retVal; } private bool IsEquals(string[] array1, string[] array2, string errorno) { bool retval = true; if ((array1 == null) && (array2 == null)) { return true; } if ((array1 == null) && (array2 != null)) { return false; } if ((array1 != null) && (array2 == null)) { return false; } if (array1.Length != array2.Length) { return false; } for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { TestLibrary.TestFramework.LogError(errorno, "Two arrays are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] array1[i] = " + array1[i] + ", array2[i] = " + array2[i] + ", i = " + i); retval = false; break; } } return retval; } #endregion }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #if CORECLR // Use stubs for SerializableAttribute using Microsoft.PowerShell.CoreClr.Stubs; #endif namespace System.Management.Automation { [Flags] internal enum VariablePathFlags { None = 0x00, Local = 0x01, Script = 0x02, Global = 0x04, Private = 0x08, Variable = 0x10, Function = 0x20, DriveQualified = 0x40, Unqualified = 0x80, // If any of these bits are set, the path does not represent an unscoped variable. UnscopedVariableMask = Local | Script | Global | Private | Function | DriveQualified, } /// <summary> /// A variable path that you can query the scope and drive of the variable reference. /// </summary> public class VariablePath { #region private data /// <summary> /// Stores the path that was passed to the constructor. /// </summary> private string _userPath; /// <summary> /// The name of the variable without any scope or drive. /// </summary> private string _unqualifiedPath; /// <summary> /// Store flags about the path, such as private/global/local/etc. /// </summary> private VariablePathFlags _flags = VariablePathFlags.None; #endregion private data #region Constructor /// <summary> /// Private constructor for CloneAndSetLocal(). /// </summary> private VariablePath() { } /// <summary> /// Constructs a variable path. /// </summary> /// <param name="path">The path to parse.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> public VariablePath(string path) : this(path, VariablePathFlags.None) { } /// <summary> /// Constructs a scoped item lookup path. /// </summary> /// /// <param name="path">The path to parse.</param> /// <param name="knownFlags"> /// These flags for anything known about the path (such as, is it a function) before /// being scanned. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> internal VariablePath(string path, VariablePathFlags knownFlags) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } _userPath = path; _flags = knownFlags; string candidateScope = null; string candidateScopeUpper = null; VariablePathFlags candidateFlags = VariablePathFlags.Unqualified; int currentCharIndex = 0; int lastScannedColon = -1; scanScope: switch (path[0]) { case 'g': case 'G': candidateScope = "lobal"; candidateScopeUpper = "LOBAL"; candidateFlags = VariablePathFlags.Global; break; case 'l': case 'L': candidateScope = "ocal"; candidateScopeUpper = "OCAL"; candidateFlags = VariablePathFlags.Local; break; case 'p': case 'P': candidateScope = "rivate"; candidateScopeUpper = "RIVATE"; candidateFlags = VariablePathFlags.Private; break; case 's': case 'S': candidateScope = "cript"; candidateScopeUpper = "CRIPT"; candidateFlags = VariablePathFlags.Script; break; case 'v': case 'V': if (knownFlags == VariablePathFlags.None) { // If we see 'variable:', our namespaceId will be empty, and // we'll also need to scan for the scope again. candidateScope = "ariable"; candidateScopeUpper = "ARIABLE"; candidateFlags = VariablePathFlags.Variable; } break; } if (candidateScope != null) { currentCharIndex += 1; // First character already matched. int j; for (j = 0; currentCharIndex < path.Length && j < candidateScope.Length; ++j, ++currentCharIndex) { if (path[currentCharIndex] != candidateScope[j] && path[currentCharIndex] != candidateScopeUpper[j]) { break; } } if (j == candidateScope.Length && currentCharIndex < path.Length && path[currentCharIndex] == ':') { if (_flags == VariablePathFlags.None) { _flags = VariablePathFlags.Variable; } _flags |= candidateFlags; lastScannedColon = currentCharIndex; currentCharIndex += 1; // If saw 'variable:', we need to look for a scope after 'variable:'. if (candidateFlags == VariablePathFlags.Variable) { knownFlags = VariablePathFlags.Variable; candidateScope = candidateScopeUpper = null; candidateFlags = VariablePathFlags.None; goto scanScope; } } } if (_flags == VariablePathFlags.None) { lastScannedColon = path.IndexOf(':', currentCharIndex); // No colon, or a colon as the first character means we have // a simple variable, otherwise it's a drive. if (lastScannedColon > 0) { _flags = VariablePathFlags.DriveQualified; } } if (lastScannedColon == -1) { _unqualifiedPath = _userPath; } else { _unqualifiedPath = _userPath.Substring(lastScannedColon + 1); } if (_flags == VariablePathFlags.None) { _flags = VariablePathFlags.Unqualified | VariablePathFlags.Variable; } } internal VariablePath CloneAndSetLocal() { Debug.Assert(IsUnscopedVariable, "Special method to clone, input must be unqualified"); VariablePath result = new VariablePath(); result._userPath = _userPath; result._unqualifiedPath = _unqualifiedPath; result._flags = VariablePathFlags.Local | VariablePathFlags.Variable; return result; } #endregion Constructor #region data accessors /// <summary> /// Gets the full path including any possibly specified scope and/or drive name. /// </summary> public string UserPath { get { return _userPath; } } /// <summary> /// Returns true if the path explicitly specifies 'global:'. /// </summary> public bool IsGlobal { get { return 0 != (_flags & VariablePathFlags.Global); } } /// <summary> /// Returns true if the path explicitly specifies 'local:'. /// </summary> public bool IsLocal { get { return 0 != (_flags & VariablePathFlags.Local); } } /// <summary> /// Returns true if the path explicitly specifies 'private:'. /// </summary> public bool IsPrivate { get { return 0 != (_flags & VariablePathFlags.Private); } } /// <summary> /// Returns true if the path explicitly specifies 'script:'. /// </summary> public bool IsScript { get { return 0 != (_flags & VariablePathFlags.Script); } } /// <summary> /// Returns true if the path specifies no drive or scope qualifiers. /// </summary> public bool IsUnqualified { get { return 0 != (_flags & VariablePathFlags.Unqualified); } } /// <summary> /// Returns true if the path specifies a variable path with no scope qualifiers. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unscoped")] public bool IsUnscopedVariable { get { return (0 == (_flags & VariablePathFlags.UnscopedVariableMask)); } } /// <summary> /// Returns true if the path defines a variable. /// </summary> public bool IsVariable { get { return 0 != (_flags & VariablePathFlags.Variable); } } /// <summary> /// Returns true if the path defines a function. /// </summary> internal bool IsFunction { get { return 0 != (_flags & VariablePathFlags.Function); } } /// <summary> /// Returns true if the path specifies a drive other than the variable drive. /// </summary> public bool IsDriveQualified { get { return 0 != (_flags & VariablePathFlags.DriveQualified); } } /// <summary> /// The drive name, or null if the path is for a variable. /// It may also be null for some functions (specifically if this is a FunctionScopedItemLookupPath.) /// </summary> public string DriveName { get { if (!IsDriveQualified) { return null; } // The drive name is asked for infrequently. Lots of VariablePath // objects are created, so rather than allocate an extra string that will // always be null, just compute the drive name on demand. return _userPath.Substring(0, _userPath.IndexOf(':')); } } /// <summary> /// Gets the namespace specific string /// </summary> internal string UnqualifiedPath { get { return _unqualifiedPath; } } /// <summary> /// Return the drive qualified name, if any drive specified, otherwise the simple variable name. /// </summary> internal string QualifiedName { get { return IsDriveQualified ? _userPath : _unqualifiedPath; } } #endregion data accessors /// <summary> /// Helpful for debugging. /// </summary> public override string ToString() { return _userPath; } } internal class FunctionLookupPath : VariablePath { internal FunctionLookupPath(string path) : base(path, VariablePathFlags.Function | VariablePathFlags.Unqualified) { } } } // namespace System.Management.Automation
using System; using System.Linq; using System.Reflection; using Xunit; using Should; namespace AutoMapper.UnitTests { namespace ConditionalMapping { public class When_configuring_a_member_to_skip_based_on_the_property_value : AutoMapperSpecBase { public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Value, opt => opt.Condition(src => src.Value > 0)); }); [Fact] public void Should_skip_the_mapping_when_the_condition_is_true() { var destination = Mapper.Map<Source, Destination>(new Source {Value = -1}); destination.Value.ShouldEqual(0); } [Fact] public void Should_execute_the_mapping_when_the_condition_is_false() { var destination = Mapper.Map<Source, Destination>(new Source { Value = 7 }); destination.Value.ShouldEqual(7); } } public class When_configuring_a_member_to_skip_based_on_the_property_value_with_custom_mapping : AutoMapperSpecBase { public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Value, opt => { opt.Condition(src => src.Value > 0); opt.ResolveUsing((Source src) => { return 10; }); }); }); [Fact] public void Should_skip_the_mapping_when_the_condition_is_true() { var destination = Mapper.Map<Source, Destination>(new Source { Value = -1 }); destination.Value.ShouldEqual(0); } [Fact] public void Should_execute_the_mapping_when_the_condition_is_false() { Mapper.Map<Source, Destination>(new Source { Value = 7 }).Value.ShouldEqual(10); } } public class When_configuring_a_map_to_ignore_all_properties_with_an_inaccessible_setter : AutoMapperSpecBase { private Destination _destination; public class Source { public int Id { get; set; } public string Title { get; set; } public string CodeName { get; set; } public string Nickname { get; set; } public string ScreenName { get; set; } } public class Destination { private double _height; public int Id { get; set; } public virtual string Name { get; protected set; } public string Title { get; internal set; } public string CodeName { get; private set; } public string Nickname { get; private set; } public string ScreenName { get; private set; } public int Age { get; private set; } public double Height { get { return _height; } } public Destination() { _height = 60; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.ScreenName, opt => opt.MapFrom(src => src.ScreenName)) .IgnoreAllPropertiesWithAnInaccessibleSetter() .ForMember(dest => dest.Nickname, opt => opt.MapFrom(src => src.Nickname)); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Id = 5, CodeName = "007", Nickname = "Jimmy", ScreenName = "jbogard" }); } [Fact] public void Should_consider_the_configuration_valid_even_if_some_properties_with_an_inaccessible_setter_are_unmapped() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid); } [Fact] public void Should_map_a_property_with_an_inaccessible_setter_if_a_specific_mapping_is_configured_after_the_ignore_method() { _destination.Nickname.ShouldEqual("Jimmy"); } [Fact] public void Should_not_map_a_property_with_an_inaccessible_setter_if_no_specific_mapping_is_configured_even_though_name_and_type_match() { _destination.CodeName.ShouldBeNull(); } [Fact] public void Should_not_map_a_property_with_no_public_setter_if_a_specific_mapping_is_configured_before_the_ignore_method() { _destination.ScreenName.ShouldBeNull(); } } public class When_configuring_a_reverse_map_to_ignore_all_source_properties_with_an_inaccessible_setter : AutoMapperSpecBase { private Destination _destination; private Source _source; public class Source { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Force { get; set; } public string ReverseForce { get; private set; } public string Respect { get; private set; } public int Foo { get; private set; } public int Bar { get; protected set; } public void Initialize() { ReverseForce = "You With"; Respect = "R-E-S-P-E-C-T"; } } public class Destination { public string Name { get; set; } public int Age { get; set; } public bool IsVisible { get; set; } public string Force { get; private set; } public string ReverseForce { get; set; } public string Respect { get; set; } public int Foz { get; private set; } public int Baz { get; protected set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .IgnoreAllPropertiesWithAnInaccessibleSetter() .ForMember(dest => dest.IsVisible, opt => opt.Ignore()) .ForMember(dest => dest.Force, opt => opt.MapFrom(src => src.Force)) .ReverseMap() .IgnoreAllSourcePropertiesWithAnInaccessibleSetter() .ForMember(dest => dest.ReverseForce, opt => opt.MapFrom(src => src.ReverseForce)) .ForSourceMember(dest => dest.IsVisible, opt => opt.Ignore()); }); protected override void Because_of() { var source = new Source { Id = 5, Name = "Bob", Age = 35, Force = "With You" }; source.Initialize(); _destination = Mapper.Map<Source, Destination>(source); _source = Mapper.Map<Destination, Source>(_destination); } [Fact] public void Should_consider_the_configuration_valid_even_if_some_properties_with_an_inaccessible_setter_are_unmapped() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid); } [Fact] public void Should_forward_and_reverse_map_a_property_that_is_accessible_on_both_source_and_destination() { _source.Name.ShouldEqual("Bob"); } [Fact] public void Should_forward_and_reverse_map_an_inaccessible_destination_property_if_a_mapping_is_defined() { _source.Force.ShouldEqual("With You"); } [Fact] public void Should_forward_and_reverse_map_an_inaccessible_source_property_if_a_mapping_is_defined() { _source.ReverseForce.ShouldEqual("You With"); } [Fact] public void Should_forward_and_reverse_map_an_inaccessible_source_property_even_if_a_mapping_is_not_defined() { _source.Respect.ShouldEqual("R-E-S-P-E-C-T"); // justification: if the mapping works one way, it should work in reverse } } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; using System.Collections.Generic; using System.Globalization; using System.IO; using JsonFx.Model; using JsonFx.Serialization; using JsonFx.Utils; namespace JsonFx.Json { public partial class JsonWriter { #region Constants private const string ErrorUnexpectedToken = "Unexpected token ({0})"; #endregion Constants /// <summary> /// Outputs JSON text from an input stream of tokens /// </summary> public class JsonFormatter : ITextFormatter<ModelTokenType> { #region Constants #if WINDOWS_PHONE private static readonly JsonFx.CodeGen.ProxyDelegate EnumGetValues = JsonFx.CodeGen.DynamicMethodGenerator.GetMethodProxy(typeof(Enum), "GetValues"); #elif SILVERLIGHT private static readonly JsonFx.CodeGen.ProxyDelegate EnumGetValues = JsonFx.CodeGen.DynamicMethodGenerator.GetMethodProxy(typeof(Enum), "InternalGetValues"); #endif #endregion Constants #region Fields private readonly DataWriterSettings Settings; // TODO: find a way to generalize this setting private bool encodeLessThan; #endregion Fields #region Init /// <summary> /// Ctor /// </summary> /// <param name="settings"></param> public JsonFormatter(DataWriterSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } this.Settings = settings; } #endregion Init #region Properties /// <summary> /// Gets and sets if '&lt;' should be encoded in strings /// Useful for when emitting directly into page /// </summary> public bool EncodeLessThan { get { return this.encodeLessThan; } set { this.encodeLessThan = value; } } #endregion Properties #region ITextFormatter<T> Methods /// <summary> /// Formats the token sequence as a string /// </summary> /// <param name="tokens"></param> public string Format(IEnumerable<Token<ModelTokenType>> tokens) { using (StringWriter writer = new StringWriter()) { this.Format(tokens, writer); return writer.GetStringBuilder().ToString(); } } /// <summary> /// Formats the token sequence to the writer /// </summary> /// <param name="writer"></param> /// <param name="tokens"></param> public void Format(IEnumerable<Token<ModelTokenType>> tokens, TextWriter writer) { if (tokens == null) { throw new ArgumentNullException("tokens"); } bool prettyPrint = this.Settings.PrettyPrint; // allows us to keep basic context without resorting to a push-down automata bool pendingNewLine = false; bool needsValueDelim = false; int depth = 0; foreach (Token<ModelTokenType> token in tokens) { switch (token.TokenType) { case ModelTokenType.ArrayBegin: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } writer.Write(JsonGrammar.OperatorArrayBegin); pendingNewLine = true; needsValueDelim = false; continue; } case ModelTokenType.ArrayEnd: { if (pendingNewLine) { pendingNewLine = false; } else if (prettyPrint) { this.WriteLine(writer, --depth); } writer.Write(JsonGrammar.OperatorArrayEnd); needsValueDelim = true; continue; } case ModelTokenType.Primitive: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } Type valueType = (token.Value == null) ? null : token.Value.GetType(); TypeCode typeCode = Type.GetTypeCode(valueType); switch (typeCode) { case TypeCode.Boolean: { writer.Write(true.Equals(token.Value) ? JsonGrammar.KeywordTrue : JsonGrammar.KeywordFalse); break; } case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: { if (valueType.IsEnum) { goto default; } this.WriteNumber(writer, token.Value, typeCode); break; } case TypeCode.DBNull: case TypeCode.Empty: { writer.Write(JsonGrammar.KeywordNull); break; } default: { ITextFormattable<ModelTokenType> formattable = token.Value as ITextFormattable<ModelTokenType>; if (formattable != null) { formattable.Format(this, writer); break; } this.WritePrimitive(writer, token.Value); break; } } needsValueDelim = true; continue; } case ModelTokenType.ObjectBegin: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } writer.Write(JsonGrammar.OperatorObjectBegin); pendingNewLine = true; needsValueDelim = false; continue; } case ModelTokenType.ObjectEnd: { if (pendingNewLine) { pendingNewLine = false; } else if (prettyPrint) { this.WriteLine(writer, --depth); } writer.Write(JsonGrammar.OperatorObjectEnd); needsValueDelim = true; continue; } case ModelTokenType.Property: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } this.WritePropertyName(writer, token.Name.LocalName); if (prettyPrint) { writer.Write(" "); writer.Write(JsonGrammar.OperatorPairDelim); writer.Write(" "); } else { writer.Write(JsonGrammar.OperatorPairDelim); } needsValueDelim = false; continue; } case ModelTokenType.None: default: { throw new TokenException<ModelTokenType>( token, String.Format(ErrorUnexpectedToken, token.TokenType)); } } } } #endregion ITextFormatter<T> Methods #region Write Methods protected virtual void WritePrimitive(TextWriter writer, object value) { if (value is TimeSpan) { this.WriteNumber(writer, ((TimeSpan)value).Ticks, TypeCode.Int64); return; } this.WriteString(writer, this.FormatString(value)); } protected virtual void WritePropertyName(TextWriter writer, string propertyName) { this.WriteString(writer, this.FormatString(propertyName)); } protected virtual void WriteNumber(TextWriter writer, object value, TypeCode typeCode) { bool overflowsIEEE754 = false; string number; switch (typeCode) { case TypeCode.Byte: { number = ((byte)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Boolean: { number = true.Equals(value) ? "1" : "0"; break; } case TypeCode.Decimal: { overflowsIEEE754 = true; number = ((decimal)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Double: { double doubleValue = (double)value; if (Double.IsNaN(doubleValue)) { this.WriteNaN(writer); return; } if (Double.IsInfinity(doubleValue)) { if (Double.IsNegativeInfinity(doubleValue)) { this.WriteNegativeInfinity(writer); } else { this.WritePositiveInfinity(writer); } return; } // round-trip format has a few more digits than general // http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#RFormatString number = doubleValue.ToString("r", CultureInfo.InvariantCulture); break; } case TypeCode.Int16: { number = ((short)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Int32: { number = ((int)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Int64: { overflowsIEEE754 = true; number = ((long)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.SByte: { number = ((sbyte)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Single: { float floatValue = (float)value; if (Single.IsNaN(floatValue)) { this.WriteNaN(writer); return; } if (Single.IsInfinity(floatValue)) { if (Single.IsNegativeInfinity(floatValue)) { this.WriteNegativeInfinity(writer); } else { this.WritePositiveInfinity(writer); } return; } // round-trip format has a few more digits than general // http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#RFormatString number = floatValue.ToString("r", CultureInfo.InvariantCulture); break; } case TypeCode.UInt16: { number = ((ushort)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.UInt32: { overflowsIEEE754 = true; number = ((uint)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.UInt64: { overflowsIEEE754 = true; number = ((ulong)value).ToString("g", CultureInfo.InvariantCulture); break; } default: { throw new TokenException<ModelTokenType>(ModelGrammar.TokenPrimitive(value), "Invalid number token"); } } if (overflowsIEEE754 && this.InvalidIEEE754(Convert.ToDecimal(value))) { // checks for IEEE-754 overflow and emit as strings this.WriteString(writer, number); } else { // fits within an IEEE-754 floating point so emit directly writer.Write(number); } } protected virtual void WriteNegativeInfinity(TextWriter writer) { writer.Write(JsonGrammar.KeywordNull); } protected virtual void WritePositiveInfinity(TextWriter writer) { writer.Write(JsonGrammar.KeywordNull); } protected virtual void WriteNaN(TextWriter writer) { writer.Write(JsonGrammar.KeywordNull); } protected virtual void WriteString(TextWriter writer, string value) { int start = 0, length = value.Length; writer.Write(JsonGrammar.OperatorStringDelim); for (int i=start; i<length; i++) { char ch = value[i]; if (ch <= '\u001F' || ch >= '\u007F' || (this.encodeLessThan && ch == '<') || // improves compatibility within script blocks ch == JsonGrammar.OperatorStringDelim || ch == JsonGrammar.OperatorCharEscape) { if (i > start) { writer.Write(value.Substring(start, i-start)); } start = i+1; switch (ch) { case JsonGrammar.OperatorStringDelim: case JsonGrammar.OperatorCharEscape: { writer.Write(JsonGrammar.OperatorCharEscape); writer.Write(ch); continue; } case '\b': { writer.Write("\\b"); continue; } case '\f': { writer.Write("\\f"); continue; } case '\n': { writer.Write("\\n"); continue; } case '\r': { writer.Write("\\r"); continue; } case '\t': { writer.Write("\\t"); continue; } default: { writer.Write("\\u"); writer.Write(CharUtility.ConvertToUtf32(value, i).ToString("X4")); continue; } } } } if (length > start) { writer.Write(value.Substring(start, length-start)); } writer.Write(JsonGrammar.OperatorStringDelim); } private void WriteLine(TextWriter writer, int depth) { // emit CRLF writer.Write(this.Settings.NewLine); for (int i=0; i<depth; i++) { // indent next line accordingly writer.Write(this.Settings.Tab); } } #endregion Write Methods #region String Methods /// <summary> /// Converts an object to its string representation /// </summary> /// <param name="value"></param> /// <returns></returns> protected virtual string FormatString(object value) { if (value is Enum) { return this.FormatEnum((Enum)value); } return Token<ModelTokenType>.ToString(value); } #endregion String Methods #region Enum Methods /// <summary> /// Converts an enum to its string representation /// </summary> /// <param name="value"></param> /// <returns></returns> private string FormatEnum(Enum value) { Type type = value.GetType(); IDictionary<Enum, string> map = this.Settings.Resolver.LoadEnumMaps(type); string enumName; if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value)) { Enum[] flags = JsonFormatter.GetFlagList(type, value); string[] flagNames = new string[flags.Length]; for (int i=0; i<flags.Length; i++) { if (!map.TryGetValue(flags[i], out flagNames[i]) || String.IsNullOrEmpty(flagNames[i])) { flagNames[i] = flags[i].ToString("f"); } } enumName = String.Join(", ", flagNames); } else { if (!map.TryGetValue(value, out enumName) || String.IsNullOrEmpty(enumName)) { enumName = value.ToString("f"); } } return enumName; } /// <summary> /// Splits a bitwise-OR'd set of enums into a list. /// </summary> /// <param name="enumType">the enum type</param> /// <param name="value">the combined value</param> /// <returns>list of flag enums</returns> /// <remarks> /// from PseudoCode.EnumHelper /// </remarks> private static Enum[] GetFlagList(Type enumType, object value) { ulong longVal = Convert.ToUInt64(value); #if SILVERLIGHT ulong[] enumValues = (ulong[])JsonFormatter.EnumGetValues(enumType); #else Array enumValues = Enum.GetValues(enumType); #endif List<Enum> enums = new List<Enum>(enumValues.Length); // check for empty if (longVal == 0L) { // Return the value of empty, or zero if none exists enums.Add((Enum)Convert.ChangeType(value, enumType, CultureInfo.InvariantCulture)); return enums.ToArray(); } for (int i = enumValues.Length-1; i >= 0; i--) { ulong enumValue = Convert.ToUInt64(enumValues.GetValue(i)); if ((i == 0) && (enumValue == 0L)) { continue; } // matches a value in enumeration if ((longVal & enumValue) == enumValue) { // remove from val longVal -= enumValue; // add enum to list enums.Add(enumValues.GetValue(i) as Enum); } } if (longVal != 0x0L) { enums.Add(Enum.ToObject(enumType, longVal) as Enum); } return enums.ToArray(); } #endregion Enum Methods #region Number Methods /// <summary> /// Determines if a numeric value cannot be represented as IEEE-754. /// </summary> /// <param name="value"></param> /// <returns></returns> /// <remarks> /// http://stackoverflow.com/questions/1601646 /// </remarks> protected virtual bool InvalidIEEE754(decimal value) { try { return (decimal)(Decimal.ToDouble(value)) != value; } catch { return true; } } #endregion Number Methods } } }
//******************************************************* // // Delphi DataSnap Framework // // Copyright(c) 1995-2011 Embarcadero Technologies, Inc. // //******************************************************* using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Newtonsoft.Json.Linq; namespace Embarcadero.Datasnap.WindowsPhone7 { public interface IDSCallbackChannelManagerEventListener { void OnException(Exception ex); } /** * Handle callback communications. */ public class DSCallbackChannelManager { private String ChannelName; private String ManagerID; private String SecurityToken; private WorkerThread wThread; private Thread thread; private Object locker; private DSRESTConnection Connection; private DSAdmin dsadmin; private DSAdmin.ExceptionCallback ExCallback; private int MaxRetries = 5; private int RetryDelay = 1000; public void setMaxRetries(int maxRetries) { MaxRetries = maxRetries; } public int getMaxRetries() { return MaxRetries; } public void setRetryDelay(int retryDelay) { RetryDelay = retryDelay; } public int getRetryDelay() { return RetryDelay; } /** * @param Connection DSRESTConnection * @param ChannelName String * @param ManagerID String */ public DSCallbackChannelManager(DSRESTConnection Connection, String ChannelName, String ManagerID, DSAdmin.ExceptionCallback ExceptionCallback) : base() { locker = new Object(); this.ExCallback = ExceptionCallback; this.ChannelName = ChannelName; this.ManagerID = ManagerID; this.Connection = Connection; this.dsadmin = new DSAdmin(this.Connection, ExCallback); Random random = new Random(); this.SecurityToken = Convert.ToString(random.Next(100000)) + "." + Convert.ToString(random.Next(100000)); } public DSCallbackChannelManager(DSRESTConnection Connection, String ChannelName) : base() { locker = new Object(); this.ChannelName = ChannelName; this.ManagerID = getNewManagerID(); this.Connection = Connection; this.dsadmin = new DSAdmin(this.Connection, ExCallback); Random random = new Random(); this.SecurityToken = Convert.ToString(random.Next(100000)) + "." + Convert.ToString(random.Next(100000)); } public void NotifyCallback(String ClientId, String CallbackId, TJSONValue Msg, DSAdmin.NotifyCallbackCallback callback = null, DSAdmin.ExceptionCallback ExCal = null) { dsadmin.NotifyCallback(ClientId, CallbackId, Msg, callback, ExCal); } public void BroadcastToChannel(String ChannelName, TJSONValue Msg, DSAdmin.BroadcastToChannelCallback callback = null, DSAdmin.ExceptionCallback ExCal = null) { dsadmin.BroadcastToChannel(ChannelName, Msg, callback, ExCal); } private IDSCallbackChannelManagerEventListener EventListener = null; public void SetEventListener(IDSCallbackChannelManagerEventListener EventListener) { } protected void lockIt() { Monitor.Enter(this); } protected void unlockIt() { Monitor.Exit(this); } /** * Registering another callback with the client channel * * @param CallbackId * @throws Exception */ private void registerClientCallback(String CallbackId, DSAdmin.RegisterClientCallbackServerCallback RegisterClientCallbackServerCallback = null) { dsadmin.RegisterClientCallbackServer(getManagerID(), CallbackId, ChannelName, getSecurityToken(), RegisterClientCallbackServerCallback, (Exception ex) => { if (EventListener != null) EventListener.OnException(ex); }); } public delegate void OnRegisterCallbackFinish(); /** * method used by the client for Registering or Adding a callback with the client channel * * @param CallbackId String * @param Callback the class that implements the method "execute" * @param OnRegisterCallbackFinish */ public void registerCallback(String CallbackId, DBXCallback Callback, OnRegisterCallbackFinish onRegisterCallbackFinish = null) { TJSONValue Value = new TJSONTrue(); if (wThread == null) { wThread = new WorkerThread(Connection.Clone(true), this); thread = new Thread(new ThreadStart(wThread.run)); dsadmin.ConsumeClientChannel(ChannelName, getManagerID(), CallbackId, ChannelName, getSecurityToken(), Value, (TJSONValue res) => { if (res is TJSONObject && ((TJSONObject)res).has("invoke")) { thread.Start(); } if (onRegisterCallbackFinish != null) onRegisterCallbackFinish(); }); } else { registerClientCallback(CallbackId); if (onRegisterCallbackFinish != null) onRegisterCallbackFinish(); } wThread.addCallback(CallbackId, Callback); } /** * Stopping the Heavyweight Callback * * @return bool * @throws Exception */ public bool closeClientChannel() { lockIt(); try { dsadmin.CloseClientChannel(getManagerID(), getSecurityToken()); wThread.terminate(); try { if (!thread.Join(500)) thread.Abort(); } catch (Exception) { } thread = null; return true; } finally { unlockIt(); } } /** * invokes closeClientChannel() */ public void stop() { closeClientChannel(); } /** * Removing a callback from a Client Channel * * @param CallbackId * @throws Exception */ public void unregisterCallback(String CallbackId, DSAdmin.UnregisterClientCallbackCallback Callback = null) { lockIt(); try { dsadmin.UnregisterClientCallback(ChannelName, CallbackId, getSecurityToken(), Callback, (Exception ex) => { if (EventListener != null) EventListener.OnException(ex); }); } finally { unlockIt(); } } /** * Returns the name of the channel to connect to. * @return String channelname */ public String getChannelName() { return ChannelName; } /** * Returns Unique connection id. * @return String channelID */ public String getManagerID() { return ManagerID; } /** * Returns Unique Security Token. * @return String SecurityToken */ public String getSecurityToken() { return SecurityToken; } ////////////////////////////////////////////////////////// //// CALLBACKs WORKER THREAD ////////////////////////////////////////////////////////// protected class WorkerThread { protected bool stopped; private Object locker = new Object(); private DSAdmin dsadmin; private DSCallbackChannelManager mngr; private Dictionary<String, DBXCallback> callbacks; public WorkerThread(DSRESTConnection connection, DSCallbackChannelManager mngr) : base() { this.dsadmin = new DSAdmin(connection, mngr.ExCallback); this.mngr = mngr; callbacks = new Dictionary<string, DBXCallback>(); } public void removeCallback(String callbackId) { cbListLock(); try { callbacks.Remove(callbackId); } finally { cbListUnLock(); } } public void addCallback(String callbackId, DBXCallback callback) { cbListLock(); try { callbacks.Add(callbackId, callback); } finally { cbListUnLock(); } } public void terminate() { stopped = true; } public delegate void Exec(JObject jobj); public void run() { stopped = false; try { TJSONValue res; while (!stopped) { res = channelCallbackExecute(); if (res != null) executeCallback((JObject)res.getInternalObject()); res = null; } } catch (Exception) { stopped = true; } } /** * Getting a response from the Server There are two ways in which we respond to the server, broadcast (all client registered into the channel) or invoke (only a specific CallbackId) * @param arg the server response */ private void executeCallback(JObject arg) { cbListLock(); JToken o; try { if (arg.TryGetValue("broadcast", out o)) { broadcastEvent(arg); } else if (arg.TryGetValue("invoke", out o)) { invokeEvent(arg); } else if (arg.TryGetValue("close", out o)) { stopped = arg.Value<bool>("close"); } else throw new DBXException("Invalid callback result type"); } finally { cbListUnLock(); } } /** * send the the contents of the server response at the "execute" method of our DBXCallback class * @param json the contents of the server response */ private void invokeEvent(JObject json) { TJSONArray arr = new TJSONArray(json.Value<JArray>("invoke")); String callbackID = arr.getAsJsonString(0).getValue(); arr.remove(0); DBXCallback cb = callbacks[callbackID]; if (cb != null) cb.Execute(arr.get(0), Convert.ToInt32(arr.getInt(1).Value)); else throw new DBXException("Invalid callback response"); } private void broadcastEvent(JObject json) { List<string> keys = new List<string>(callbacks.Keys); TJSONArray arr = new TJSONArray(json.Value<JArray>("broadcast")); foreach (String callbackskeys in keys) { DBXCallback cb = callbacks[callbackskeys]; if (cb != null) cb.Execute(arr.get(0), Convert.ToInt32(arr.getInt(1).Value)); else throw new DBXException("Invalid callback response"); } } /** * @return JObject */ private TJSONValue channelCallbackExecute() { Object o = new Object(); TJSONValue Value = new TJSONTrue(); TJSONValue res = null; long lastRequestAttempt = 0; int retries = 0; while (!stopped) { lastRequestAttempt = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; res = null; Exception raisedException = null; Monitor.Enter(o); try { dsadmin.ConsumeClientChannel(mngr.getChannelName(), mngr .getManagerID(), "", mngr.getChannelName(), mngr .getSecurityToken(), Value, (r) => { Monitor.Enter(o); try { res = r; Monitor.PulseAll(o); } finally { Monitor.Exit(o); } }, (e) => { Monitor.Enter(o); try { raisedException = e; Monitor.PulseAll(o); } finally { Monitor.Exit(o); } } ); Monitor.Wait(o); //analize the callback's results if (raisedException != null) { if ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - lastRequestAttempt >= dsadmin.getConnection().getConnectionTimeout() + 1000) retries = 0; if (retries == this.mngr.getMaxRetries()) { terminate(); res = null; mngr.Connection.syncContext.Send(new SendOrPostCallback(x => mngr.ExCallback.DynamicInvoke(raisedException)), null); } retries++; Thread.Sleep(this.mngr.getRetryDelay()); } else break; } finally { Monitor.Exit(o); } } //while return res; } private void cbListLock() { Monitor.Enter(this); } private void cbListUnLock() { Monitor.Exit(this); } } /** * * @return a New String represents a ManagerID */ public static String getNewManagerID() { Random random = new Random(); return Convert.ToString(random.Next(100000)) + "." + Convert.ToString(random.Next(100000)); } } }
#region License /* Copyright (c) 2005 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; namespace Sanford.Multimedia.Midi { /// <summary> /// Provides basic functionality for generating tick events with pulses per /// quarter note resolution. /// </summary> public abstract class PpqnClock : IClock { #region PpqnClock Members #region Fields /// <summary> /// The default tempo in microseconds: 120bpm. /// </summary> public const int DefaultTempo = 500000; /// <summary> /// The minimum pulses per quarter note value. /// </summary> public const int PpqnMinValue = 24; // The number of microseconds per millisecond. private const int MicrosecondsPerMillisecond = 1000; // The pulses per quarter note value. private int ppqn = PpqnMinValue; // The tempo in microseconds. private int tempo = DefaultTempo; // The product of the timer period, the pulses per quarter note, and // the number of microseconds per millisecond. private int periodResolution; // The number of ticks per MIDI clock. private int ticksPerClock; // The running fractional tick count. private int fractionalTicks = 0; // The timer period. private readonly int timerPeriod; // Indicates whether the clock is running. protected bool running = false; #endregion #region Construction protected PpqnClock(int timerPeriod) { #region Require if(timerPeriod < 1) { throw new ArgumentOutOfRangeException("timerPeriod", timerPeriod, "Timer period cannot be less than one."); } #endregion this.timerPeriod = timerPeriod; CalculatePeriodResolution(); CalculateTicksPerClock(); } #endregion #region Methods protected int GetTempo() { return tempo; } protected void SetTempo(int tempo) { #region Require if(tempo < 1) { throw new ArgumentOutOfRangeException( "Tempo out of range."); } #endregion this.tempo = tempo; } protected void Reset() { fractionalTicks = 0; } protected int GenerateTicks() { int ticks = (fractionalTicks + periodResolution) / tempo; fractionalTicks += periodResolution - ticks * tempo; return ticks; } private void CalculatePeriodResolution() { periodResolution = ppqn * timerPeriod * MicrosecondsPerMillisecond; } private void CalculateTicksPerClock() { ticksPerClock = ppqn / PpqnMinValue; } protected virtual void OnTick(EventArgs e) { EventHandler handler = Tick; if(handler != null) { handler(this, EventArgs.Empty); } } protected virtual void OnStarted(EventArgs e) { EventHandler handler = Started; if(handler != null) { handler(this, e); } } protected virtual void OnStopped(EventArgs e) { EventHandler handler = Stopped; if(handler != null) { handler(this, e); } } protected virtual void OnContinued(EventArgs e) { EventHandler handler = Continued; if(handler != null) { handler(this, e); } } #endregion #region Properties public int Ppqn { get { return ppqn; } set { #region Require if(value < PpqnMinValue) { throw new ArgumentOutOfRangeException("Ppqn", value, "Pulses per quarter note out of range."); } else if(value % PpqnMinValue != 0) { throw new ArgumentException( "Pulses per quarter note is not a multiple of 24."); } #endregion ppqn = value; CalculatePeriodResolution(); CalculateTicksPerClock(); } } public abstract int Ticks { get; } public int TicksPerClock { get { return ticksPerClock; } } #endregion #endregion #region IClock Members public event System.EventHandler Tick; public event System.EventHandler Started; public event System.EventHandler Continued; public event System.EventHandler Stopped; public bool IsRunning { get { return running; } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace CupCakeHeaven.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BasicOperations operations. /// </summary> internal partial class BasicOperations : IServiceOperations<AzureCompositeModel>, IBasicOperations { /// <summary> /// Initializes a new instance of the BasicOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BasicOperations(AzureCompositeModel client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex type {id: 2, name: 'abc', color: 'YELLOW'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } string apiVersion = "2016-02-29"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is invalid for the local strong type /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type whose properties are null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type while the server doesn't provide a response /// payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Sql { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// The Azure SQL Database management API provides a RESTful set of web /// services that interact with Azure SQL Database services to manage your /// databases. The API enables you to create, retrieve, update, and delete /// databases. /// </summary> public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription ID that identifies an Azure subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IServersOperations. /// </summary> public virtual IServersOperations Servers { get; private set; } /// <summary> /// Gets the IDatabasesOperations. /// </summary> public virtual IDatabasesOperations Databases { get; private set; } /// <summary> /// Gets the IImportExportOperations. /// </summary> public virtual IImportExportOperations ImportExportOperations { get; private set; } /// <summary> /// Gets the IElasticPoolsOperations. /// </summary> public virtual IElasticPoolsOperations ElasticPools { get; private set; } /// <summary> /// Gets the IRecommendedElasticPoolsOperations. /// </summary> public virtual IRecommendedElasticPoolsOperations RecommendedElasticPools { get; private set; } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SqlManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SqlManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SqlManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SqlManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SqlManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SqlManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SqlManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SqlManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Servers = new ServersOperations(this); Databases = new DatabasesOperations(this); ImportExportOperations = new ImportExportOperations(this); ElasticPools = new ElasticPoolsOperations(this); RecommendedElasticPools = new RecommendedElasticPoolsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Lists all of the available SQL Rest API operations. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationListResult>> ListOperationsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2014-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListOperations", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Sql/operations").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<OperationListResult>(_responseContent, DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; namespace System.Reflection.Metadata.Ecma335 { public static class MetadataTokens { /// <summary> /// Maximum number of tables that can be present in Ecma335 metadata. /// </summary> public static readonly int TableCount = TableIndexExtensions.Count; /// <summary> /// Maximum number of tables that can be present in Ecma335 metadata. /// </summary> public static readonly int HeapCount = HeapIndexExtensions.Count; /// <summary> /// Returns the row number of a metadata table entry that corresponds /// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>One based row number.</returns> /// <exception cref="ArgumentException">The <paramref name="handle"/> is not a valid metadata table handle.</exception> public static int GetRowNumber(this MetadataReader reader, Handle handle) { if (handle.IsHeapHandle) { ThrowTableHandleRequired(); } if (handle.IsVirtual) { return MapVirtualHandleRowId(reader, handle); } return (int)handle.RowId; } /// <summary> /// Returns the offset of metadata heap data that corresponds /// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>Zero based offset, or -1 if <paramref name="handle"/> isn't a metadata heap handle.</returns> /// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="handle"/> is invalid.</exception> public static int GetHeapOffset(this MetadataReader reader, Handle handle) { if (!handle.IsHeapHandle) { ThrowHeapHandleRequired(); } if (handle.IsVirtual) { return MapVirtualHandleRowId(reader, handle); } return (int)handle.RowId; } /// <summary> /// Returns the metadata token of the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>Metadata token.</returns> /// <exception cref="ArgumentException"> /// Handle represents a metadata entity that doesn't have a token. /// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>. /// </exception> public static int GetToken(this MetadataReader reader, Handle handle) { if (!TokenTypeIds.IsEcmaToken(handle.value)) { ThrowTableHandleOrUserStringRequired(); } if (handle.IsVirtual) { return MapVirtualHandleRowId(reader, handle) | (int)(handle.value & TokenTypeIds.TokenTypeMask); } return (int)handle.value; } private static int MapVirtualHandleRowId(MetadataReader reader, Handle handle) { switch (handle.Kind) { case HandleKind.AssemblyReference: // pretend that virtual rows immediately follow real rows: return (int)(reader.AssemblyRefTable.NumberOfNonVirtualRows + 1 + handle.RowId); case HandleKind.String: case HandleKind.Blob: // We could precalculate offsets for virtual strings and blobs as we are creating them // if we wanted to implement this. throw new NotSupportedException(MetadataResources.CantGetOffsetForVirtualHeapHandle); default: throw new ArgumentException(MetadataResources.InvalidHandle, "handle"); } } /// <summary> /// Returns the row number of a metadata table entry that corresponds /// to the specified <paramref name="handle"/>. /// </summary> /// <returns> /// One based row number, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetRowNumber(MetadataReader, Handle)"/>. /// </returns> public static int GetRowNumber(Handle handle) { if (handle.IsHeapHandle) { ThrowTableHandleRequired(); } if (handle.IsVirtual) { return -1; } return (int)handle.RowId; } /// <summary> /// Returns the offset of metadata heap data that corresponds /// to the specified <paramref name="handle"/>. /// </summary> /// <returns> /// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>. /// </returns> public static int GetHeapOffset(Handle handle) { if (!handle.IsHeapHandle) { ThrowHeapHandleRequired(); } if (handle.IsVirtual) { return -1; } return (int)handle.RowId; } /// <summary> /// Returns the metadata token of the specified <paramref name="handle"/>. /// </summary> /// <returns> /// Metadata token, or 0 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetToken(MetadataReader, Handle)"/>. /// </returns> /// <exception cref="ArgumentException"> /// Handle represents a metadata entity that doesn't have a token. /// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>. /// </exception> public static int GetToken(Handle handle) { if (!TokenTypeIds.IsEcmaToken(handle.value)) { ThrowTableHandleOrUserStringRequired(); } if (handle.IsVirtual) { return 0; } return (int)handle.value; } /// <summary> /// Gets the <see cref="TableIndex"/> of the table corresponding to the specified <see cref="HandleKind"/>. /// </summary> /// <param name="type">Handle type.</param> /// <param name="index">Table index.</param> /// <returns>True if the handle type corresponds to an Ecma335 table, false otherwise.</returns> public static bool TryGetTableIndex(HandleKind type, out TableIndex index) { if ((int)type < TableIndexExtensions.Count) { index = (TableIndex)type; return true; } index = 0; return false; } /// <summary> /// Gets the <see cref="HeapIndex"/> of the heap corresponding to the specified <see cref="HandleKind"/>. /// </summary> /// <param name="type">Handle type.</param> /// <param name="index">Heap index.</param> /// <returns>True if the handle type corresponds to an Ecma335 heap, false otherwise.</returns> public static bool TryGetHeapIndex(HandleKind type, out HeapIndex index) { switch (type) { case HandleKind.UserString: index = HeapIndex.UserString; return true; case HandleKind.String: case HandleKind.NamespaceDefinition: index = HeapIndex.String; return true; case HandleKind.Blob: index = HeapIndex.Blob; return true; case HandleKind.Guid: index = HeapIndex.Guid; return true; default: index = 0; return false; } } #region Handle Factories /// <summary> /// Creates a handle from a token value. /// </summary> /// <exception cref="ArgumentException"> /// <paramref name="token"/> is not a valid metadata token. /// It must encode a metadata table entity or an offset in <see cref="HandleKind.UserString"/> heap. /// </exception> public static Handle Handle(int token) { if (!TokenTypeIds.IsEcmaToken(unchecked((uint)token))) { ThrowInvalidToken(); } return new Handle((uint)token); } /// <summary> /// Creates a handle from a token value. /// </summary> /// <exception cref="ArgumentException"> /// <paramref name="tableIndex"/> is not a valid table index.</exception> public static Handle Handle(TableIndex tableIndex, int rowNumber) { int token = ((int)tableIndex << TokenTypeIds.RowIdBitCount) | rowNumber; if (!TokenTypeIds.IsEcmaToken(unchecked((uint)token))) { ThrowInvalidTableIndex(); } return new Handle((uint)token); } public static MethodDefinitionHandle MethodDefinitionHandle(int rowNumber) { return Metadata.MethodDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static MethodImplementationHandle MethodImplementationHandle(int rowNumber) { return Metadata.MethodImplementationHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static MethodSpecificationHandle MethodSpecificationHandle(int rowNumber) { return Metadata.MethodSpecificationHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static TypeDefinitionHandle TypeDefinitionHandle(int rowNumber) { return Metadata.TypeDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static ExportedTypeHandle ExportedTypeHandle(int rowNumber) { return Metadata.ExportedTypeHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static TypeReferenceHandle TypeReferenceHandle(int rowNumber) { return Metadata.TypeReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static TypeSpecificationHandle TypeSpecificationHandle(int rowNumber) { return Metadata.TypeSpecificationHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static MemberReferenceHandle MemberReferenceHandle(int rowNumber) { return Metadata.MemberReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static FieldDefinitionHandle FieldDefinitionHandle(int rowNumber) { return Metadata.FieldDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static EventDefinitionHandle EventDefinitionHandle(int rowNumber) { return Metadata.EventDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static PropertyDefinitionHandle PropertyDefinitionHandle(int rowNumber) { return Metadata.PropertyDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static StandaloneSignatureHandle StandaloneSignatureHandle(int rowNumber) { return Metadata.StandaloneSignatureHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static ParameterHandle ParameterHandle(int rowNumber) { return Metadata.ParameterHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static GenericParameterHandle GenericParameterHandle(int rowNumber) { return Metadata.GenericParameterHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static GenericParameterConstraintHandle GenericParameterConstraintHandle(int rowNumber) { return Metadata.GenericParameterConstraintHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static ModuleReferenceHandle ModuleReferenceHandle(int rowNumber) { return Metadata.ModuleReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static AssemblyReferenceHandle AssemblyReferenceHandle(int rowNumber) { return Metadata.AssemblyReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static CustomAttributeHandle CustomAttributeHandle(int rowNumber) { return Metadata.CustomAttributeHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static DeclarativeSecurityAttributeHandle DeclarativeSecurityAttributeHandle(int rowNumber) { return Metadata.DeclarativeSecurityAttributeHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static ConstantHandle ConstantHandle(int rowNumber) { return Metadata.ConstantHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static ManifestResourceHandle ManifestResourceHandle(int rowNumber) { return Metadata.ManifestResourceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static AssemblyFileHandle AssemblyFileHandle(int rowNumber) { return Metadata.AssemblyFileHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask)); } public static UserStringHandle UserStringHandle(int offset) { return Metadata.UserStringHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask)); } public static StringHandle StringHandle(int offset) { return Metadata.StringHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask)); } public static BlobHandle BlobHandle(int offset) { return Metadata.BlobHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask)); } public static GuidHandle GuidHandle(int offset) { return Metadata.GuidHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask)); } #endregion [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowTableHandleRequired() { throw new ArgumentException(MetadataResources.NotMetadataTableHandle, "handle"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowHeapHandleRequired() { throw new ArgumentException(MetadataResources.NotMetadataHeapHandle, "handle"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowTableHandleOrUserStringRequired() { throw new ArgumentException(MetadataResources.NotMetadataTableOrUserStringHandle, "handle"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidToken() { throw new ArgumentException(MetadataResources.InvalidToken, "token"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidTableIndex() { throw new ArgumentOutOfRangeException("tableIndex"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.Permissions; using Enumerable = System.Linq.Enumerable; namespace System.ComponentModel.Design { /// <summary> /// Provides access to get and set option values for a designer. /// </summary> public abstract class DesignerOptionService : IDesignerOptionService { private DesignerOptionCollection _options; private static readonly char[] s_slash = {'\\'}; /// <summary> /// Returns the options collection for this service. There is /// always a global options collection that contains child collections. /// </summary> public DesignerOptionCollection Options { get { return _options ?? (_options = new DesignerOptionCollection(this, null, string.Empty, null)); } } /// <summary> /// Creates a new DesignerOptionCollection with the given name, and adds it to /// the given parent. The "value" parameter specifies an object whose public /// properties will be used in the Properties collection of the option collection. /// The value parameter can be null if this options collection does not offer /// any properties. Properties will be wrapped in such a way that passing /// anything into the component parameter of the property descriptor will be /// ignored and the value object will be substituted. /// </summary> protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent, string name, object value) { if (parent == null) { throw new ArgumentNullException(nameof(parent)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidArgument, name.Length.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)), "name.Length"); } return new DesignerOptionCollection(this, parent, name, value); } /// <summary> /// Retrieves the property descriptor for the given page / value name. Returns /// null if the property couldn't be found. /// </summary> private PropertyDescriptor GetOptionProperty(string pageName, string valueName) { if (pageName == null) { throw new ArgumentNullException(nameof(pageName)); } if (valueName == null) { throw new ArgumentNullException(nameof(valueName)); } string[] optionNames = pageName.Split(s_slash); DesignerOptionCollection options = Options; foreach (string optionName in optionNames) { options = options[optionName]; if (options == null) { return null; } } return options.Properties[valueName]; } /// <summary> /// This method is called on demand the first time a user asks for child /// options or properties of an options collection. /// </summary> protected virtual void PopulateOptionCollection(DesignerOptionCollection options) { } /// <summary> /// This method must be implemented to show the options dialog UI for the given object. /// </summary> protected virtual bool ShowDialog(DesignerOptionCollection options, object optionObject) { return false; } /// <internalonly/> /// <summary> /// Gets the value of an option defined in this package. /// </summary> object IDesignerOptionService.GetOptionValue(string pageName, string valueName) { PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName); return optionProp?.GetValue(null); } /// <internalonly/> /// <summary> /// Sets the value of an option defined in this package. /// </summary> void IDesignerOptionService.SetOptionValue(string pageName, string valueName, object value) { PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName); optionProp?.SetValue(null, value); } /// <summary> /// The DesignerOptionCollection class is a collection that contains /// other DesignerOptionCollection objects. This forms a tree of options, /// with each branch of the tree having a name and a possible collection of /// properties. Each parent branch of the tree contains a union of the /// properties if all the branch's children. /// </summary> [TypeConverter(typeof(DesignerOptionConverter))] public sealed class DesignerOptionCollection : IList { private DesignerOptionService _service; private object _value; private ArrayList _children; private PropertyDescriptorCollection _properties; /// <summary> /// Creates a new DesignerOptionCollection. /// </summary> internal DesignerOptionCollection(DesignerOptionService service, DesignerOptionCollection parent, string name, object value) { _service = service; Parent = parent; Name = name; _value = value; if (Parent != null) { if (Parent._children == null) { Parent._children = new ArrayList(1); } Parent._children.Add(this); } } /// <summary> /// The count of child options collections this collection contains. /// </summary> public int Count { get { EnsurePopulated(); return _children.Count; } } /// <summary> /// The name of this collection. Names are programmatic names and are not /// localized. A name search is case insensitive. /// </summary> public string Name { get; } /// <summary> /// Returns the parent collection object, or null if there is no parent. /// </summary> public DesignerOptionCollection Parent { get; } /// <summary> /// The collection of properties that this OptionCollection, along with all of /// its children, offers. PropertyDescriptors are taken directly from the /// value passed to CreateObjectCollection and wrapped in an additional property /// descriptor that hides the value object from the user. This means that any /// value may be passed into the "component" parameter of the various /// PropertyDescriptor methods. The value is ignored and is replaced with /// the correct value internally. /// </summary> public PropertyDescriptorCollection Properties { get { if (_properties == null) { ArrayList propList; if (_value != null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_value); propList = new ArrayList(props.Count); foreach (PropertyDescriptor prop in props) { propList.Add(new WrappedPropertyDescriptor(prop, _value)); } } else { propList = new ArrayList(1); } EnsurePopulated(); foreach (DesignerOptionCollection child in _children) { propList.AddRange(child.Properties); } PropertyDescriptor[] propArray = (PropertyDescriptor[])propList.ToArray(typeof(PropertyDescriptor)); _properties = new PropertyDescriptorCollection(propArray, true); } return _properties; } } /// <summary> /// Retrieves the child collection at the given index. /// </summary> public DesignerOptionCollection this[int index] { [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] get { EnsurePopulated(); if (index < 0 || index >= _children.Count) { throw new IndexOutOfRangeException(nameof(index)); } return (DesignerOptionCollection)_children[index]; } } /// <summary> /// Retrieves the child collection at the given name. The name search is case /// insensitive. /// </summary> public DesignerOptionCollection this[string name] { get { EnsurePopulated(); foreach (DesignerOptionCollection child in _children) { if (string.Compare(child.Name, name, true, CultureInfo.InvariantCulture) == 0) { return child; } } return null; } } /// <summary> /// Copies this collection to an array. /// </summary> public void CopyTo(Array array, int index) { EnsurePopulated(); _children.CopyTo(array, index); } /// <summary> /// Called before any access to our collection to force it to become populated. /// </summary> private void EnsurePopulated() { if (_children == null) { _service.PopulateOptionCollection(this); if (_children == null) { _children = new ArrayList(1); } } } /// <summary> /// Returns an enumerator that can be used to iterate this collection. /// </summary> public IEnumerator GetEnumerator() { EnsurePopulated(); return _children.GetEnumerator(); } /// <summary> /// Returns the numerical index of the given value. /// </summary> public int IndexOf(DesignerOptionCollection value) { EnsurePopulated(); return _children.IndexOf(value); } /// <summary> /// Locates the value object to use for getting or setting a property. /// </summary> private static object RecurseFindValue(DesignerOptionCollection options) { if (options._value != null) { return options._value; } foreach (DesignerOptionCollection child in options) { object value = RecurseFindValue(child); if (value != null) { return value; } } return null; } /// <summary> /// Displays a dialog-based user interface that allows the user to /// configure the various options. /// </summary> public bool ShowDialog() { object value = RecurseFindValue(this); if (value == null) { return false; } return _service.ShowDialog(this, value); } /// <internalonly/> /// <summary> /// Private ICollection implementation. /// </summary> bool ICollection.IsSynchronized => false; /// <internalonly/> /// <summary> /// Private ICollection implementation. /// </summary> object ICollection.SyncRoot => this; /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> bool IList.IsFixedSize => true; /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> bool IList.IsReadOnly => true; /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> object IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> int IList.Add(object value) { throw new NotSupportedException(); } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> void IList.Clear() { throw new NotSupportedException(); } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> bool IList.Contains(object value) { EnsurePopulated(); return _children.Contains(value); } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> int IList.IndexOf(object value) { EnsurePopulated(); return _children.IndexOf(value); } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> void IList.Insert(int index, object value) { throw new NotSupportedException(); } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> void IList.Remove(object value) { throw new NotSupportedException(); } /// <internalonly/> /// <summary> /// Private IList implementation. /// </summary> void IList.RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// A special property descriptor that forwards onto a base /// property descriptor but allows any value to be used for the /// "component" parameter. /// </summary> private sealed class WrappedPropertyDescriptor : PropertyDescriptor { private object _target; private PropertyDescriptor _property; internal WrappedPropertyDescriptor(PropertyDescriptor property, object target) : base(property.Name, null) { _property = property; _target = target; } public override AttributeCollection Attributes => _property.Attributes; public override Type ComponentType => _property.ComponentType; public override bool IsReadOnly => _property.IsReadOnly; public override Type PropertyType => _property.PropertyType; public override bool CanResetValue(object component) { return _property.CanResetValue(_target); } public override object GetValue(object component) { return _property.GetValue(_target); } public override void ResetValue(object component) { _property.ResetValue(_target); } public override void SetValue(object component, object value) { _property.SetValue(_target, value); } public override bool ShouldSerializeValue(object component) { return _property.ShouldSerializeValue(_target); } } } /// <summary> /// The type converter for the designer option collection. /// </summary> internal sealed class DesignerOptionConverter : TypeConverter { public override bool GetPropertiesSupported(ITypeDescriptorContext cxt) { return true; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext cxt, object value, Attribute[] attributes) { PropertyDescriptorCollection props = new PropertyDescriptorCollection(null); DesignerOptionCollection options = value as DesignerOptionCollection; if (options == null) { return props; } foreach (DesignerOptionCollection option in options) { props.Add(new OptionPropertyDescriptor(option)); } foreach (PropertyDescriptor p in options.Properties) { props.Add(p); } return props; } public override object ConvertTo(ITypeDescriptorContext cxt, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { return SR.CollectionConverterText; } return base.ConvertTo(cxt, culture, value, destinationType); } private class OptionPropertyDescriptor : PropertyDescriptor { private DesignerOptionCollection _option; internal OptionPropertyDescriptor(DesignerOptionCollection option) : base(option.Name, null) { _option = option; } public override Type ComponentType => _option.GetType(); public override bool IsReadOnly => true; public override Type PropertyType => _option.GetType(); public override bool CanResetValue(object component) { return false; } public override object GetValue(object component) { return _option; } public override void ResetValue(object component) { } public override void SetValue(object component, object value) { } public override bool ShouldSerializeValue(object component) { return false; } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; /// <summary> /// Native utility methods. /// </summary> internal static class IgniteUtils { /** Prefix for temp directory names. */ private const string DirIgniteTmp = "Ignite_"; /** Thread-local random. */ [ThreadStatic] private static Random _rnd; /// <summary> /// Gets thread local random. /// </summary> /// <value>Thread local random.</value> public static Random ThreadLocalRandom { get { return _rnd ?? (_rnd = new Random()); } } /// <summary> /// Returns shuffled list copy. /// </summary> /// <returns>Shuffled list copy.</returns> public static IList<T> Shuffle<T>(IList<T> list) { int cnt = list.Count; if (cnt > 1) { List<T> res = new List<T>(list); Random rnd = ThreadLocalRandom; while (cnt > 1) { cnt--; int idx = rnd.Next(cnt + 1); T val = res[idx]; res[idx] = res[cnt]; res[cnt] = val; } return res; } return list; } /// <summary> /// Create new instance of specified class. /// </summary> /// <param name="typeName">Class name</param> /// <param name="props">Properties to set.</param> /// <returns>New Instance.</returns> public static T CreateInstance<T>(string typeName, IEnumerable<KeyValuePair<string, object>> props = null) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); var type = new TypeResolver().ResolveType(typeName); if (type == null) throw new IgniteException("Failed to create class instance [className=" + typeName + ']'); var res = (T) Activator.CreateInstance(type); if (props != null) SetProperties(res, props); return res; } /// <summary> /// Set properties on the object. /// </summary> /// <param name="target">Target object.</param> /// <param name="props">Properties.</param> private static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props) { if (props == null) return; IgniteArgumentCheck.NotNull(target, "target"); Type typ = target.GetType(); foreach (KeyValuePair<string, object> prop in props) { PropertyInfo prop0 = typ.GetProperty(prop.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (prop0 == null) throw new IgniteException("Property is not found [type=" + typ.Name + ", property=" + prop.Key + ']'); prop0.SetValue(target, prop.Value, null); } } /// <summary> /// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory. /// </summary> /// <returns>The full path of the temporary directory.</returns> internal static string GetTempDirectoryName() { var baseDir = Path.Combine(Path.GetTempPath(), DirIgniteTmp); while (true) { try { return Directory.CreateDirectory(baseDir + Path.GetRandomFileName()).FullName; } catch (IOException) { // Expected } catch (UnauthorizedAccessException) { // Expected } } } /// <summary> /// Convert unmanaged char array to string. /// </summary> /// <param name="chars">Char array.</param> /// <param name="charsLen">Char array length.</param> /// <returns></returns> public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen) { IntPtr ptr = new IntPtr(chars); if (ptr == IntPtr.Zero) return null; byte[] arr = new byte[charsLen]; Marshal.Copy(ptr, arr, 0, arr.Length); return Encoding.UTF8.GetString(arr); } /// <summary> /// Convert string to unmanaged byte array. /// </summary> /// <param name="str">String.</param> /// <returns>Unmanaged byte array.</returns> public static unsafe sbyte* StringToUtf8Unmanaged(string str) { var ptr = IntPtr.Zero; if (str != null) { byte[] strBytes = Encoding.UTF8.GetBytes(str); ptr = Marshal.AllocHGlobal(strBytes.Length + 1); Marshal.Copy(strBytes, 0, ptr, strBytes.Length); *((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator. } return (sbyte*)ptr.ToPointer(); } /// <summary> /// Reads node collection from stream. /// </summary> /// <param name="reader">Reader.</param> /// <param name="pred">The predicate.</param> /// <returns> Nodes list or null. </returns> public static List<IClusterNode> ReadNodes(BinaryReader reader, Func<ClusterNodeImpl, bool> pred = null) { var cnt = reader.ReadInt(); if (cnt < 0) return null; var res = new List<IClusterNode>(cnt); var ignite = reader.Marshaller.Ignite; if (pred == null) { for (var i = 0; i < cnt; i++) res.Add(ignite.GetNode(reader.ReadGuid())); } else { for (var i = 0; i < cnt; i++) { var node = ignite.GetNode(reader.ReadGuid()); if (pred(node)) res.Add(node); } } return res; } /// <summary> /// Encodes the peek modes into a single int value. /// </summary> public static int EncodePeekModes(CachePeekMode[] modes) { var res = 0; if (modes == null) { return res; } foreach (var mode in modes) { res |= (int)mode; } return res; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Net.NetworkInformation { public enum DuplicateAddressDetectionState { Deprecated = 3, Duplicate = 2, Invalid = 0, Preferred = 4, Tentative = 1, } public abstract partial class GatewayIPAddressInformation { protected GatewayIPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } } public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable { protected internal GatewayIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IcmpV4Statistics { protected IcmpV4Statistics() { } public abstract long AddressMaskRepliesReceived { get; } public abstract long AddressMaskRepliesSent { get; } public abstract long AddressMaskRequestsReceived { get; } public abstract long AddressMaskRequestsSent { get; } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long SourceQuenchesReceived { get; } public abstract long SourceQuenchesSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } public abstract long TimestampRepliesReceived { get; } public abstract long TimestampRepliesSent { get; } public abstract long TimestampRequestsReceived { get; } public abstract long TimestampRequestsSent { get; } } public abstract partial class IcmpV6Statistics { protected IcmpV6Statistics() { } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MembershipQueriesReceived { get; } public abstract long MembershipQueriesSent { get; } public abstract long MembershipReductionsReceived { get; } public abstract long MembershipReductionsSent { get; } public abstract long MembershipReportsReceived { get; } public abstract long MembershipReportsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long NeighborAdvertisementsReceived { get; } public abstract long NeighborAdvertisementsSent { get; } public abstract long NeighborSolicitsReceived { get; } public abstract long NeighborSolicitsSent { get; } public abstract long PacketTooBigMessagesReceived { get; } public abstract long PacketTooBigMessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long RouterAdvertisementsReceived { get; } public abstract long RouterAdvertisementsSent { get; } public abstract long RouterSolicitsReceived { get; } public abstract long RouterSolicitsSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } } public partial class IPAddressCollection : System.Collections.Generic.ICollection<System.Net.IPAddress>, System.Collections.Generic.IEnumerable<System.Net.IPAddress>, System.Collections.IEnumerable { protected internal IPAddressCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.IPAddress this[int index] { get { throw null; } } public virtual void Add(System.Net.IPAddress address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.IPAddress address) { throw null; } public virtual void CopyTo(System.Net.IPAddress[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.IPAddress> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.IPAddress address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IPAddressInformation { protected IPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } public abstract bool IsDnsEligible { get; } public abstract bool IsTransient { get; } } public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable { internal IPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IPGlobalProperties { protected IPGlobalProperties() { } public abstract string DhcpScopeName { get; } public abstract string DomainName { get; } public abstract string HostName { get; } public abstract bool IsWinsProxy { get; } public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; } public virtual System.IAsyncResult BeginGetUnicastAddresses(System.AsyncCallback callback, object state) { throw null; } public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection EndGetUnicastAddresses(System.IAsyncResult asyncResult) { throw null; } public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections(); public abstract System.Net.IPEndPoint[] GetActiveTcpListeners(); public abstract System.Net.IPEndPoint[] GetActiveUdpListeners(); public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics(); public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics(); public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { throw null; } public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics(); public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics(); public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection GetUnicastAddresses() { throw null; } public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { throw null; } } public abstract partial class IPGlobalStatistics { protected IPGlobalStatistics() { } public abstract int DefaultTtl { get; } public abstract bool ForwardingEnabled { get; } public abstract int NumberOfInterfaces { get; } public abstract int NumberOfIPAddresses { get; } public abstract int NumberOfRoutes { get; } public abstract long OutputPacketRequests { get; } public abstract long OutputPacketRoutingDiscards { get; } public abstract long OutputPacketsDiscarded { get; } public abstract long OutputPacketsWithNoRoute { get; } public abstract long PacketFragmentFailures { get; } public abstract long PacketReassembliesRequired { get; } public abstract long PacketReassemblyFailures { get; } public abstract long PacketReassemblyTimeout { get; } public abstract long PacketsFragmented { get; } public abstract long PacketsReassembled { get; } public abstract long ReceivedPackets { get; } public abstract long ReceivedPacketsDelivered { get; } public abstract long ReceivedPacketsDiscarded { get; } public abstract long ReceivedPacketsForwarded { get; } public abstract long ReceivedPacketsWithAddressErrors { get; } public abstract long ReceivedPacketsWithHeadersErrors { get; } public abstract long ReceivedPacketsWithUnknownProtocol { get; } } public abstract partial class IPInterfaceProperties { protected IPInterfaceProperties() { } public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; } public abstract string DnsSuffix { get; } public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; } public abstract bool IsDnsEnabled { get; } public abstract bool IsDynamicDnsEnabled { get; } public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; } public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; } public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties(); public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties(); } public abstract partial class IPInterfaceStatistics { protected IPInterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public enum IPStatus { BadDestination = 11018, BadHeader = 11042, BadOption = 11007, BadRoute = 11012, DestinationHostUnreachable = 11003, DestinationNetworkUnreachable = 11002, DestinationPortUnreachable = 11005, DestinationProhibited = 11004, DestinationProtocolUnreachable = 11004, DestinationScopeMismatch = 11045, DestinationUnreachable = 11040, HardwareError = 11008, IcmpError = 11044, NoResources = 11006, PacketTooBig = 11009, ParameterProblem = 11015, SourceQuench = 11016, Success = 0, TimedOut = 11010, TimeExceeded = 11041, TtlExpired = 11013, TtlReassemblyTimeExceeded = 11014, Unknown = -1, UnrecognizedNextHeader = 11043, } public abstract partial class IPv4InterfaceProperties { protected IPv4InterfaceProperties() { } public abstract int Index { get; } public abstract bool IsAutomaticPrivateAddressingActive { get; } public abstract bool IsAutomaticPrivateAddressingEnabled { get; } public abstract bool IsDhcpEnabled { get; } public abstract bool IsForwardingEnabled { get; } public abstract int Mtu { get; } public abstract bool UsesWins { get; } } public abstract partial class IPv4InterfaceStatistics { protected IPv4InterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv6InterfaceProperties { protected IPv6InterfaceProperties() { } public abstract int Index { get; } public abstract int Mtu { get; } public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { throw null; } } public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected MulticastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable { protected internal MulticastIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public enum NetBiosNodeType { Broadcast = 1, Hybrid = 8, Mixed = 4, Peer2Peer = 2, Unknown = 0, } public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e); public delegate void NetworkAvailabilityChangedEventHandler(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e); public partial class NetworkAvailabilityEventArgs : System.EventArgs { internal NetworkAvailabilityEventArgs() { } public bool IsAvailable { get { throw null; } } } public static partial class NetworkChange { public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } } public static event System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { } remove { } } } public partial class NetworkInformationException : System.ComponentModel.Win32Exception { public NetworkInformationException() { } public NetworkInformationException(int errorCode) { } protected NetworkInformationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public override int ErrorCode { get { throw null; } } } public abstract partial class NetworkInterface { protected NetworkInterface() { } public virtual string Description { get { throw null; } } public virtual string Id { get { throw null; } } public static int IPv6LoopbackInterfaceIndex { get { throw null; } } public virtual bool IsReceiveOnly { get { throw null; } } public static int LoopbackInterfaceIndex { get { throw null; } } public virtual string Name { get { throw null; } } public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { throw null; } } public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { throw null; } } public virtual long Speed { get { throw null; } } public virtual bool SupportsMulticast { get { throw null; } } public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { throw null; } public virtual System.Net.NetworkInformation.IPv4InterfaceStatistics GetIPv4Statistics() { throw null; } public static bool GetIsNetworkAvailable() { throw null; } public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { throw null; } public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { throw null; } } public enum NetworkInterfaceComponent { IPv4 = 0, IPv6 = 1, } public enum NetworkInterfaceType { AsymmetricDsl = 94, Atm = 37, BasicIsdn = 20, Ethernet = 6, Ethernet3Megabit = 26, FastEthernetFx = 69, FastEthernetT = 62, Fddi = 15, GenericModem = 48, GigabitEthernet = 117, HighPerformanceSerialBus = 144, IPOverAtm = 114, Isdn = 63, Loopback = 24, MultiRateSymmetricDsl = 143, Ppp = 23, PrimaryIsdn = 21, RateAdaptDsl = 95, Slip = 28, SymmetricDsl = 96, TokenRing = 9, Tunnel = 131, Unknown = 1, VeryHighSpeedDsl = 97, Wireless80211 = 71, Wman = 237, Wwanpp = 243, Wwanpp2 = 244, } public enum OperationalStatus { Dormant = 5, Down = 2, LowerLayerDown = 7, NotPresent = 6, Testing = 3, Unknown = 4, Up = 1, } public partial class PhysicalAddress { public static readonly System.Net.NetworkInformation.PhysicalAddress None; public PhysicalAddress(byte[] address) { } public override bool Equals(object comparand) { throw null; } public byte[] GetAddressBytes() { throw null; } public override int GetHashCode() { throw null; } public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { throw null; } public override string ToString() { throw null; } } public partial class Ping : System.ComponentModel.Component { public Ping() { } public event System.Net.NetworkInformation.PingCompletedEventHandler PingCompleted { add { } remove { } } protected override void Dispose(bool disposing) { } protected void OnPingCompleted(System.Net.NetworkInformation.PingCompletedEventArgs e) { } public System.Net.NetworkInformation.PingReply Send(System.Net.IPAddress address) { throw null; } public System.Net.NetworkInformation.PingReply Send(System.Net.IPAddress address, int timeout) { throw null; } public System.Net.NetworkInformation.PingReply Send(System.Net.IPAddress address, int timeout, byte[] buffer) { throw null; } public System.Net.NetworkInformation.PingReply Send(System.Net.IPAddress address, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions options) { throw null; } public System.Net.NetworkInformation.PingReply Send(string hostNameOrAddress) { throw null; } public System.Net.NetworkInformation.PingReply Send(string hostNameOrAddress, int timeout) { throw null; } public System.Net.NetworkInformation.PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer) { throw null; } public System.Net.NetworkInformation.PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions options) { throw null; } public void SendAsync(System.Net.IPAddress address, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions options, object userToken) { } public void SendAsync(System.Net.IPAddress address, int timeout, byte[] buffer, object userToken) { } public void SendAsync(System.Net.IPAddress address, int timeout, object userToken) { } public void SendAsync(System.Net.IPAddress address, object userToken) { } public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions options, object userToken) { } public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, object userToken) { } public void SendAsync(string hostNameOrAddress, int timeout, object userToken) { } public void SendAsync(string hostNameOrAddress, object userToken) { } public void SendAsyncCancel() { } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(System.Net.IPAddress address) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(System.Net.IPAddress address, int timeout) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(System.Net.IPAddress address, int timeout, byte[] buffer) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(System.Net.IPAddress address, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions options) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(string hostNameOrAddress) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(string hostNameOrAddress, int timeout) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer) { throw null; } public System.Threading.Tasks.Task<System.Net.NetworkInformation.PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions options) { throw null; } } public partial class PingCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { internal PingCompletedEventArgs() : base(null, false, null) { } public System.Net.NetworkInformation.PingReply Reply { get { throw null; } } } public delegate void PingCompletedEventHandler(object sender, System.Net.NetworkInformation.PingCompletedEventArgs e); public partial class PingException : System.InvalidOperationException { protected PingException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public PingException(string message) { } public PingException(string message, System.Exception innerException) { } } public partial class PingOptions { public PingOptions() { } public PingOptions(int ttl, bool dontFragment) { } public bool DontFragment { get { throw null; } set { } } public int Ttl { get { throw null; } set { } } } public partial class PingReply { internal PingReply() { } public System.Net.IPAddress Address { get { throw null; } } public byte[] Buffer { get { throw null; } } public System.Net.NetworkInformation.PingOptions Options { get { throw null; } } public long RoundtripTime { get { throw null; } } public System.Net.NetworkInformation.IPStatus Status { get { throw null; } } } public enum PrefixOrigin { Dhcp = 3, Manual = 1, Other = 0, RouterAdvertisement = 4, WellKnown = 2, } public enum ScopeLevel { Admin = 4, Global = 14, Interface = 1, Link = 2, None = 0, Organization = 8, Site = 5, Subnet = 3, } public enum SuffixOrigin { LinkLayerAddress = 4, Manual = 1, OriginDhcp = 3, Other = 0, Random = 5, WellKnown = 2, } public abstract partial class TcpConnectionInformation { protected TcpConnectionInformation() { } public abstract System.Net.IPEndPoint LocalEndPoint { get; } public abstract System.Net.IPEndPoint RemoteEndPoint { get; } public abstract System.Net.NetworkInformation.TcpState State { get; } } public enum TcpState { Closed = 1, CloseWait = 8, Closing = 9, DeleteTcb = 12, Established = 5, FinWait1 = 6, FinWait2 = 7, LastAck = 10, Listen = 2, SynReceived = 4, SynSent = 3, TimeWait = 11, Unknown = 0, } public abstract partial class TcpStatistics { protected TcpStatistics() { } public abstract long ConnectionsAccepted { get; } public abstract long ConnectionsInitiated { get; } public abstract long CumulativeConnections { get; } public abstract long CurrentConnections { get; } public abstract long ErrorsReceived { get; } public abstract long FailedConnectionAttempts { get; } public abstract long MaximumConnections { get; } public abstract long MaximumTransmissionTimeout { get; } public abstract long MinimumTransmissionTimeout { get; } public abstract long ResetConnections { get; } public abstract long ResetsSent { get; } public abstract long SegmentsReceived { get; } public abstract long SegmentsResent { get; } public abstract long SegmentsSent { get; } } public abstract partial class UdpStatistics { protected UdpStatistics() { } public abstract long DatagramsReceived { get; } public abstract long DatagramsSent { get; } public abstract long IncomingDatagramsDiscarded { get; } public abstract long IncomingDatagramsWithErrors { get; } public abstract int UdpListeners { get; } } public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected UnicastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.IPAddress IPv4Mask { get; } public virtual int PrefixLength { get { throw null; } } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable { protected internal UnicastIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.PublishedCache.Internal; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Serialization; using Umbraco.Cms.Tests.Common.Published; using Umbraco.Cms.Tests.Common.TestHelpers; using Umbraco.Cms.Tests.UnitTests.TestHelpers; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.PropertyEditors { [TestFixture] public class ConvertersTests { [Test] public void SimpleConverter3Test() { var register = new ServiceCollection(); var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader()); composition.WithCollectionBuilder<PropertyValueConverterCollectionBuilder>() .Append<SimpleConverter3A>() .Append<SimpleConverter3B>(); IPublishedModelFactory factory = new PublishedModelFactory( new[] { typeof(PublishedSnapshotTestObjects.TestElementModel1), typeof(PublishedSnapshotTestObjects.TestElementModel2), typeof(PublishedSnapshotTestObjects.TestContentModel1), typeof(PublishedSnapshotTestObjects.TestContentModel2) }, Mock.Of<IPublishedValueFallback>()); register.AddTransient(f => factory); var cacheMock = new Mock<IPublishedContentCache>(); var cacheContent = new Dictionary<int, IPublishedContent>(); cacheMock.Setup(x => x.GetById(It.IsAny<int>())).Returns<int>(id => cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null); var publishedSnapshotMock = new Mock<IPublishedSnapshot>(); publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object); var publishedSnapshotAccessorMock = new Mock<IPublishedSnapshotAccessor>(); var localPublishedSnapshot = publishedSnapshotMock.Object; publishedSnapshotAccessorMock.Setup(x => x.TryGetPublishedSnapshot(out localPublishedSnapshot)).Returns(true); register.AddTransient(f => publishedSnapshotAccessorMock.Object); IServiceProvider registerFactory = composition.CreateServiceProvider(); PropertyValueConverterCollection converters = registerFactory.GetRequiredService<PropertyValueConverterCollection>(); var serializer = new ConfigurationEditorJsonSerializer(); var dataTypeServiceMock = new Mock<IDataTypeService>(); var dataType1 = new DataType( new VoidEditor( Mock.Of<IDataValueEditorFactory>()), serializer) { Id = 1 }; var dataType2 = new DataType( new VoidEditor( "2", Mock.Of<IDataValueEditorFactory>()), serializer) { Id = 2 }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(new[] { dataType1, dataType2 }); var contentTypeFactory = new PublishedContentTypeFactory(factory, converters, dataTypeServiceMock.Object); IEnumerable<IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType, int i) { yield return contentTypeFactory.CreatePropertyType(contentType, "prop" + i, i); } IPublishedContentType elementType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", t => CreatePropertyTypes(t, 1)); IPublishedContentType elementType2 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1001, "element2", t => CreatePropertyTypes(t, 2)); IPublishedContentType contentType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1002, "content1", t => CreatePropertyTypes(t, 1)); IPublishedContentType contentType2 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1003, "content2", t => CreatePropertyTypes(t, 2)); var element1 = new PublishedElement( elementType1, Guid.NewGuid(), new Dictionary<string, object> { { "prop1", "val1" } }, false); var element2 = new PublishedElement( elementType2, Guid.NewGuid(), new Dictionary<string, object> { { "prop2", "1003" } }, false); var cnt1 = new InternalPublishedContent(contentType1) { Id = 1003, Properties = new[] { new InternalPublishedProperty { Alias = "prop1", SolidHasValue = true, SolidValue = "val1" } } }; var cnt2 = new InternalPublishedContent(contentType1) { Id = 1004, Properties = new[] { new InternalPublishedProperty { Alias = "prop2", SolidHasValue = true, SolidValue = "1003" } } }; IPublishedModelFactory publishedModelFactory = registerFactory.GetRequiredService<IPublishedModelFactory>(); cacheContent[cnt1.Id] = cnt1.CreateModel(publishedModelFactory); cacheContent[cnt2.Id] = cnt2.CreateModel(publishedModelFactory); // can get the actual property Clr type // ie ModelType gets properly mapped by IPublishedContentModelFactory // must test ModelClrType with special equals 'cos they are not ref-equals Assert.IsTrue(ModelType.Equals( typeof(IEnumerable<>).MakeGenericType(ModelType.For("content1")), contentType2.GetPropertyType("prop2").ModelClrType)); Assert.AreEqual( typeof(IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>), contentType2.GetPropertyType("prop2").ClrType); // can create a model for an element IPublishedElement model1 = factory.CreateModel(element1); Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestElementModel1>(model1); Assert.AreEqual("val1", ((PublishedSnapshotTestObjects.TestElementModel1)model1).Prop1); // can create a model for a published content IPublishedElement model2 = factory.CreateModel(element2); Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestElementModel2>(model2); var mmodel2 = (PublishedSnapshotTestObjects.TestElementModel2)model2; // and get direct property Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestContentModel1[]>( model2.Value(Mock.Of<IPublishedValueFallback>(), "prop2")); Assert.AreEqual( 1, ((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of<IPublishedValueFallback>(), "prop2")).Length); // and get model property Assert.IsInstanceOf<IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>>(mmodel2.Prop2); Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestContentModel1[]>(mmodel2.Prop2); PublishedSnapshotTestObjects.TestContentModel1 mmodel1 = mmodel2.Prop2.First(); // and we get what we want Assert.AreSame(cacheContent[mmodel1.Id], mmodel1); } public class SimpleConverter3A : PropertyValueConverterBase { public override bool IsConverter(IPublishedPropertyType propertyType) => propertyType.EditorAlias == "Umbraco.Void"; public override Type GetPropertyValueType(IPublishedPropertyType propertyType) => typeof(string); public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) => PropertyCacheLevel.Element; } public class SimpleConverter3B : PropertyValueConverterBase { private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; public SimpleConverter3B(IPublishedSnapshotAccessor publishedSnapshotAccessor) => _publishedSnapshotAccessor = publishedSnapshotAccessor; public override bool IsConverter(IPublishedPropertyType propertyType) => propertyType.EditorAlias == "Umbraco.Void.2"; public override Type GetPropertyValueType(IPublishedPropertyType propertyType) => typeof(IEnumerable<>).MakeGenericType(ModelType.For("content1")); public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) => PropertyCacheLevel.Elements; public override object ConvertSourceToIntermediate( IPublishedElement owner, IPublishedPropertyType propertyType, object source, bool preview) { var s = source as string; return s?.Split(',').Select(int.Parse).ToArray() ?? Array.Empty<int>(); } public override object ConvertIntermediateToObject( IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot(); return ((int[])inter).Select(x => (PublishedSnapshotTestObjects.TestContentModel1)publishedSnapshot.Content .GetById(x)).ToArray(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; using System.Linq; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; namespace Microsoft.NetCore.Analyzers.Data { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class ReviewSqlQueriesForSecurityVulnerabilities : DiagnosticAnalyzer { internal const string RuleId = "CA2100"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ReviewSQLQueriesForSecurityVulnerabilitiesTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageNoNonLiterals = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ReviewSQLQueriesForSecurityVulnerabilitiesMessageNoNonLiterals), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ReviewSQLQueriesForSecurityVulnerabilitiesDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageNoNonLiterals, DiagnosticCategory.Security, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterCompilationStartAction(compilationContext => { INamedTypeSymbol? iDbCommandType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDbCommand); INamedTypeSymbol? iDataAdapterType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDataAdapter); IPropertySymbol? commandTextProperty = iDbCommandType?.GetMembers("CommandText").OfType<IPropertySymbol>().FirstOrDefault(); if (iDbCommandType == null || iDataAdapterType == null || commandTextProperty == null) { return; } compilationContext.RegisterOperationBlockStartAction(operationBlockStartContext => { ISymbol symbol = operationBlockStartContext.OwningSymbol; var isInDbCommandConstructor = false; var isInDataAdapterConstructor = false; if (symbol.Kind != SymbolKind.Method) { return; } var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.MethodKind == MethodKind.Constructor) { CheckForDbCommandAndDataAdapterImplementation(symbol.ContainingType, iDbCommandType, iDataAdapterType, out isInDbCommandConstructor, out isInDataAdapterConstructor); } operationBlockStartContext.RegisterOperationAction(operationContext => { var creation = (IObjectCreationOperation)operationContext.Operation; AnalyzeMethodCall(operationContext, creation.Constructor, symbol, creation.Arguments, creation.Syntax, isInDbCommandConstructor, isInDataAdapterConstructor, iDbCommandType, iDataAdapterType); }, OperationKind.ObjectCreation); // If an object calls a constructor in a base class or the same class, this will get called. operationBlockStartContext.RegisterOperationAction(operationContext => { var invocation = (IInvocationOperation)operationContext.Operation; // We only analyze constructor invocations if (invocation.TargetMethod.MethodKind != MethodKind.Constructor) { return; } // If we're calling another constructor in the same class from this constructor, assume that all parameters are safe and skip analysis. Parameter usage // will be analyzed there if (Equals(invocation.TargetMethod.ContainingType, symbol.ContainingType)) { return; } AnalyzeMethodCall(operationContext, invocation.TargetMethod, symbol, invocation.Arguments, invocation.Syntax, isInDbCommandConstructor, isInDataAdapterConstructor, iDbCommandType, iDataAdapterType); }, OperationKind.Invocation); operationBlockStartContext.RegisterOperationAction(operationContext => { var propertyReference = (IPropertyReferenceOperation)operationContext.Operation; // We're only interested in implementations of IDbCommand.CommandText if (!propertyReference.Property.IsOverrideOrImplementationOfInterfaceMember(commandTextProperty)) { return; } // Make sure we're in assignment statement if (propertyReference.Parent is not IAssignmentOperation assignment) { return; } // Only if the property reference is actually the target of the assignment if (assignment.Target != propertyReference) { return; } ReportDiagnosticIfNecessary(operationContext, assignment.Value, assignment.Syntax, propertyReference.Property, symbol); }, OperationKind.PropertyReference); }); }); } private static void AnalyzeMethodCall(OperationAnalysisContext operationContext, IMethodSymbol constructorSymbol, ISymbol containingSymbol, ImmutableArray<IArgumentOperation> arguments, SyntaxNode invocationSyntax, bool isInDbCommandConstructor, bool isInDataAdapterConstructor, INamedTypeSymbol iDbCommandType, INamedTypeSymbol iDataAdapterType) { CheckForDbCommandAndDataAdapterImplementation(constructorSymbol.ContainingType, iDbCommandType, iDataAdapterType, out var callingDbCommandConstructor, out var callingDataAdapterConstructor); if (!callingDataAdapterConstructor && !callingDbCommandConstructor) { return; } // All parameters the function takes that are explicit strings are potential vulnerabilities var potentials = arguments.WhereAsArray(arg => arg.Parameter.Type.SpecialType == SpecialType.System_String && !arg.Parameter.IsImplicitlyDeclared); if (potentials.IsEmpty) { return; } var vulnerableArgumentsBuilder = ImmutableArray.CreateBuilder<IArgumentOperation>(); foreach (var argument in potentials) { // For the constructor of a IDbCommand-derived class, if there is only one string parameter, then we just // assume that it's the command text. If it takes more than one string, then we need to figure out which // one is the command string. However, for the constructor of a IDataAdapter, a lot of times the // constructor also take in the connection string, so we can't assume it's the command if there is only one // string. if (callingDataAdapterConstructor || potentials.Length > 1) { if (!IsParameterSymbolVulnerable(argument.Parameter)) { continue; } } vulnerableArgumentsBuilder.Add(argument); } var vulnerableArguments = vulnerableArgumentsBuilder.ToImmutable(); foreach (var argument in vulnerableArguments) { if (IsParameterSymbolVulnerable(argument.Parameter) && (isInDbCommandConstructor || isInDataAdapterConstructor)) { //No warnings, as Constructor parameters in derived classes are assumed to be safe since this rule will check the constructor arguments at their call sites. return; } if (ReportDiagnosticIfNecessary(operationContext, argument.Value, invocationSyntax, constructorSymbol, containingSymbol)) { // Only report one warning per invocation return; } } } private static bool IsParameterSymbolVulnerable(IParameterSymbol parameter) { // Parameters might be vulnerable if "cmd" or "command" is in the name return parameter != null && (parameter.Name.IndexOf("cmd", StringComparison.OrdinalIgnoreCase) != -1 || parameter.Name.IndexOf("command", StringComparison.OrdinalIgnoreCase) != -1); } private static bool ReportDiagnosticIfNecessary(OperationAnalysisContext operationContext, IOperation argumentValue, SyntaxNode syntax, ISymbol invokedSymbol, ISymbol containingMethod) { if (operationContext.Options.IsConfiguredToSkipAnalysis(Rule, containingMethod, operationContext.Compilation, operationContext.CancellationToken)) { return false; } if (argumentValue.Type.SpecialType != SpecialType.System_String || !argumentValue.ConstantValue.HasValue) { // We have a candidate for diagnostic. perform more precise dataflow analysis. if (argumentValue.TryGetEnclosingControlFlowGraph(out var cfg)) { var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationContext.Compilation); var valueContentResult = ValueContentAnalysis.TryGetOrComputeResult(cfg, containingMethod, wellKnownTypeProvider, operationContext.Options, Rule, PointsToAnalysisKind.Complete, operationContext.CancellationToken); if (valueContentResult != null) { ValueContentAbstractValue value = valueContentResult[argumentValue.Kind, argumentValue.Syntax]; if (value.NonLiteralState == ValueContainsNonLiteralState.No) { // The value is a constant literal or default/unitialized, so avoid flagging this usage. return false; } } } // Review if the symbol passed to {invocation} in {method/field/constructor/etc} has user input. operationContext.ReportDiagnostic(syntax.CreateDiagnostic(Rule, invokedSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), containingMethod.Name)); return true; } return false; } private static void CheckForDbCommandAndDataAdapterImplementation(INamedTypeSymbol containingType, INamedTypeSymbol iDbCommandType, INamedTypeSymbol iDataAdapterType, out bool implementsDbCommand, out bool implementsDataCommand) { implementsDbCommand = false; implementsDataCommand = false; foreach (var @interface in containingType.AllInterfaces) { if (Equals(@interface, iDbCommandType)) { implementsDbCommand = true; } else if (Equals(@interface, iDataAdapterType)) { implementsDataCommand = true; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class UnionTests { private const int DuplicateFactor = 8; // Get two ranges, with the right starting where the left ends public static IEnumerable<object[]> UnionUnorderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => l, rightCounts.Cast<int>())) { yield return parms.Take(4).ToArray(); } } // Union returns only the ordered portion ordered. See Issue #1331 // Get two ranges, both ordered. public static IEnumerable<object[]> UnionData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, with only the left being ordered. public static IEnumerable<object[]> UnionFirstOrderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] }; } } // Get two ranges, with only the right being ordered. public static IEnumerable<object[]> UnionSecondOrderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, both sourced from arrays, with duplicate items in each array. // Used in distinctness tests, in contrast to relying on a Select predicate to generate duplicate items. public static IEnumerable<object[]> UnionSourceMultipleData(int[] counts) { foreach (int leftCount in counts.Cast<int>()) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel(); foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) }) { int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2; ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel(); yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 }; } } } // // Union // [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); foreach (int i in leftQuery.Union(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery)) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x < leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x >= leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, expectedCount - leftCount); int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { if (i < leftCount) { Assert.Equal(seen++, i); } else { Assert.Equal(leftCount, seen); seenUnordered.Add(i); } } seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { if (i >= leftCount) { seenUnordered.AssertComplete(); Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { int seen = 0; Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_FirstOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, count - leftCount); int seen = 0; foreach (int i in leftQuery.AsOrdered().Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_FirstOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_FirstOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_SecondOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery.AsOrdered())) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(count, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_SecondOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SecondOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Fact] public static void Union_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Union_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Union(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Union(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Union(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Union(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void Union_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace helpsharp.Tasks { using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; /// ------------------------------------------------------------------------------------------------ /// <summary> /// Author: http://stackoverflow.com/users/222434/jim Link: http://stackoverflow.com/a/14945407 /// Factory class to create a periodic Task to simulate a <see cref="System.Threading.Timer"/> /// using <see cref="Task">Tasks.</see> /// </summary> /// ------------------------------------------------------------------------------------------------ public static class PeriodicTaskFactory { #region Public Methods /// ------------------------------------------------------------------------------------------------ /// <summary>Starts the periodic task.</summary> /// <remarks> /// Exceptions that occur in the <paramref name="action"/> need to be handled in the action /// itself. These exceptions will not be bubbled up to the periodic task. /// </remarks> /// <param name="action"> The action.</param> /// <param name="intervalInMilliseconds"> The interval in milliseconds.</param> /// <param name="delayInMilliseconds"> The delay in milliseconds, i.e. how long it waits to /// kick off the timer.</param> /// <param name="duration"> The duration.</param> /// <param name="maxIterations"> The max iterations.</param> /// <param name="synchronous"> if set to <c>true</c> executes each period in a /// blocking fashion and each periodic execution of the task is included in the total duration of /// the Task.</param> /// <param name="cancelToken"> The cancel token.</param> /// <param name="periodicTaskCreationOptions"><see cref="TaskCreationOptions"/> used to create the /// task for executing the <see cref="Action"/>.</param> /// <returns>A <see cref="Task"/></returns> /// <example> /// If the duration is set to 10 seconds, the maximum time this task is allowed to run is 10 /// seconds. /// </example> /// ------------------------------------------------------------------------------------------------ public static Task Start(Action action, int intervalInMilliseconds = Timeout.Infinite, int delayInMilliseconds = 0, int duration = Timeout.Infinite, int maxIterations = -1, bool synchronous = false, CancellationToken cancelToken = new CancellationToken(), TaskCreationOptions periodicTaskCreationOptions = TaskCreationOptions.None) { var stopWatch = new Stopwatch(); Action wrapperAction = () => { CheckIfCancelled(cancelToken); action(); }; Action mainAction = () => { MainPeriodicTaskAction(intervalInMilliseconds, delayInMilliseconds, duration, maxIterations, cancelToken, stopWatch, synchronous, wrapperAction, periodicTaskCreationOptions); }; return Task.Factory.StartNew(mainAction, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } #endregion Public Methods #region Private Methods /// ------------------------------------------------------------------------------------------------ /// <summary>Checks if cancelled.</summary> /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception> /// <param name="cancellationToken">The cancellation token.</param> /// ------------------------------------------------------------------------------------------------ private static void CheckIfCancelled(CancellationToken cancellationToken) { if (cancellationToken == default) { throw new ArgumentNullException(nameof(cancellationToken)); } cancellationToken.ThrowIfCancellationRequested(); } /// ------------------------------------------------------------------------------------------------ /// <summary>Mains the periodic task action.</summary> /// <param name="intervalInMilliseconds"> The interval in milliseconds.</param> /// <param name="delayInMilliseconds"> The delay in milliseconds.</param> /// <param name="duration"> The duration.</param> /// <param name="maxIterations"> The max iterations.</param> /// <param name="cancelToken"> The cancel token.</param> /// <param name="stopWatch"> The stop watch.</param> /// <param name="synchronous"> if set to <c>true</c> executes each period in a /// blocking fashion and each periodic execution of the task is included in the total duration of /// the Task.</param> /// <param name="wrapperAction"> The wrapper action.</param> /// <param name="periodicTaskCreationOptions"><see cref="TaskCreationOptions"/> used to create a /// sub task for executing the <see cref="Action"/>.</param> /// ------------------------------------------------------------------------------------------------ private static void MainPeriodicTaskAction(int intervalInMilliseconds, int delayInMilliseconds, int duration, int maxIterations, CancellationToken cancelToken, Stopwatch stopWatch, bool synchronous, Action wrapperAction, TaskCreationOptions periodicTaskCreationOptions) { var subTaskCreationOptions = TaskCreationOptions.AttachedToParent | periodicTaskCreationOptions; CheckIfCancelled(cancelToken); if (delayInMilliseconds > 0) { Thread.Sleep(delayInMilliseconds); } if (maxIterations == 0) { return; } var iteration = 0; //////////////////////////////////////////////////////////////////////////// // using a ManualResetEventSlim as it is more efficient in small intervals. // In the case where longer intervals are used, it will automatically use // a standard WaitHandle.... // see http://msdn.microsoft.com/en-us/library/vstudio/5hbefs30(v=vs.100).aspx using (var periodResetEvent = new ManualResetEventSlim(false)) { //////////////////////////////////////////////////////////// // Main periodic logic. Basically loop through this block // executing the action while (true) { CheckIfCancelled(cancelToken); var subTask = Task.Factory.StartNew(wrapperAction, cancelToken, subTaskCreationOptions, TaskScheduler.Current); if (synchronous) { stopWatch.Start(); try { subTask.Wait(cancelToken); } catch { /* do not let an errant subtask to kill the periodic task...*/ } stopWatch.Stop(); } // use the same Timeout setting as the System.Threading.Timer, infinite timeout // will execute only one iteration. if (intervalInMilliseconds == Timeout.Infinite) { break; } iteration++; if (maxIterations > 0 && iteration >= maxIterations) { break; } try { stopWatch.Start(); periodResetEvent.Wait(intervalInMilliseconds, cancelToken); stopWatch.Stop(); } catch (OperationCanceledException) { Console.WriteLine("Periodic task has been cancelled"); break; } finally { periodResetEvent.Reset(); } CheckIfCancelled(cancelToken); if (duration > 0 && stopWatch.ElapsedMilliseconds >= duration) { break; } } } } #endregion Private Methods } }
using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; using NPascalCoin.Common; using NPascalCoin.Encoding; using NPascalCoin.Payloads; using NUnit.Framework; using NUnit.Framework.Internal; using Sphere10.Framework; namespace NPascalCoin.UnitTests.Text { public abstract class EPasaTests { [SetUp] public void Setup() { } public abstract IEPasaParser NewInstance(); [Test] public void AccountNumber() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("77", out var epasa)); Assert.AreEqual(77, epasa.Account); Assert.AreEqual(44, epasa.AccountChecksum); Assert.AreEqual(EPasaHelper.ComputeExtendedChecksum("77-44"), epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic, epasa.PayloadType); Assert.AreEqual($"77-44:{EPasaHelper.ComputeExtendedChecksum("77-44")}", epasa.ToString()); } [Test] public void AccountNumber_1() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("1", out var epasa)); Assert.AreEqual(1, epasa.Account); Assert.AreEqual(22, epasa.AccountChecksum); Assert.AreEqual(EPasaHelper.ComputeExtendedChecksum("1-22"), epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic, epasa.PayloadType); Assert.AreEqual($"1-22:{EPasaHelper.ComputeExtendedChecksum("1-22")}", epasa.ToString()); } [Test] public void AccountNumber_Illegal() { var parser = NewInstance(); Assert.IsFalse(parser.TryParse("077", out var epasa)); Assert.IsFalse(parser.TryParse("77s-44", out epasa)); } [Test] public void AccountNumber_Checksum() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("77-44", out var epasa)); Assert.AreEqual(77, epasa.Account); Assert.AreEqual(44, epasa.AccountChecksum); Assert.AreEqual(EPasaHelper.ComputeExtendedChecksum("77-44"), epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic, epasa.PayloadType); Assert.AreEqual($"77-44:{EPasaHelper.ComputeExtendedChecksum("77-44")}", epasa.ToString()); } [Test] public void AccountNumber_0_10() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("0-10", out var epasa)); Assert.AreEqual(0, epasa.Account); Assert.AreEqual(10, epasa.AccountChecksum); Assert.AreEqual(EPasaHelper.ComputeExtendedChecksum("0-10"), epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic, epasa.PayloadType); Assert.AreEqual($"0-10:{EPasaHelper.ComputeExtendedChecksum("0-10")}", epasa.ToString()); } [Test] public void AccountNumber_Checksum_Illegal() { var parser = NewInstance(); Assert.IsFalse(parser.TryParse("77- 44", out var epasa)); Assert.IsFalse(parser.TryParse("77-444", out epasa)); Assert.IsFalse(parser.TryParse("77-4c", out epasa)); } [Test] public void AccountNumber_ExtendedChecksum() { var parser = NewInstance(); var epasaText = "77-44"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(77, epasa.Account); Assert.AreEqual(44, epasa.AccountChecksum); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic, epasa.PayloadType); Assert.AreEqual(epasaText, epasa.ToString()); } [Test] public void AccountNumber_ExtendedChecksum_Illegal() { var parser = NewInstance(); var epasaText = "77-44:0000"; Assert.IsFalse(parser.TryParse(epasaText, out var epasa)); } [Test] public void AccountNumber_Payload_ExtendedChecksum() { var parser = NewInstance(); var epasaText = @"77-44[""Hello World!""]"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(77, epasa.Account); Assert.AreEqual(44, epasa.AccountChecksum); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.Public | PayloadType.AsciiFormatted, epasa.PayloadType); Assert.AreEqual("Hello World!", epasa.Payload); Assert.AreEqual(epasaText, epasa.ToString()); } [Test] public void AccountNumber_Password_Valid() { var parser = NewInstance(); var epasaText = @"77-44{""Hello World!"":abcdefg}"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(77, epasa.Account); Assert.AreEqual(44, epasa.AccountChecksum); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual("abcdefg", epasa.Password); Assert.AreEqual(PayloadType.PasswordEncrypted | PayloadType.AsciiFormatted, epasa.PayloadType); Assert.AreEqual("Hello World!", epasa.Payload); Assert.AreEqual(epasaText, epasa.ToString()); } [Test] public void AccountNumber_EncryptionAndEncoding() { var parser = NewInstance(); Assert.AreEqual(PayloadType.Public | PayloadType.AsciiFormatted, parser.Parse(@"77-44[""Hello World!""]").PayloadType); Assert.AreEqual(PayloadType.Public | PayloadType.HexFormatted, parser.Parse(@"77-44[0x1234]").PayloadType); Assert.AreEqual(PayloadType.Public | PayloadType.Base58Formatted, parser.Parse(@"77-44[B58abcdefg]").PayloadType); Assert.AreEqual(PayloadType.RecipientKeyEncrypted | PayloadType.AsciiFormatted, parser.Parse(@"77-44(""Hello World!"")").PayloadType); Assert.AreEqual(PayloadType.RecipientKeyEncrypted | PayloadType.HexFormatted, parser.Parse(@"77-44(0x1234)").PayloadType); Assert.AreEqual(PayloadType.RecipientKeyEncrypted | PayloadType.Base58Formatted, parser.Parse(@"77-44(B58abcdefg)").PayloadType); Assert.AreEqual(PayloadType.SenderKeyEncrypted | PayloadType.AsciiFormatted, parser.Parse(@"77-44<""Hello World!"">").PayloadType); Assert.AreEqual(PayloadType.SenderKeyEncrypted | PayloadType.HexFormatted, parser.Parse(@"77-44<0x1234>").PayloadType); Assert.AreEqual(PayloadType.SenderKeyEncrypted | PayloadType.Base58Formatted, parser.Parse(@"77-44<B58abcdefg>").PayloadType); Assert.AreEqual(PayloadType.PasswordEncrypted | PayloadType.AsciiFormatted, parser.Parse(@"77-44{""Hello World!"":abc}").PayloadType); Assert.AreEqual(PayloadType.PasswordEncrypted | PayloadType.HexFormatted, parser.Parse(@"77-44{0x1234:abc}").PayloadType); Assert.AreEqual(PayloadType.PasswordEncrypted | PayloadType.Base58Formatted, parser.Parse(@"77-44{B58abcdefg:abc}").PayloadType); } [Test] public void AccountNumber_NonDeterministic_PayloadType() { var parser = NewInstance(); Assert.AreEqual(PayloadType.NonDeterministic, parser.Parse(@"77-44").PayloadType); Assert.AreEqual(PayloadType.Public | PayloadType.NonDeterministic, parser.Parse(@"77-44[]").PayloadType); Assert.AreEqual(PayloadType.RecipientKeyEncrypted | PayloadType.NonDeterministic, parser.Parse(@"77-44()").PayloadType); Assert.AreEqual(PayloadType.SenderKeyEncrypted | PayloadType.NonDeterministic, parser.Parse(@"77-44<>").PayloadType); Assert.AreEqual(PayloadType.PasswordEncrypted | PayloadType.NonDeterministic, parser.Parse(@"77-44{:abc}").PayloadType); Assert.AreEqual(PayloadType.PasswordEncrypted | PayloadType.NonDeterministic, parser.Parse(@"77-44{:}").PayloadType); } [Test] public void AccountNumber_NonDeterministic_ToString() { var parser = NewInstance(); Assert.AreEqual("77-44", parser.Parse(@"77-44").ToString(true)); Assert.AreEqual("77-44[]", parser.Parse("77-44[]").ToString(true)); Assert.AreEqual("77-44()", parser.Parse("77-44()").ToString(true)); Assert.AreEqual("77-44<>", parser.Parse("77-44<>").ToString(true)); Assert.AreEqual("77-44{:abc}", parser.Parse("77-44{:abc}").ToString(true)); Assert.AreEqual("77-44{:}", parser.Parse("77-44{:}").ToString(true)); } [Test] public void AccountName() { var parser = NewInstance(); var epasaText = "pascalcoin-foundation"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(null, epasa.Account); Assert.AreEqual(null, epasa.AccountChecksum); Assert.AreEqual("pascalcoin-foundation", epasa.AccountName); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic | PayloadType.AddressedByName, epasa.PayloadType); Assert.AreEqual($"{epasaText}:{checksum}", epasa.ToString()); } [Test] public void AccountName_ExtendedChecksum() { var parser = NewInstance(); var epasaText = "pascalcoin-foundation"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(null, epasa.Account); Assert.AreEqual(null, epasa.AccountChecksum); Assert.AreEqual("pascalcoin-foundation", epasa.AccountName); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.NonDeterministic | PayloadType.AddressedByName, epasa.PayloadType); Assert.AreEqual(epasaText, epasa.ToString()); } [Test] public void AccountName_Payload_ExtendedChecksum() { var parser = NewInstance(); var epasaText = @"pascalcoin-foundation[""Hello World!""]"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(null, epasa.Account); Assert.AreEqual(null, epasa.AccountChecksum); Assert.AreEqual("pascalcoin-foundation", epasa.AccountName); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual(PayloadType.Public | PayloadType.AsciiFormatted | PayloadType.AddressedByName, epasa.PayloadType); Assert.AreEqual("Hello World!", epasa.Payload); Assert.AreEqual(epasaText, epasa.ToString()); } [Test] public void AccountName_EncryptionAndEncoding() { var parser = NewInstance(); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.Public | PayloadType.AsciiFormatted, parser.Parse(@"pascalcoin-foundation[""Hello World!""]").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.Public | PayloadType.HexFormatted, parser.Parse(@"pascalcoin-foundation[0x1234]").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.Public | PayloadType.Base58Formatted, parser.Parse(@"pascalcoin-foundation[B58abcdefg]").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.RecipientKeyEncrypted | PayloadType.AsciiFormatted, parser.Parse(@"pascalcoin-foundation(""Hello World!"")").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.RecipientKeyEncrypted | PayloadType.HexFormatted, parser.Parse(@"pascalcoin-foundation(0x1234)").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.RecipientKeyEncrypted | PayloadType.Base58Formatted, parser.Parse(@"pascalcoin-foundation(B58abcdefg)").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.SenderKeyEncrypted | PayloadType.AsciiFormatted, parser.Parse(@"pascalcoin-foundation<""Hello World!"">").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.SenderKeyEncrypted | PayloadType.HexFormatted, parser.Parse(@"pascalcoin-foundation<0x1234>").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.SenderKeyEncrypted | PayloadType.Base58Formatted, parser.Parse(@"pascalcoin-foundation<B58abcdefg>").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.PasswordEncrypted | PayloadType.AsciiFormatted, parser.Parse(@"pascalcoin-foundation{""Hello World!"":abc}").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.PasswordEncrypted | PayloadType.HexFormatted, parser.Parse(@"pascalcoin-foundation{0x1234:abc}").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.PasswordEncrypted | PayloadType.Base58Formatted, parser.Parse(@"pascalcoin-foundation{B58abcdefg:abc}").PayloadType); } [Test] public void AccountName_NonDeterministic_PayloadType() { var parser = NewInstance(); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.NonDeterministic, parser.Parse(@"pascalcoin-foundation").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.Public | PayloadType.NonDeterministic, parser.Parse(@"pascalcoin-foundation[]").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.RecipientKeyEncrypted | PayloadType.NonDeterministic, parser.Parse(@"pascalcoin-foundation()").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.SenderKeyEncrypted | PayloadType.NonDeterministic, parser.Parse(@"pascalcoin-foundation<>").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.PasswordEncrypted | PayloadType.NonDeterministic, parser.Parse(@"pascalcoin-foundation{:abc}").PayloadType); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.PasswordEncrypted | PayloadType.NonDeterministic, parser.Parse(@"pascalcoin-foundation{:}").PayloadType); } [Test] public void AccountName_NonDeterministic_ToString() { var parser = NewInstance(); Assert.AreEqual("pascalcoin-foundation", parser.Parse(@"pascalcoin-foundation").ToString(true)); Assert.AreEqual("pascalcoin-foundation[]", parser.Parse("pascalcoin-foundation[]").ToString(true)); Assert.AreEqual("pascalcoin-foundation()", parser.Parse("pascalcoin-foundation()").ToString(true)); Assert.AreEqual("pascalcoin-foundation<>", parser.Parse("pascalcoin-foundation<>").ToString(true)); Assert.AreEqual("pascalcoin-foundation{:abc}", parser.Parse("pascalcoin-foundation{:abc}").ToString(true)); Assert.AreEqual("pascalcoin-foundation{:}", parser.Parse("pascalcoin-foundation{:}").ToString(true)); } [Test] public void AccountName_Short() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("a", out var epasa)); } [Test] public void AccountName_Short_WithChecksum() { var parser = NewInstance(); var epasaText = "a"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); } [Test] public void PayToKey() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("@[1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2]", out var epasa)); Assert.IsTrue(epasa.IsPayToKey); } [Test] public void PayToKey_WithChecksum() { var parser = NewInstance(); var epasaText = "@[1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2]"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.IsTrue(epasa.IsPayToKey); } [Test] public void NotPayToKey_1() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("@<1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2>", out var epasa)); Assert.IsFalse(epasa.IsPayToKey); } [Test] public void NotPayToKey_2() { var parser = NewInstance(); Assert.IsTrue(parser.TryParse("@[0x0123456789abcdef]", out var epasa)); Assert.IsFalse(epasa.IsPayToKey); } [Test] public void EdgeCase_AllEscapeChars() { var parser = NewInstance(); var name = @"(a)b{c}d[e]f:g""h<i>"; var content = @"""a(b)c:d<e>f[g\h]i{j}"; var password = name; var epasaText = $@"{Pascal64Encoding.Escape(name)}{{""{PascalAsciiEncoding.Escape(content)}"":{PascalAsciiEncoding.Escape(password)}}}"; var checksum = EPasaHelper.ComputeExtendedChecksum(epasaText); epasaText = $"{epasaText}:{checksum}"; Assert.IsTrue(parser.TryParse(epasaText, out var epasa)); Assert.AreEqual(null, epasa.Account); Assert.AreEqual(null, epasa.AccountChecksum); Assert.AreEqual(name, epasa.AccountName); Assert.AreEqual(checksum, epasa.ExtendedChecksum); Assert.AreEqual(password, epasa.Password); Assert.AreEqual(PayloadType.AddressedByName | PayloadType.PasswordEncrypted | PayloadType.AsciiFormatted, epasa.PayloadType); Assert.AreEqual(content, epasa.Payload); Assert.AreEqual(epasaText, epasa.ToString()); } } }
namespace FacsalData.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.AppointmentType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 35), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.DepartmentModification", c => new { ModificationId = c.Long(nullable: false, identity: true), UpdatedBy = c.String(), UpdatedDate = c.DateTimeOffset(nullable: false, precision: 7), Department_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.ModificationId) .ForeignKey("dbo.Department", t => t.Department_Id) .Index(t => t.Department_Id); CreateTable( "dbo.Department", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 50), SequenceValue = c.String(nullable: false, maxLength: 3), UnitId = c.String(maxLength: 128), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Unit", t => t.UnitId) .Index(t => t.UnitId); CreateTable( "dbo.Employment", c => new { Id = c.Long(nullable: false, identity: true), PersonId = c.String(maxLength: 128), DepartmentId = c.String(maxLength: 128), HomeDepartmentId = c.String(maxLength: 128), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), Department_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Department", t => t.DepartmentId) .ForeignKey("dbo.Department", t => t.HomeDepartmentId) .ForeignKey("dbo.Person", t => t.PersonId) .ForeignKey("dbo.Department", t => t.Department_Id) .Index(t => t.PersonId) .Index(t => t.DepartmentId) .Index(t => t.HomeDepartmentId) .Index(t => t.Department_Id); CreateTable( "dbo.Person", c => new { Id = c.String(nullable: false, maxLength: 128), Pid = c.String(nullable: false, maxLength: 30), LastName = c.String(nullable: false, maxLength: 35), FirstName = c.String(nullable: false, maxLength: 35), StatusTypeId = c.Int(nullable: false), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.StatusType", t => t.StatusTypeId, cascadeDelete: true) .Index(t => t.StatusTypeId); CreateTable( "dbo.PersonModification", c => new { ModificationId = c.Long(nullable: false, identity: true), UpdatedBy = c.String(), UpdatedDate = c.DateTimeOffset(nullable: false, precision: 7), Person_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.ModificationId) .ForeignKey("dbo.Person", t => t.Person_Id) .Index(t => t.Person_Id); CreateTable( "dbo.Salary", c => new { Id = c.Long(nullable: false, identity: true), PersonId = c.String(maxLength: 128), CycleYear = c.Int(nullable: false), Title = c.String(maxLength: 128), FacultyTypeId = c.Int(nullable: false), RankTypeId = c.String(maxLength: 128), AppointmentTypeId = c.Int(nullable: false), LeaveTypeId = c.Int(nullable: false), FullTimeEquivalent = c.Decimal(nullable: false, precision: 18, scale: 2), BannerBaseAmount = c.Int(), BaseAmount = c.Int(nullable: false), AdminAmount = c.Int(nullable: false), EminentAmount = c.Int(nullable: false), PromotionAmount = c.Int(nullable: false), MeritIncrease = c.Int(nullable: false), SpecialIncrease = c.Int(nullable: false), EminentIncrease = c.Int(nullable: false), BaseSalaryAdjustmentNote = c.String(maxLength: 1024), MeritAdjustmentTypeId = c.Int(), MeritAdjustmentNote = c.String(maxLength: 1024), SpecialAdjustmentNote = c.String(maxLength: 1024), Comments = c.String(maxLength: 1024), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AppointmentType", t => t.AppointmentTypeId, cascadeDelete: true) .ForeignKey("dbo.FacultyType", t => t.FacultyTypeId, cascadeDelete: true) .ForeignKey("dbo.LeaveType", t => t.LeaveTypeId, cascadeDelete: true) .ForeignKey("dbo.MeritAdjustmentType", t => t.MeritAdjustmentTypeId) .ForeignKey("dbo.Person", t => t.PersonId) .ForeignKey("dbo.RankType", t => t.RankTypeId) .Index(t => t.PersonId) .Index(t => t.FacultyTypeId) .Index(t => t.RankTypeId) .Index(t => t.AppointmentTypeId) .Index(t => t.LeaveTypeId) .Index(t => t.MeritAdjustmentTypeId); CreateTable( "dbo.BaseSalaryAdjustment", c => new { Id = c.Long(nullable: false, identity: true), StartingBaseAmount = c.Int(nullable: false), NewBaseAmount = c.Int(nullable: false), SalaryId = c.Long(nullable: false), BaseAdjustmentTypeId = c.Int(nullable: false), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.BaseAdjustmentType", t => t.BaseAdjustmentTypeId, cascadeDelete: true) .ForeignKey("dbo.Salary", t => t.SalaryId, cascadeDelete: true) .Index(t => t.SalaryId) .Index(t => t.BaseAdjustmentTypeId); CreateTable( "dbo.BaseAdjustmentType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 35), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.FacultyType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 35), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.LeaveType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 35), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.MeritAdjustmentType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 60), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SalaryModification", c => new { ModificationId = c.Long(nullable: false, identity: true), UpdatedBy = c.String(), UpdatedDate = c.DateTimeOffset(nullable: false, precision: 7), Salary_Id = c.Long(), }) .PrimaryKey(t => t.ModificationId) .ForeignKey("dbo.Salary", t => t.Salary_Id) .Index(t => t.Salary_Id); CreateTable( "dbo.RankType", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 35), SequenceValue = c.String(nullable: false, maxLength: 3), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SpecialSalaryAdjustment", c => new { Id = c.Long(nullable: false, identity: true), SalaryId = c.Long(nullable: false), SpecialAdjustmentTypeId = c.Int(nullable: false), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Salary", t => t.SalaryId, cascadeDelete: true) .ForeignKey("dbo.SpecialAdjustmentType", t => t.SpecialAdjustmentTypeId, cascadeDelete: true) .Index(t => t.SalaryId) .Index(t => t.SpecialAdjustmentTypeId); CreateTable( "dbo.SpecialAdjustmentType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 35), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.StatusType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 35), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Unit", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 50), SequenceValue = c.String(nullable: false, maxLength: 3), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.UnitModification", c => new { ModificationId = c.Long(nullable: false, identity: true), UpdatedBy = c.String(), UpdatedDate = c.DateTimeOffset(nullable: false, precision: 7), Unit_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.ModificationId) .ForeignKey("dbo.Unit", t => t.Unit_Id) .Index(t => t.Unit_Id); CreateTable( "dbo.RoleAssignment", c => new { Id = c.Int(nullable: false, identity: true), RoleId = c.Int(nullable: false), UserId = c.Int(nullable: false), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Role", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.User", t => t.UserId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.Role", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true); CreateTable( "dbo.User", c => new { Id = c.Int(nullable: false, identity: true), Pid = c.String(nullable: false, maxLength: 30), CreatedBy = c.String(), CreatedDate = c.DateTimeOffset(nullable: false, precision: 7), RowVersion = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => t.Pid, unique: true); } public override void Down() { DropForeignKey("dbo.RoleAssignment", "UserId", "dbo.User"); DropForeignKey("dbo.RoleAssignment", "RoleId", "dbo.Role"); DropForeignKey("dbo.Department", "UnitId", "dbo.Unit"); DropForeignKey("dbo.UnitModification", "Unit_Id", "dbo.Unit"); DropForeignKey("dbo.DepartmentModification", "Department_Id", "dbo.Department"); DropForeignKey("dbo.Employment", "Department_Id", "dbo.Department"); DropForeignKey("dbo.Employment", "PersonId", "dbo.Person"); DropForeignKey("dbo.Person", "StatusTypeId", "dbo.StatusType"); DropForeignKey("dbo.SpecialSalaryAdjustment", "SpecialAdjustmentTypeId", "dbo.SpecialAdjustmentType"); DropForeignKey("dbo.SpecialSalaryAdjustment", "SalaryId", "dbo.Salary"); DropForeignKey("dbo.Salary", "RankTypeId", "dbo.RankType"); DropForeignKey("dbo.Salary", "PersonId", "dbo.Person"); DropForeignKey("dbo.SalaryModification", "Salary_Id", "dbo.Salary"); DropForeignKey("dbo.Salary", "MeritAdjustmentTypeId", "dbo.MeritAdjustmentType"); DropForeignKey("dbo.Salary", "LeaveTypeId", "dbo.LeaveType"); DropForeignKey("dbo.Salary", "FacultyTypeId", "dbo.FacultyType"); DropForeignKey("dbo.BaseSalaryAdjustment", "SalaryId", "dbo.Salary"); DropForeignKey("dbo.BaseSalaryAdjustment", "BaseAdjustmentTypeId", "dbo.BaseAdjustmentType"); DropForeignKey("dbo.Salary", "AppointmentTypeId", "dbo.AppointmentType"); DropForeignKey("dbo.PersonModification", "Person_Id", "dbo.Person"); DropForeignKey("dbo.Employment", "HomeDepartmentId", "dbo.Department"); DropForeignKey("dbo.Employment", "DepartmentId", "dbo.Department"); DropIndex("dbo.User", new[] { "Pid" }); DropIndex("dbo.Role", new[] { "Name" }); DropIndex("dbo.RoleAssignment", new[] { "UserId" }); DropIndex("dbo.RoleAssignment", new[] { "RoleId" }); DropIndex("dbo.UnitModification", new[] { "Unit_Id" }); DropIndex("dbo.SpecialSalaryAdjustment", new[] { "SpecialAdjustmentTypeId" }); DropIndex("dbo.SpecialSalaryAdjustment", new[] { "SalaryId" }); DropIndex("dbo.SalaryModification", new[] { "Salary_Id" }); DropIndex("dbo.BaseSalaryAdjustment", new[] { "BaseAdjustmentTypeId" }); DropIndex("dbo.BaseSalaryAdjustment", new[] { "SalaryId" }); DropIndex("dbo.Salary", new[] { "MeritAdjustmentTypeId" }); DropIndex("dbo.Salary", new[] { "LeaveTypeId" }); DropIndex("dbo.Salary", new[] { "AppointmentTypeId" }); DropIndex("dbo.Salary", new[] { "RankTypeId" }); DropIndex("dbo.Salary", new[] { "FacultyTypeId" }); DropIndex("dbo.Salary", new[] { "PersonId" }); DropIndex("dbo.PersonModification", new[] { "Person_Id" }); DropIndex("dbo.Person", new[] { "StatusTypeId" }); DropIndex("dbo.Employment", new[] { "Department_Id" }); DropIndex("dbo.Employment", new[] { "HomeDepartmentId" }); DropIndex("dbo.Employment", new[] { "DepartmentId" }); DropIndex("dbo.Employment", new[] { "PersonId" }); DropIndex("dbo.Department", new[] { "UnitId" }); DropIndex("dbo.DepartmentModification", new[] { "Department_Id" }); DropTable("dbo.User"); DropTable("dbo.Role"); DropTable("dbo.RoleAssignment"); DropTable("dbo.UnitModification"); DropTable("dbo.Unit"); DropTable("dbo.StatusType"); DropTable("dbo.SpecialAdjustmentType"); DropTable("dbo.SpecialSalaryAdjustment"); DropTable("dbo.RankType"); DropTable("dbo.SalaryModification"); DropTable("dbo.MeritAdjustmentType"); DropTable("dbo.LeaveType"); DropTable("dbo.FacultyType"); DropTable("dbo.BaseAdjustmentType"); DropTable("dbo.BaseSalaryAdjustment"); DropTable("dbo.Salary"); DropTable("dbo.PersonModification"); DropTable("dbo.Person"); DropTable("dbo.Employment"); DropTable("dbo.Department"); DropTable("dbo.DepartmentModification"); DropTable("dbo.AppointmentType"); } } }
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using System.Text; namespace Sharpex2D.Math { [Developer("ThuCommix", "developer@sharpex2d.de")] [TestState(TestState.Untested)] public struct Matrix : ICloneable { #region Matrix private readonly int _columns; private readonly double[,] _fields; private readonly int _rows; /// <summary> /// Initializes a new Matrix class. /// </summary> /// <param name="columns">The amount of Columns.</param> /// <param name="rows">The amount of Rows.</param> public Matrix(int columns, int rows) { _fields = new double[columns, rows]; for (int x = 0; x <= columns - 1; x++) { for (int y = 0; y <= rows - 1; y++) { _fields[x, y] = 0; } } _columns = columns; _rows = rows; } /// <summary> /// Gets the amount of columns. /// </summary> public int Columns { get { return _columns; } } /// <summary> /// Gets the amount of rows. /// </summary> public int Rows { get { return _rows; } } /// <summary> /// Clones the Matrix. /// </summary> /// <returns>Object</returns> public object Clone() { return MemberwiseClone(); } /// <summary> /// Sets a value of the element. /// </summary> /// <param name="column">The Column.</param> /// <param name="row">The Row.</param> /// <param name="value">The Value.</param> public void Set(int column, int row, double value) { if (column > _columns || column < 0) { throw new ArgumentOutOfRangeException("column"); } if (row > _rows || row < 0) { throw new ArgumentOutOfRangeException("row"); } _fields[column, row] = value; } /// <summary> /// Gets the value of the element. /// </summary> /// <param name="column">The Column.</param> /// <param name="row">The Row.</param> /// <returns>The value of the element</returns> public double Get(int column, int row) { if (column > _columns || column < 0) { throw new ArgumentOutOfRangeException("column"); } if (row > _rows || row < 0) { throw new ArgumentOutOfRangeException("row"); } return _fields[column, row]; } /// <summary> /// Converts the Matrix in to a string. /// </summary> /// <returns>String</returns> public override string ToString() { var sb = new StringBuilder(); for (int y = 0; y <= Rows - 1; y++) { for (int x = 0; x <= Columns - 1; x++) { if (x == Columns - 1) { sb.Append(Get(x, y)); } else { sb.Append(Get(x, y) + ", "); } } sb.AppendLine(); } return sb.ToString(); } /// <summary> /// Check if another matrix is equal to the current matrix. /// </summary> /// <param name="other">The Matrix.</param> /// <returns></returns> public bool Equals(Matrix other) { return Equals(_fields, other._fields) && _columns == other._columns && _rows == other._rows; } /// <summary> /// Check if another matrix is equal to the current matrix. /// </summary> /// <param name="obj">The Matrix.</param> /// <returns></returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((Matrix) obj); } /// <summary> /// Gets the HashCode. /// </summary> /// <returns>Int32</returns> public override int GetHashCode() { unchecked { int hashCode = (_fields != null ? _fields.GetHashCode() : 0); hashCode = (hashCode*397) ^ _columns; hashCode = (hashCode*397) ^ _rows; return hashCode; } } /// <summary> /// Checks for Null. /// </summary> /// <param name="matrices">The Matrices.</param> private static void CheckForNull(params Matrix[] matrices) { if (matrices.Any(matrix => matrix == null)) { throw new ArgumentNullException("matrices"); } } /// <summary> /// Copys the current Matrix to another matrix. /// </summary> /// <param name="matrix">The Matrix.</param> public void CopyTo(Matrix matrix) { if (Columns == matrix.Columns && Rows == matrix.Rows) { for (int y = 0; y <= Rows - 1; y++) { for (int x = 0; x <= Columns - 1; x++) { matrix.Set(x, y, Get(x, y)); } } } else { throw new ArgumentException("The matrices needs to have the same size."); } } /// <summary> /// Resizes the matrix. /// </summary> /// <param name="columns">The Columns.</param> /// <param name="rows">The Rows.</param> /// <returns>Matrix</returns> public Matrix Resize(int columns, int rows) { var result = new Matrix(columns, rows); for (int y = 0; y <= rows - 1; y++) { for (int x = 0; x <= columns - 1; x++) { if (x <= Columns - 1 && y <= Rows - 1) { result.Set(x, y, Get(x, y)); } else { result.Set(x, y, 0); } } } return result; } #region Operator /// <summary> /// Addition of two matrices. /// </summary> /// <param name="a">The first Matrix.</param> /// <param name="b">The second Matrix.</param> /// <returns>Matrix</returns> public static Matrix operator +(Matrix a, Matrix b) { CheckForNull(a, b); if (a.Columns != b.Columns || a.Rows != b.Rows) throw new InvalidOperationException("The two matrices needs to have the same size."); var result = new Matrix(a.Columns, a.Rows); for (int y = 0; y <= a.Rows - 1; y++) { for (int x = 0; x <= a.Columns - 1; x++) { result.Set(x, y, a.Get(x, y) + b.Get(x, y)); } } return result; } /// <summary> /// Substraction of two matrices. /// </summary> /// <param name="a">The first Matrix.</param> /// <param name="b">The second Matrix.</param> /// <returns>Matrix</returns> public static Matrix operator -(Matrix a, Matrix b) { CheckForNull(a, b); if (a.Columns != b.Columns || a.Rows != b.Rows) throw new InvalidOperationException("The two matrices needs to have the same size."); var result = new Matrix(a.Columns, a.Rows); for (int y = 0; y <= a.Rows - 1; y++) { for (int x = 0; x <= a.Columns - 1; x++) { result.Set(x, y, a.Get(x, y) - b.Get(x, y)); } } return result; } /// <summary> /// Multiplys two matrices. /// </summary> /// <param name="a">The first Matrix.</param> /// <param name="b">The second Matrix.</param> /// <returns>Matrix</returns> public static Matrix operator *(Matrix a, Matrix b) { CheckForNull(a, b); if (a.Columns != b.Columns || a.Rows != b.Rows) throw new InvalidOperationException("The two matrices needs to have the same size."); var result = new Matrix(a.Columns, a.Rows); for (int y = 0; y <= a.Rows - 1; y++) { for (int x = 0; x <= a.Columns - 1; x++) { result.Set(x, y, a.Get(x, y)*b.Get(x, y)); } } return result; } /// <summary> /// Scalarmultiply with a matrix. /// </summary> /// <param name="a">The Matrix.</param> /// <param name="scalar">The Scalar</param> /// <returns>Matrix</returns> public static Matrix operator *(Matrix a, double scalar) { CheckForNull(a); var result = new Matrix(a.Columns, a.Rows); for (int y = 0; y <= a.Rows - 1; y++) { for (int x = 0; x <= a.Columns - 1; x++) { result.Set(x, y, a.Get(x, y)*scalar); } } return result; } /// <summary> /// Scalarmultiply with a matrix. /// </summary> /// <param name="a">The Matrix.</param> /// <param name="scalar">The Scalar</param> /// <returns>Matrix</returns> public static Matrix operator *(double scalar, Matrix a) { CheckForNull(a); var result = new Matrix(a.Columns, a.Rows); for (int y = 0; y <= a.Rows - 1; y++) { for (int x = 0; x <= a.Columns - 1; x++) { result.Set(x, y, a.Get(x, y)*scalar); } } return result; } /// <summary> /// Divide two matrices. /// </summary> /// <param name="a">The first Matrix.</param> /// <param name="b">The second Matrix.</param> /// <returns>Matrix</returns> public static Matrix operator /(Matrix a, Matrix b) { CheckForNull(a, b); if (a.Columns != b.Columns || a.Rows != b.Rows) throw new InvalidOperationException("The two matrices needs to have the same size."); var result = new Matrix(a.Columns, a.Rows); for (int y = 0; y <= a.Rows - 1; y++) { for (int x = 0; x <= a.Columns - 1; x++) { result.Set(x, y, a.Get(x, y)/b.Get(x, y)); } } return result; } public static bool operator ==(Matrix a, Matrix b) { CheckForNull(a, b); return a != null && a.Equals(b); } public static bool operator !=(Matrix a, Matrix b) { CheckForNull(a, b); return a != null && !a.Equals(b); } /// <summary> /// Addition with another matrix. /// </summary> /// <param name="other">The Matrix.</param> /// <returns>Matrix</returns> public Matrix Addition(Matrix other) { return this + other; } /// <summary> /// Substract with another matrix. /// </summary> /// <param name="other">The Matrix.</param> /// <returns>Matrix</returns> public Matrix Subtract(Matrix other) { return this - other; } /// <summary> /// Multiply with another matrix. /// </summary> /// <param name="other">The Matrix.</param> /// <returns>Matrix</returns> public Matrix Multiply(Matrix other) { return this*other; } /// <summary> /// Multiply with a scalar. /// </summary> /// <param name="scalar">The Scalar.</param> /// <returns>Matrix</returns> public Matrix Multiply(double scalar) { return this*scalar; } /// <summary> /// Divide with another matrix. /// </summary> /// <param name="other">The Matrix.</param> /// <returns>Matrix</returns> public Matrix Divide(Matrix other) { return this/other; } /// <summary> /// Pow the matrix. /// </summary> /// <param name="exponent">The Exponent.</param> /// <returns>Matrix</returns> public Matrix Pow(double exponent) { var result = new Matrix(Columns, Rows); for (int y = 0; y <= Rows - 1; y++) { for (int x = 0; x <= Columns - 1; x++) { result.Set(x, y, MathHelper.Pow((float) Get(x, y), (float) exponent)); } } return result; } /// <summary> /// Transposes the matrix. /// </summary> /// <returns>Matrix</returns> public Matrix Transpose() { var result = new Matrix(Rows, Columns); for (int y = 0; y <= Rows - 1; y++) { for (int x = 0; x <= Columns - 1; x++) { result.Set(y, x, Get(x, y)); } } return result; } #endregion #endregion } }
/* Copyright 2017 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using ArcGIS.Core.Data; using ArcGIS.Core.Data.PluginDatastore; using ArcGIS.Core.Geometry; namespace ProGpxPluginDatasource { /// <summary> /// (Custom) interface the sample uses to extract row information from the /// plugin table /// </summary> internal interface IPluginRowProvider { PluginRow FindRow(int oid, IEnumerable<string> columnFilter, SpatialReference sr); } public class ProGpxPluginTableTemplate : PluginTableTemplate, IDisposable, IPluginRowProvider { private readonly DataTable _dataTable = new DataTable(); private readonly string _gpxFilePath; private readonly SpatialReference _spatialReference; private readonly string _tableName; private Envelope _gisExtent; private const string GeometryFieldName = "Shape"; private const string ObjectIdFieldName = "ObjectId"; private const string LongFieldName = "Longitude"; private const string LatFieldName = "Latitude"; private const string AltFieldName = "Altitude"; private const string NameFieldName = "Name"; private const string CreatorFieldName = "Creator"; private const string CreatorVersionFieldName = "CreatorVersion"; private const string TypeFieldName = "ActivityType"; private const string DateTimeFieldName = "ActivityDate"; private const string TrkPntTime = "Time"; private const string TrkPntHr = "HeartRate"; private const string TrkPntCad = "Cadence"; private GeometryType _geomType = GeometryType.Polyline; private List<PluginField> _pluginFields = null; /// <summary> /// Ctor using path that points to the gpx file /// </summary> /// <param name="gpxFilePath">path to gpx file. The geometry type is appended to the tablename like this: "|Point" or "|Line"</param> public ProGpxPluginTableTemplate(string gpxFilePath) { var theFilePath = gpxFilePath; var theGeomType = "|Line"; var parts = theFilePath.Split(new[] { '|' }); if (parts.Length > 1) { theFilePath = parts[0]; theGeomType = $@"|{parts[1]}"; } if (!theGeomType.EndsWith("Line", StringComparison.OrdinalIgnoreCase)) _geomType = GeometryType.Point; this._gpxFilePath = theFilePath; this._tableName = $@"{System.IO.Path.GetFileNameWithoutExtension (theFilePath)}{theGeomType}"; this._spatialReference = SpatialReferences.WGS84; CreateTable(this._tableName, this._gpxFilePath); } public override IReadOnlyList<PluginField> GetFields() { if (_pluginFields == null) { _pluginFields = new List<PluginField>(); foreach (var col in _dataTable.Columns.Cast<DataColumn>()) { // TODO: process all field types here ... this list is not complete var fieldType = FieldType.String; System.Diagnostics.Debug.WriteLine($@"{col.ColumnName} {col.DataType}"); if (col.ColumnName == ObjectIdFieldName || col.ColumnName == GeometryFieldName) { fieldType = col.ColumnName == GeometryFieldName ? FieldType.Geometry : FieldType.OID; } else { switch (col.DataType.Name) { case nameof(DateTime): fieldType = FieldType.Date; break; case nameof(Double): fieldType = FieldType.Double; break; case nameof(Int16): fieldType = FieldType.Integer; break; case nameof(Int32): fieldType = FieldType.Integer; break; case nameof(Guid): fieldType = FieldType.GUID; break; case nameof(String): fieldType = FieldType.String; break; case nameof(Single): fieldType = FieldType.Single; break; default: System.Diagnostics.Debug.WriteLine($@"Unsupported datatype: {col.DataType.Name} not mapped"); break; } } _pluginFields.Add(new PluginField() { Name = col.ColumnName, AliasName = col.ColumnName, FieldType = fieldType }); } } return _pluginFields; } public override string GetName() { return _tableName; } public override PluginCursorTemplate Search(QueryFilter queryFilter) => this.SearchInternal(queryFilter); public override PluginCursorTemplate Search(SpatialQueryFilter spatialQueryFilter) => this.SearchInternal(spatialQueryFilter); public override GeometryType GetShapeType() { return _geomType; } /// <summary> /// Get the extent for the dataset (if it has one) /// </summary> /// <remarks>Ideally, your plugin table should return an extent even if it is /// empty</remarks> /// <returns><see cref="Envelope"/></returns> public override Envelope GetExtent() { return _gisExtent; } #region Internal Functions private void CreateTable(string tableName, string filePath) { _dataTable.TableName = tableName; var oidCol = new DataColumn(ObjectIdFieldName, typeof(Int32)) { AutoIncrement = true, AutoIncrementSeed = 1 }; _dataTable.Columns.Add(oidCol); _dataTable.PrimaryKey = new DataColumn[] { oidCol }; _dataTable.Columns.Add(new DataColumn(GeometryFieldName, typeof(ArcGIS.Core.Geometry.Geometry))); _dataTable.Columns.Add(new DataColumn(LongFieldName, typeof(Double))); _dataTable.Columns.Add(new DataColumn(LatFieldName, typeof(Double))); _dataTable.Columns.Add(new DataColumn(AltFieldName, typeof(Double))); if (_geomType == GeometryType.Polyline) { _dataTable.Columns.Add(new DataColumn(TypeFieldName, typeof(string))); _dataTable.Columns.Add(new DataColumn(DateTimeFieldName, typeof(DateTime))); _dataTable.Columns.Add(new DataColumn(NameFieldName, typeof(string))); _dataTable.Columns.Add(new DataColumn(CreatorFieldName, typeof(string))); _dataTable.Columns.Add(new DataColumn(CreatorVersionFieldName, typeof(string))); } else { _dataTable.Columns.Add(new DataColumn(TrkPntTime, typeof(DateTime))); _dataTable.Columns.Add(new DataColumn(TrkPntHr, typeof(Int32))); _dataTable.Columns.Add(new DataColumn(TrkPntCad, typeof(Int32))); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); string xmlns = xmlDoc.DocumentElement.NamespaceURI; XmlNamespaceManager nmsp = new XmlNamespaceManager(xmlDoc.NameTable); nmsp.AddNamespace("x", xmlns); DateTime dateValue = DateTime.Now; XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes(@"//x:gpx/x:metadata/x:time", nmsp); if (nodeList.Count > 0) { var dateStr = nodeList[0].InnerText; try { dateValue = DateTime.Parse(dateStr); Console.WriteLine("'{0}' converted to {1}.", dateStr, dateValue); } catch (FormatException) { Console.WriteLine("Unable to convert '{0}'.", dateStr); } } var creator = string.Empty; var creatorVersion = string.Empty; nodeList = xmlDoc.DocumentElement.SelectNodes(@"//x:gpx", nmsp); if (nodeList.Count > 0) { var node = nodeList[0]; foreach (XmlAttribute attr in node.Attributes) { switch (attr.Name) { case "creator": creator = attr.Value; break; case "version": creatorVersion = attr.Value; break; } } } var activityName = string.Empty; var activityType = string.Empty; nodeList = xmlDoc.DocumentElement.SelectNodes("/x:gpx/x:trk/x:name", nmsp); if (nodeList.Count > 0) activityName = nodeList[0].InnerText; nodeList = xmlDoc.DocumentElement.SelectNodes("/x:gpx/x:trk/x:type", nmsp); if (nodeList.Count > 0) activityType = nodeList[0].InnerText; var newRow = _dataTable.NewRow(); var objectid = 1; // let's make a 3d line shape List<Coordinate3D> lst3DCoords = new List<Coordinate3D>(); double lng = 0.0, lat = 0.0, ele = 0.0; Int32 cad = -1, hr = -1; DateTime? trkTime = null; nodeList = xmlDoc.DocumentElement.SelectNodes("/x:gpx/x:trk/x:trkseg/x:trkpt", nmsp); foreach (XmlNode node in nodeList) { lng = double.Parse(node.Attributes["lon"].Value); lat = double.Parse(node.Attributes["lat"].Value); foreach (XmlNode childNode in node.ChildNodes) { switch (childNode.Name) { case "ele": ele = double.Parse(childNode.InnerText); break; case "time": trkTime = DateTime.Parse(childNode.InnerText); break; case "extensions": if (childNode.HasChildNodes) { foreach (XmlNode extNode in childNode.ChildNodes[0].ChildNodes) { switch (extNode.LocalName) { case "hr": hr = Int32.Parse(extNode.InnerText); break; case "cad": cad = Int32.Parse(extNode.InnerText); break; } } } break; } } if (_geomType == GeometryType.Polyline) { lst3DCoords.Add(new Coordinate3D(lng, lat, ele)); } else { // for the point variety we only have many rows newRow[ObjectIdFieldName] = objectid++; var mp = MapPointBuilder.CreateMapPoint(new Coordinate3D(lng, lat, ele), _spatialReference); newRow[GeometryFieldName] = mp; newRow[LongFieldName] = lng; newRow[LatFieldName] = lat; newRow[AltFieldName] = ele; if (trkTime.HasValue) newRow[TrkPntTime] = trkTime.Value; newRow[TrkPntHr] = hr; newRow[TrkPntCad] = cad; _dataTable.Rows.Add(newRow); _gisExtent = _gisExtent == null ? mp.Extent : _gisExtent.Union(mp.Extent); newRow = _dataTable.NewRow(); } } if (_geomType == GeometryType.Polyline) { // for the line variety we only have one row newRow[ObjectIdFieldName] = objectid; var pl = PolylineBuilder.CreatePolyline(lst3DCoords, _spatialReference); newRow[GeometryFieldName] = pl; newRow[LongFieldName] = lng; newRow[LatFieldName] = lat; newRow[AltFieldName] = ele; newRow[TypeFieldName] = activityType; newRow[DateTimeFieldName] = dateValue; newRow[NameFieldName] = activityName; newRow[CreatorFieldName] = creator; newRow[CreatorVersionFieldName] = creatorVersion; _dataTable.Rows.Add(newRow); _gisExtent = _gisExtent == null ? pl.Extent : _gisExtent.Union(pl.Extent); } } private PluginCursorTemplate SearchInternal(QueryFilter qf) { var oids = this.ExecuteQuery(qf); var columns = this.GetQuerySubFields(qf); return new ProGpxPluginCursorTemplate(this, oids, columns, qf.OutputSpatialReference); } /// <summary> /// Implement querying with a query filter /// </summary> /// <param name="qf"></param> /// <returns></returns> private List<int> ExecuteQuery(QueryFilter qf) { List<int> result = new List<int>(); SpatialQueryFilter sqf = null; if (qf is SpatialQueryFilter) { sqf = qf as SpatialQueryFilter; } var whereClause = string.Empty; if (!string.IsNullOrEmpty(qf.WhereClause)) { whereClause = qf.WhereClause; } else { if (qf.ObjectIDs.Count() > 0) { whereClause = $@"{ObjectIdFieldName} in ({string.Join(",", qf.ObjectIDs)})"; } } var subFields = string.IsNullOrEmpty(qf.SubFields) ? "*" : qf.SubFields; var selectRows = _dataTable.Select(whereClause, qf.PostfixClause); int recCount = selectRows.Length; if (sqf == null) { result = selectRows.AsEnumerable().Select(row => (int)row[ObjectIdFieldName]).ToList(); } else { result = selectRows.AsEnumerable().Where(Row => CheckSpatialQuery(sqf, Row[GeometryFieldName] as Geometry)).Select(row => (int)row[ObjectIdFieldName]).ToList(); } return result; } private bool CheckSpatialQuery(SpatialQueryFilter sqf, Geometry geom) { if (geom == null) { return false; } return HasRelationship(GeometryEngine.Instance, sqf.FilterGeometry, geom, sqf.SpatialRelationship); } internal static bool HasRelationship(IGeometryEngine engine, Geometry geom1, Geometry geom2, SpatialRelationship relationship) { switch (relationship) { case SpatialRelationship.Intersects: return engine.Intersects(geom1, geom2); case SpatialRelationship.IndexIntersects: return engine.Intersects(geom1, geom2); case SpatialRelationship.EnvelopeIntersects: return engine.Intersects(geom1.Extent, geom2.Extent); case SpatialRelationship.Contains: return engine.Contains(geom1, geom2); case SpatialRelationship.Crosses: return engine.Crosses(geom1, geom2); case SpatialRelationship.Overlaps: return engine.Overlaps(geom1, geom2); case SpatialRelationship.Touches: return engine.Touches(geom1, geom2); case SpatialRelationship.Within: return engine.Within(geom1, geom2); } return false;//unknown relationship } private List<string> GetQuerySubFields(QueryFilter qf) { //Honor Subfields in Query Filter string columns = qf.SubFields ?? "*"; List<string> subFields; if (columns == "*") { subFields = this.GetFields().Select(col => col.Name.ToUpper()).ToList(); } else { var names = columns.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); subFields = names.Select(n => n.ToUpper()).ToList(); } return subFields; } #endregion Internal Functions #region IPluginRowProvider /// <summary> /// Find a given row (using Object ID) and retrieve attributes using columnFilter and output spatial reference /// </summary> /// <param name="oid">Search for this record using this Object ID</param> /// <param name="columnFilter">List of Column Names to be returned</param> /// <param name="srout">project spatial data using this output spatial reference</param> /// <returns>PlugInRow</returns> public PluginRow FindRow(int oid, IEnumerable<string> columnFilter, SpatialReference srout) { Geometry shape = null; List<object> values = new List<object>(); var row = _dataTable.Rows.Find(oid); //The order of the columns in the returned rows ~must~ match //GetFields. If a column is filtered out, an empty placeholder must //still be provided even though the actual value is skipped var columnNames = this.GetFields().Select(col => col.Name.ToUpper()).ToList(); foreach (var colName in columnNames) { if (columnFilter.Contains(colName)) { //special handling for shape if (colName == GeometryFieldName) { shape = row[GeometryFieldName] as Geometry; if (srout != null) { if (!srout.Equals(_spatialReference)) shape = GeometryEngine.Instance.Project(shape, srout); } values.Add(shape); } else { values.Add(row[colName]); } } else { values.Add(System.DBNull.Value);//place holder } } return new PluginRow() { Values = values }; } #endregion IPluginRowProvider #region IDisposable Support private bool disposedValue = false; // To detect redundant calls /// <summary> /// Clean up resources /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (_dataTable == null) return; if (disposing) { _dataTable?.Clear(); _gisExtent = null; } disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~ProPluginTableTemplate() // { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } /// <summary> /// This code added to correctly implement the disposable pattern. /// </summary> public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace PetStore.Server.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt321() { var test = new SimpleUnaryOpTest__ShiftRightLogicalInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalInt321 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector256<Int32> _clsVar; private Vector256<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static SimpleUnaryOpTest__ShiftRightLogicalInt321() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogicalInt321() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogicalInt321(); var result = Avx2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if ((int)(firstOp[0] >> 1) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(firstOp[i] >> 1) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int32>(Vector256<Int32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; /** Tablet is the input to the room. It's a 4x4 grid. */ [RequireComponent(typeof(GameTabletRenderer))] public class GameTabletMover : MonoBehaviour, ITablet { public Color successColor; public Color errorColor; public tk2dSprite tabletBaseSprite; public int startGridVertexX; public int startGridVertexY; [HideInInspector] public Mover.Direction MovementDirection = Mover.Direction.UP; public ITabletCell TopLeft { get { return GetComponent<GameTabletRenderer>().TopLeft; } set { GetComponent<GameTabletRenderer>().TopLeft.SetState(value); } } public ITabletCell TopRight { get { return GetComponent<GameTabletRenderer>().TopRight; } set { GetComponent<GameTabletRenderer>().TopRight.SetState(value); } } public ITabletCell BottomLeft { get { return GetComponent<GameTabletRenderer>().BottomLeft; } set { GetComponent<GameTabletRenderer>().BottomLeft.SetState(value); } } public ITabletCell BottomRight { get { return GetComponent<GameTabletRenderer>().BottomRight; } set { GetComponent<GameTabletRenderer>().BottomRight.SetState(value); } } private bool moveStopped = false; public int GridCellX { get { return GridVertexX - 1; } } public int GridCellY { get { return GridVertexY - 1; } } public int GridVertexX { get; private set; } public int GridVertexY { get; private set; } // Use this for initialization void Start() { Reset(); moveStopped = false; TickController.MoveTickEvent += TriggerMove; TickController.ResetTabletsEvent += Reset; LevelStateManager.InputChanged += OnGlobalInputChanged; LevelStateManager.LevelCompletedEvent += SetLevelCompletedColor; } void OnDestroy() { TickController.MoveTickEvent -= TriggerMove; TickController.ResetTabletsEvent -= Reset; LevelStateManager.InputChanged -= OnGlobalInputChanged; LevelStateManager.LevelCompletedEvent -= SetLevelCompletedColor; } private void OnGlobalInputChanged(ITablet state) { this.SetState(state); } private void SetLevelCompletedColor(bool success) { tabletBaseSprite.color = success ? successColor : errorColor; } private void Reset() { tabletBaseSprite.color = Color.white; MovementDirection = Mover.Direction.UP; GridVertexX = startGridVertexX; GridVertexY = startGridVertexY; transform.position = MachineGrid.Obj.getVertexWorldPosition(GridVertexX, GridVertexY); transform.rotation = Quaternion.Euler(0, 0, 0); this.SetState(LevelStateManager.InputTablet); InterruptMove(); } private void InterruptMove() { moveStopped = true; } void TriggerMove(float lengthOfTickSeconds) { Vector2 direction = MovementDirection.ToUnitVector(); // Check for pins if (NoFrontPins(GridVertexX, GridVertexY, direction)) { Vector2 oldPosition = MachineGrid.Obj.getVertexWorldPosition(GridVertexX, GridVertexY); // Do the move in the grid GridVertexX += Mathf.RoundToInt(direction.x); GridVertexY += Mathf.RoundToInt(direction.y); // Animate the move direction.Scale(FindObjectOfType<MachineGrid>().GetCellSizeWorldSpace()); StartCoroutine(DoMove(oldPosition, direction, lengthOfTickSeconds)); } else { // Do either a rotation or a bounceback List<Vector2> offsetBlacklist = new List<Vector2>(); offsetBlacklist.Add(new Vector2(0, 0)); offsetBlacklist.Add(new Vector2(0, 1)); offsetBlacklist.Add(new Vector2(1, 0)); offsetBlacklist.Add(new Vector2(1, 1)); offsetBlacklist.Add(new Vector2(2, 0)); offsetBlacklist.Add(new Vector2(2, 1)); if (PinAtPosition(GridVertexX, GridVertexY, direction, 1, -1) && offsetBlacklist.TrueForAll((vector) => !PinAtPosition(GridVertexX, GridVertexY, direction, Mathf.RoundToInt(vector.x), Mathf.RoundToInt(vector.y)))) { // Start a rotation anticlockwise Debug.Log("Anticlockwise rotation starting."); StartCoroutine(DoRotation(direction, lengthOfTickSeconds, new Vector2(-1, 1), 90)); GridVertexX += 2 * Mathf.RoundToInt(direction.x); GridVertexY += 2 * Mathf.RoundToInt(direction.y); GetComponent<GameTabletRenderer>().RotateReferencesCounterclockwise(); } else if (PinAtPosition(GridVertexX, GridVertexY, direction, 1, 1) && offsetBlacklist.TrueForAll((vector) => !PinAtPosition(GridVertexX, GridVertexY, direction, Mathf.RoundToInt(vector.x), Mathf.RoundToInt(-vector.y)))) { // Start a rotation clockwise Debug.Log("Clockwise rotation starting."); StartCoroutine(DoRotation(direction, lengthOfTickSeconds, new Vector2(1, 1), -90)); GridVertexX += 2 * Mathf.RoundToInt(direction.x); GridVertexY += 2 * Mathf.RoundToInt(direction.y); GetComponent<GameTabletRenderer>().RotateReferencesCounterclockwise(); GetComponent<GameTabletRenderer>().RotateReferencesCounterclockwise(); GetComponent<GameTabletRenderer>().RotateReferencesCounterclockwise(); } else { // There's a pin in the way, but still at least one pin in front of us; bounce back. // TODO(taylor): animate a partial swing in some cases. Debug.Log("Bouncing back the way we came."); MovementDirection = MovementDirection.Clockwise().Clockwise(); TriggerMove(lengthOfTickSeconds); } } } private IEnumerator DoRotation(Vector2 direction, float lengthOfTickSeconds, Vector2 offset, float angle) { moveStopped = false; Vector2 gridPosition = new Vector2(GridVertexX, GridVertexY); Vector2 newGridPosition = gridPosition + (Vector2)(Quaternion.AngleAxis(AngleFromTo(direction, Vector2.up), Vector3.forward) * offset); Vector2 origin = MachineGrid.Obj.getVertexWorldPosition( Mathf.RoundToInt(newGridPosition.x), Mathf.RoundToInt(newGridPosition.y)); float startTime = Time.time; Vector2 originalPosition = transform.position; Quaternion originalRotation = transform.rotation; while (Time.time < startTime + lengthOfTickSeconds) { yield return null; if (moveStopped) { moveStopped = false; yield break; } transform.position = originalPosition; transform.rotation = originalRotation; transform.RotateAround(origin, Vector3.forward, (Time.time - startTime) / lengthOfTickSeconds * angle); } // set position and rotation to correct for drift Vector2 newPosition = gridPosition + direction * 2; transform.position = MachineGrid.Obj.getVertexWorldPosition( Mathf.RoundToInt(newPosition.x), Mathf.RoundToInt(newPosition.y)); transform.rotation = originalRotation * Quaternion.AngleAxis(angle, Vector3.forward); yield break; } private bool NoFrontPins(int gridVertexX, int gridVertexY, Vector2 direction) { return !PinAtPosition(gridVertexX, gridVertexY, direction, 1, -1) && !PinAtPosition(gridVertexX, gridVertexY, direction, 1, 0) && !PinAtPosition(gridVertexX, gridVertexY, direction, 1, 1); } private bool PinAtPosition(int gridVertexX, int gridVertexY, Vector2 direction, int parallelOffset, int perpendicularOffset) { Vector2 gridPosition = new Vector2(gridVertexX, gridVertexY); Vector2 offset = new Vector2(perpendicularOffset, parallelOffset); Vector2 newGridPosition = gridPosition + (Vector2) (Quaternion.AngleAxis(AngleFromTo(direction, Vector2.up), Vector3.forward) * offset); // out of bounds check if (newGridPosition.x < 0 || newGridPosition.x > MachineGrid.Obj.GridVertices.GetLength(0) - 1 || newGridPosition.y < 0 || newGridPosition.y > MachineGrid.Obj.GridVertices.GetLength(1) - 1) { return false; } VertexMachine machineAtPosition = MachineGrid.Obj.GridVertices[ Mathf.RoundToInt(newGridPosition.x), Mathf.RoundToInt(newGridPosition.y)] .GetComponent<GridVertex>().VertexMachine; if (machineAtPosition == null) { return false; } return machineAtPosition.GetComponent<PinMachine>() != null; } private float AngleFromTo(Vector2 from, Vector2 to) { float angle = Vector2.Angle(from, to); if (Vector3.Cross(from, to).z > 0) angle = 360 - angle; return angle; } IEnumerator DoMove(Vector2 from, Vector2 delta, float lengthOfTickSeconds) { moveStopped = false; float startTime = Time.time; while (Time.time < startTime + lengthOfTickSeconds) { transform.position = Vector2.Lerp(from, from + delta, (Time.time - startTime) / lengthOfTickSeconds); yield return null; if (moveStopped) { moveStopped = false; yield break; } } transform.position = from + delta; } /** Gets the piece that is on position x,y of the room floor. */ public GameTabletCell GetTabletPieceByFactoryPosition(int x, int y) { int tabletX = x - GridCellX; int tabletY = y - GridCellY; if (tabletX == 0 && tabletY == 0) { return GetComponent<GameTabletRenderer>().bottomLeft; } else if (tabletX == 0 && tabletY == 1) { return GetComponent<GameTabletRenderer>().topLeft; } else if (tabletX == 1 && tabletY == 0) { return GetComponent<GameTabletRenderer>().bottomRight; } else if (tabletX == 1 && tabletY == 1) { return GetComponent<GameTabletRenderer>().topRight; } else { return null; } } public GameTabletCell[] GetAllCells() { return GetComponent<GameTabletRenderer>().GetAllCells(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExpressRouteCircuitPeeringsOperations operations. /// </summary> internal partial class ExpressRouteCircuitPeeringsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitPeeringsOperations { /// <summary> /// Initializes a new instance of the ExpressRouteCircuitPeeringsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ExpressRouteCircuitPeeringsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified peering from the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified authorization from the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (peeringName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("peeringName", peeringName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a peering in the specified express route circuits. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create or update express route circuit peering /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ExpressRouteCircuitPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all peerings in a specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified peering from the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (peeringName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("peeringName", peeringName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a peering in the specified express route circuits. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create or update express route circuit peering /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (peeringName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringName"); } if (peeringParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("peeringName", peeringName); tracingParameters.Add("peeringParameters", peeringParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(peeringParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(peeringParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all peerings in a specified express route circuit. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; namespace Microsoft.VisualStudioTools.Project { internal class FileNode : HierarchyNode, IDiskBasedNode { private bool _isLinkFile; private uint _docCookie; private static readonly string[] _defaultOpensWithDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx", ".xsd", ".resource", ".xaml" }; private static readonly string[] _supportsDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx" }; private static readonly string[] _supportsDesignViewSubTypes = new[] { ProjectFileAttributeValue.Code, ProjectFileAttributeValue.Form, ProjectFileAttributeValue.UserControl, ProjectFileAttributeValue.Component, ProjectFileAttributeValue.Designer }; private string _caption; #region static fields #if !DEV14_OR_LATER private static Dictionary<string, int> extensionIcons; #endif #endregion #region overriden Properties public override bool DefaultOpensWithDesignView { get { // ASPX\ASCX files support design view but should be opened by default with // LOGVIEWID_Primary - this is because they support design and html view which // is a tools option setting for them. If we force designview this option // gets bypassed. We do a similar thing for asax/asmx/xsd. By doing so, we don't force // the designer to be invoked when double-clicking on the - it will now go through the // shell's standard open mechanism. string extension = Path.GetExtension(Url); return !_defaultOpensWithDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) && !IsCodeBehindFile && SupportsDesignView; } } public override bool SupportsDesignView { get { if (ItemNode != null && !ItemNode.IsExcluded) { string extension = Path.GetExtension(Url); if (_supportsDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) || IsCodeBehindFile) { return true; } else { var subType = ItemNode.GetMetadata("SubType"); if (subType != null && _supportsDesignViewExtensions.Contains(subType, StringComparer.OrdinalIgnoreCase)) { return true; } } } return false; } } public override bool IsNonMemberItem { get { return ItemNode is AllFilesProjectElement; } } /// <summary> /// overwrites of the generic hierarchyitem. /// </summary> [System.ComponentModel.BrowsableAttribute(false)] public override string Caption { get { return _caption; } } private void UpdateCaption() { // Use LinkedIntoProjectAt property if available string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt); if (caption == null || caption.Length == 0) { // Otherwise use filename caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include); caption = Path.GetFileName(caption); } _caption = caption; } public override string GetEditLabel() { if (IsLinkFile) { // cannot rename link files return null; } return Caption; } #if !DEV14_OR_LATER public override int ImageIndex { get { // Check if the file is there. if (!this.CanShowDefaultIcon()) { return (int)ProjectNode.ImageName.MissingFile; } //Check for known extensions int imageIndex; string extension = Path.GetExtension(this.FileName); if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex))) { // Missing or unknown extension; let the base class handle this case. return base.ImageIndex; } // The file type is known and there is an image for it in the image list. return imageIndex; } } #endif public uint DocCookie { get { return this._docCookie; } set { this._docCookie = value; } } public override bool IsLinkFile { get { return _isLinkFile; } } internal void SetIsLinkFile(bool value) { _isLinkFile = value; } protected override VSOVERLAYICON OverlayIconIndex { get { if (IsLinkFile) { return VSOVERLAYICON.OVERLAYICON_SHORTCUT; } return VSOVERLAYICON.OVERLAYICON_NONE; } } public override Guid ItemTypeGuid { get { return VSConstants.GUID_ItemType_PhysicalFile; } } public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_ITEMNODE; } } public override string Url { get { return ItemNode.Url; } } public override string Name => CommonUtils.GetFileOrDirectoryName(ItemNode.Url); #endregion #region ctor #if !DEV14_OR_LATER [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static FileNode() { // Build the dictionary with the mapping between some well known extensions // and the index of the icons inside the standard image list. extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm); extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass); extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService); extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl); extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage); extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig); extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage); extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage); extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet); extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet); extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile); extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile); extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile); extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile); extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources); extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources); extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap); extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon); extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image); extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image); extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image); extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap); extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio); extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio); extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio); extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB); extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR); extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile); extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema); extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile); extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX); extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK); } #endif /// <summary> /// Constructor for the FileNode /// </summary> /// <param name="root">Root of the hierarchy</param> /// <param name="e">Associated project element</param> public FileNode(ProjectNode root, ProjectElement element) : base(root, element) { UpdateCaption(); } #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { if (IsLinkFile) { return new LinkFileNodeProperties(this); } else if (IsNonMemberItem) { return new ExcludedFileNodeProperties(this); } return new IncludedFileNodeProperties(this); } /// <summary> /// Get an instance of the automation object for a FileNode /// </summary> /// <returns>An instance of the Automation.OAFileNode if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } /// <summary> /// Renames a file node. /// </summary> /// <param name="label">The new name.</param> /// <returns>An errorcode for failure or S_OK.</returns> /// <exception cref="InvalidOperationException" if the file cannot be validated> /// <devremark> /// We are going to throw instead of showing messageboxes, since this method is called from various places where a dialog box does not make sense. /// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox. /// Also the automation methods are also calling SetEditLabel /// </devremark> public override int SetEditLabel(string label) { // IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is // expected that we can be called with a label which is the same as the current // label and this should not be considered a NO-OP. if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } // Validate the filename. if (String.IsNullOrEmpty(label)) { throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label)); } else if (label.Length > NativeMethods.MAX_PATH) { throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label)); } else if (Utilities.IsFileNameInvalid(label)) { throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label)); } for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling) { // TODO: Distinguish between real Urls and fake ones (eg. "References") if (n != this && String.Equals(n.Caption, label, StringComparison.OrdinalIgnoreCase)) { if (File.Exists(n.Url)) { //A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. //If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu. throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label)); } else { // Check if the file is open in the editor, if so, we need to close it, and if it's dirty // let the user save it. DocumentManager manager = n.GetDocumentManager(); if (manager != null) { int close = manager.Close(__FRAMECLOSE.FRAMECLOSE_PromptSave); if (close == VSConstants.E_ABORT || close == VSConstants.S_FALSE) { // User cancelled operation in message box. throw new InvalidOperationException(SR.GetString(SR.FileOpenDoesNotExist, label)); } } if (File.Exists(n.Url)) { // The file was dirty and the user saved it. throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label)); } // The file is no longer open in the editor and isn't on disk. We can try removing it now. if (!n.Remove(false)) { throw new InvalidOperationException(SR.GetString(SR.UnableToRemoveFile, label)); } } } } string fileName = Path.GetFileNameWithoutExtension(label); // Verify that the file extension is unchanged string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include)); if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site) && !String.Equals(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase)) { // Prompt to confirm that they really want to change the extension of the file string message = SR.GetString(SR.ConfirmExtensionChange, label); IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell)) { // The user cancelled the confirmation for changing the extension. // Return S_OK in order not to show any extra dialog box return VSConstants.S_OK; } } // Build the relative path by looking at folder names above us as one scenarios // where we get called is when a folder above us gets renamed (in which case our path is invalid) strRelPath = Path.Combine(GetRelativePathToParent(Parent), Name); return SetEditLabel(label, strRelPath); } private static string GetFullPathToParent(HierarchyNode parent) { while (parent is FileNode) { if (parent == parent.Parent) { break; } parent = parent.Parent; } if (parent != null) { try { return parent.FullPathToChildren; } catch (InvalidOperationException) { return parent.Url; } } throw new InvalidOperationException("Node is not parented correctly"); } private static string GetRelativePathToParent(HierarchyNode parent) { var parts = new List<string>(); while (parent is FileNode) { if (parent == parent.Parent) { break; } parent = parent.Parent; } while (parent is FolderNode) { parts.Add(parent.Name); if (parent == parent.Parent) { break; } parent = parent.Parent; } parts.Reverse(); return Path.Combine(parts.ToArray()); } public override void Reparent(HierarchyNode newParent) { var oldUrl = Url; var newUrl = CommonUtils.GetAbsoluteFilePath( GetFullPathToParent(newParent), CommonUtils.GetFileOrDirectoryName(oldUrl) ); RenameDocument(oldUrl, newUrl); base.Reparent(newParent); } public override string GetMkDocument() { Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node"); Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path"); return this.Url; } /// <summary> /// Delete the item corresponding to the specified path from storage. /// </summary> /// <param name="path"></param> protected internal override void DeleteFromStorage(string path) { if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly. File.Delete(path); } } /// <summary> /// Rename the underlying document based on the change the user just made to the edit label. /// </summary> protected internal override int SetEditLabel(string label, string relativePath) { int returnValue = VSConstants.S_OK; uint oldId = this.ID; string strSavePath = Path.GetDirectoryName(relativePath); strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath); string newName = Path.Combine(strSavePath, label); if (String.Equals(newName, this.Url, StringComparison.Ordinal)) { // This is really a no-op (including changing case), so there is nothing to do return VSConstants.S_FALSE; } else if (String.Equals(newName, this.Url, StringComparison.OrdinalIgnoreCase)) { // This is a change of file casing only. } else { // If the renamed file already exists then quit (unless it is the result of the parent having done the move). if (IsFileOnDisk(newName) && (IsFileOnDisk(this.Url) || !String.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException(SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, label)); } else if (newName.Length > NativeMethods.MAX_PATH) { throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label)); } } string oldName = this.Url; // must update the caption prior to calling RenameDocument, since it may // cause queries of that property (such as from open editors). string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include); try { if (!RenameDocument(oldName, newName)) { this.ItemNode.Rename(oldrelPath); } if (this is DependentFileNode) { ProjectMgr.OnInvalidateItems(this.Parent); } } catch (Exception e) { // Just re-throw the exception so we don't get duplicate message boxes. Trace.WriteLine("Exception : " + e.Message); this.RecoverFromRenameFailure(newName, oldrelPath); returnValue = Marshal.GetHRForException(e); throw; } // Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale // hierarchy item id. if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE; } return returnValue; } /// <summary> /// Returns a specific Document manager to handle files /// </summary> /// <returns>Document manager object</returns> protected internal override DocumentManager GetDocumentManager() { return new FileDocumentManager(this); } public override int QueryService(ref Guid guidService, out object result) { if (guidService == typeof(EnvDTE.Project).GUID) { result = ProjectMgr.GetAutomationObject(); return VSConstants.S_OK; } else if (guidService == typeof(EnvDTE.ProjectItem).GUID) { result = GetAutomationObject(); return VSConstants.S_OK; } return base.QueryService(ref guidService, out result); } /// <summary> /// Called by the drag&drop implementation to ask the node /// which is being dragged/droped over which nodes should /// process the operation. /// This allows for dragging to a node that cannot contain /// items to let its parent accept the drop, while a reference /// node delegate to the project and a folder/project node to itself. /// </summary> /// <returns></returns> protected internal override HierarchyNode GetDragTargetHandlerNode() { Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode"); HierarchyNode handlerNode = this; while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode)) handlerNode = handlerNode.Parent; if (handlerNode == null) handlerNode = this.ProjectMgr; return handlerNode; } internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } // Exec on special filenode commands if (cmdGroup == VsMenus.guidStandardCommandSet97) { IVsWindowFrame windowFrame = null; switch ((VsCommands)cmd) { case VsCommands.ViewCode: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show); case VsCommands.ViewForm: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show); case VsCommands.Open: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show); case VsCommands.OpenWith: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.Copy: case VsCommands.Paste: case VsCommands.Cut: case VsCommands.Rename: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.ViewCode: //case VsCommands.Delete: goto case VsCommands.OpenWith; case VsCommands.Open: case VsCommands.OpenWith: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } protected override void DoDefaultAction() { FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager; Utilities.CheckNotNull(manager, "Could not get the FileDocumentManager"); manager.Open(false, false, WindowFrameShowAction.Show); } /// <summary> /// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data. /// </summary> /// <param name="docData">A pointer to the document in the rdt</param> /// <param name="newFilePath">The new file path to the document</param> /// <returns></returns> internal override int AfterSaveItemAs(IntPtr docData, string newFilePath) { Utilities.ArgumentNotNullOrEmpty("newFilePath", newFilePath); int returnCode = VSConstants.S_OK; newFilePath = newFilePath.Trim(); //Identify if Path or FileName are the same for old and new file string newDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(newFilePath)); string oldDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.GetMkDocument())); bool isSamePath = CommonUtils.IsSameDirectory(newDirectoryName, oldDirectoryName); bool isSameFile = CommonUtils.IsSamePath(newFilePath, this.Url); //Get target container HierarchyNode targetContainer = null; bool isLink = false; if (isSamePath) { targetContainer = this.Parent; } else if (!CommonUtils.IsSubpathOf(this.ProjectMgr.ProjectHome, newDirectoryName)) { targetContainer = this.Parent; isLink = true; } else if (CommonUtils.IsSameDirectory(this.ProjectMgr.ProjectHome, newDirectoryName)) { //the projectnode is the target container targetContainer = this.ProjectMgr; } else { //search for the target container among existing child nodes targetContainer = this.ProjectMgr.FindNodeByFullPath(newDirectoryName); if (targetContainer != null && (targetContainer is FileNode)) { // We already have a file node with this name in the hierarchy. throw new InvalidOperationException(SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, Path.GetFileName(newFilePath))); } } if (targetContainer == null) { // Add a chain of subdirectories to the project. string relativeUri = CommonUtils.GetRelativeDirectoryPath(this.ProjectMgr.ProjectHome, newDirectoryName); targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri); } Utilities.CheckNotNull(targetContainer, "Could not find a target container"); //Suspend file changes while we rename the document string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include); string oldName = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, oldrelPath); SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName); sfc.Suspend(); try { // Rename the node. DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData); // Check if the file name was actually changed. // In same cases (e.g. if the item is a file and the user has changed its encoding) this function // is called even if there is no real rename. if (!isSameFile || (this.Parent.ID != targetContainer.ID)) { // The path of the file is changed or its parent is changed; in both cases we have // to rename the item. if (isLink != IsLinkFile) { if (isLink) { var newPath = CommonUtils.GetRelativeFilePath( this.ProjectMgr.ProjectHome, Path.Combine(Path.GetDirectoryName(Url), Path.GetFileName(newFilePath)) ); ItemNode.SetMetadata(ProjectFileConstants.Link, newPath); } else { ItemNode.SetMetadata(ProjectFileConstants.Link, null); } SetIsLinkFile(isLink); } RenameFileNode(oldName, newFilePath, targetContainer); ProjectMgr.OnInvalidateItems(this.Parent); } } catch (Exception e) { Trace.WriteLine("Exception : " + e.Message); this.RecoverFromRenameFailure(newFilePath, oldrelPath); throw; } finally { sfc.Resume(); } return returnCode; } /// <summary> /// Determines if this is node a valid node for painting the default file icon. /// </summary> /// <returns></returns> protected override bool CanShowDefaultIcon() { string moniker = this.GetMkDocument(); return File.Exists(moniker); } #endregion #region virtual methods public override object GetProperty(int propId) { switch ((__VSHPROPID)propId) { case __VSHPROPID.VSHPROPID_ItemDocCookie: if (this.DocCookie != 0) return (IntPtr)this.DocCookie; //cast to IntPtr as some callers expect VT_INT break; } return base.GetProperty(propId); } public virtual string FileName { get { return this.Caption; } set { this.SetEditLabel(value); } } /// <summary> /// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented. /// </summary> /// <param name="showMessage">true if user should be presented for UI in case the file is not present</param> /// <returns>true if file is on disk</returns> internal protected virtual bool IsFileOnDisk(bool showMessage) { bool fileExist = IsFileOnDisk(this.Url); if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) { string message = SR.GetString(SR.ItemDoesNotExistInProjectDirectory, Caption); string title = string.Empty; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; Utilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton); } return fileExist; } /// <summary> /// Determine if the file represented by "path" exist in storage. /// Override this method if your files are not persisted on disk. /// </summary> /// <param name="path">Url representing the file</param> /// <returns>True if the file exist</returns> internal protected virtual bool IsFileOnDisk(string path) { return File.Exists(path); } /// <summary> /// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy. /// </summary> /// <param name="oldFileName">The old file name.</param> /// <param name="newFileName">The new file name</param> /// <param name="newParentId">The new parent id of the item.</param> /// <returns>The newly added FileNode.</returns> /// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks> internal FileNode RenameFileNode(string oldFileName, string newFileName, HierarchyNode newParent) { if (CommonUtils.IsSamePath(oldFileName, newFileName)) { // We do not want to rename the same file return null; } //If we are included in the project and our parent isn't then //we need to bring our parent into the project if (!this.IsNonMemberItem && newParent.IsNonMemberItem) { ErrorHandler.ThrowOnFailure(newParent.IncludeInProjectWithRefresh(false)); } // Retrieve child nodes to add later. List<HierarchyNode> childNodes = this.GetChildNodes(); FileNode renamedNode; using (this.ProjectMgr.ExtensibilityEventsDispatcher.Suspend()) { // Remove this from its parent. ProjectMgr.OnItemDeleted(this); this.Parent.RemoveChild(this); // Update name in MSBuild this.ItemNode.Rename(CommonUtils.GetRelativeFilePath(ProjectMgr.ProjectHome, newFileName)); // Request a new file node be made. This is used to replace the old file node. This way custom // derived FileNode types will be used and correctly associated on rename. This is useful for things // like .txt -> .js where the file would now be able to be a startup project/file. renamedNode = this.ProjectMgr.CreateFileNode(this.ItemNode); renamedNode.ItemNode.RefreshProperties(); renamedNode.IsVisible = this.IsVisible; renamedNode.UpdateCaption(); newParent.AddChild(renamedNode); renamedNode.Parent = newParent; } UpdateCaption(); ProjectMgr.ReDrawNode(renamedNode, UIHierarchyElement.Caption); renamedNode.ProjectMgr.ExtensibilityEventsDispatcher.FireItemRenamed(this, oldFileName); //Update the new document in the RDT. DocumentManager.RenameDocument(renamedNode.ProjectMgr.Site, oldFileName, newFileName, renamedNode.ID); //Select the new node in the hierarchy renamedNode.ExpandItem(EXPANDFLAGS.EXPF_SelectItem); // Add children to new node and rename them appropriately. childNodes.ForEach(x => renamedNode.AddChild(x)); RenameChildNodes(renamedNode); return renamedNode; } /// <summary> /// Rename all childnodes /// </summary> /// <param name="newFileNode">The newly added Parent node.</param> protected virtual void RenameChildNodes(FileNode parentNode) { foreach (var childNode in GetChildNodes().OfType<FileNode>()) { string newfilename; if (childNode.HasParentNodeNameRelation) { string relationalName = childNode.Parent.GetRelationalName(); string extension = childNode.GetRelationNameExtension(); newfilename = relationalName + extension; newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename); } else { newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption); } childNode.RenameDocument(childNode.GetMkDocument(), newfilename); //We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed //which happens if the is no name relation between the parent and the child string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon); if (!string.IsNullOrEmpty(dependentOf)) { childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include)); } } } /// <summary> /// Tries recovering from a rename failure. /// </summary> /// <param name="fileThatFailed"> The file that failed to be renamed.</param> /// <param name="originalFileName">The original filenamee</param> protected virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName) { if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName)) { this.ItemNode.Rename(originalFileName); } } internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { return this.ProjectMgr.CanProjectDeleteItems; } return false; } /// <summary> /// This should be overriden for node that are not saved on disk /// </summary> /// <param name="oldName">Previous name in storage</param> /// <param name="newName">New name in storage</param> internal virtual void RenameInStorage(string oldName, string newName) { // Make a few attempts over a short time period for (int retries = 4; retries > 0; --retries) { try { File.Move(oldName, newName); return; } catch (IOException) { System.Threading.Thread.Sleep(50); } } // Final attempt has no handling so exception propagates File.Move(oldName, newName); } /// <summary> /// This method should be overridden to provide the list of special files and associated flags for source control. /// </summary> /// <param name="sccFile">One of the file associated to the node.</param> /// <param name="files">The list of files to be placed under source control.</param> /// <param name="flags">The flags that are associated to the files.</param> protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) { if (this.ExcludeNodeFromScc) { return; } Utilities.ArgumentNotNull("files", files); Utilities.ArgumentNotNull("flags", flags); foreach (HierarchyNode node in this.GetChildNodes()) { files.Add(node.GetMkDocument()); } } #endregion #region Helper methods /// <summary> /// Gets called to rename the eventually running document this hierarchyitem points to /// </summary> /// returns FALSE if the doc can not be renamed internal bool RenameDocument(string oldName, string newName) { IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT == null) return false; IntPtr docData = IntPtr.Zero; IVsHierarchy pIVsHierarchy; uint itemId; uint uiVsDocCookie; SuspendFileChanges sfc = null; if (File.Exists(oldName)) { sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName); sfc.Suspend(); } try { // Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished. // Scenario that could fail if we do not suspend. // We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.) // 1. User renames a file in the above project sytem relying on MPF // 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file. // 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded. // The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process. // The result is that the project re-evaluates itself wrongly. VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags; ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie)); if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr)) { // Don't rename it if it wasn't opened by us. return false; } // ask other potentially running packages if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag)) { return false; } if (IsFileOnDisk(oldName)) { RenameInStorage(oldName, newName); } // For some reason when ignoreFileChanges is called in Resume, we get an ArgumentException because // Somewhere a required fileWatcher is null. This issue only occurs when you copy and rename a typescript file, // Calling Resume here prevents said fileWatcher from being null. Don't know why it works, but it does. // Also fun! This is the only location it can go (between RenameInStorage and RenameFileNode) // So presumably there is some condition that is no longer met once both of these methods are called with a ts file. // https://nodejstools.codeplex.com/workitem/1510 if (sfc != null) { sfc.Resume(); sfc.Suspend(); } if (!CommonUtils.IsSamePath(oldName, newName)) { // Check out the project file if necessary. if (!this.ProjectMgr.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } this.RenameFileNode(oldName, newName); } else if (!oldName.Equals(newName, StringComparison.Ordinal)) { this.RenameCaseOnlyChange(oldName, newName); } DocumentManager.UpdateCaption(this.ProjectMgr.Site, Caption, docData); // changed from MPFProj: // http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8231 this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag); } finally { if (sfc != null) { sfc.Resume(); } if (docData != IntPtr.Zero) { Marshal.Release(docData); } } return true; } internal virtual FileNode RenameFileNode(string oldFileName, string newFileName) { string newFolder = CommonUtils.GetParent(newFileName); var parentFolder = ProjectMgr.CreateFolderNodes(newFolder); if (parentFolder == null) { throw new InvalidOperationException("Invalid parent path: " + newFolder); } return this.RenameFileNode(oldFileName, newFileName, parentFolder); } /// <summary> /// Renames the file node for a case only change. /// </summary> /// <param name="newFileName">The new file name.</param> private void RenameCaseOnlyChange(string oldName, string newName) { //Update the include for this item. string relName = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newName); Debug.Assert(String.Equals(this.ItemNode.GetMetadata(ProjectFileConstants.Include), relName, StringComparison.OrdinalIgnoreCase), "Not just changing the filename case"); this.ItemNode.Rename(relName); this.ItemNode.RefreshProperties(); UpdateCaption(); ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption); this.RenameChildNodes(this); // Refresh the property browser. IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); //Select the new node in the hierarchy ExpandItem(EXPANDFLAGS.EXPF_SelectItem); } #endregion #region helpers /// <summary> /// Update the ChildNodes after the parent node has been renamed /// </summary> /// <param name="newFileNode">The new FileNode created as part of the rename of this node</param> private void SetNewParentOnChildNodes(FileNode newFileNode) { foreach (HierarchyNode childNode in GetChildNodes()) { childNode.Parent = newFileNode; } } private List<HierarchyNode> GetChildNodes() { List<HierarchyNode> childNodes = new List<HierarchyNode>(); HierarchyNode childNode = this.FirstChild; while (childNode != null) { childNodes.Add(childNode); childNode = childNode.NextSibling; } return childNodes; } #endregion void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) { string oldLoc = CommonUtils.GetAbsoluteFilePath(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include)); string newLoc = CommonUtils.GetAbsoluteFilePath(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include)); ProjectMgr.UpdatePathForDeferredSave(oldLoc, newLoc); // make sure the directory is there Directory.CreateDirectory(Path.GetDirectoryName(newLoc)); if (File.Exists(oldLoc)) { File.Move(oldLoc, newLoc); } } } }
// This file has been generated by the GUI designer. Do not modify. namespace Pinta.Effects { public partial class CurvesDialog { private global::Gtk.HBox hbox1; private global::Gtk.Label labelMap; private global::Gtk.HSeparator hseparatorMap; private global::Gtk.HBox hbox2; private global::Gtk.ComboBox comboMap; private global::Gtk.Alignment alignment3; private global::Gtk.Label labelPoint; private global::Gtk.DrawingArea drawing; private global::Gtk.HBox hbox3; private global::Gtk.CheckButton checkRed; private global::Gtk.CheckButton checkGreen; private global::Gtk.CheckButton checkBlue; private global::Gtk.Alignment alignment1; private global::Gtk.Button buttonReset; private global::Gtk.Label labelTip; private global::Gtk.Button buttonCancel; private global::Gtk.Button buttonOk; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget Pinta.Effects.CurvesDialog this.Name = "Pinta.Effects.CurvesDialog"; this.Title = global::Mono.Unix.Catalog.GetString ("Curves"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); this.Resizable = false; this.AllowGrow = false; this.SkipTaskbarHint = true; // Internal child Pinta.Effects.CurvesDialog.VBox global::Gtk.VBox w1 = this.VBox; w1.Name = "dialog1_VBox"; w1.BorderWidth = ((uint)(2)); // Container child dialog1_VBox.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.labelMap = new global::Gtk.Label (); this.labelMap.Name = "labelMap"; this.labelMap.LabelProp = global::Mono.Unix.Catalog.GetString ("Transfer Map"); this.hbox1.Add (this.labelMap); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.labelMap])); w2.Position = 0; w2.Expand = false; w2.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.hseparatorMap = new global::Gtk.HSeparator (); this.hseparatorMap.Name = "hseparatorMap"; this.hbox1.Add (this.hseparatorMap); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.hseparatorMap])); w3.Position = 1; w1.Add (this.hbox1); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(w1 [this.hbox1])); w4.Position = 0; w4.Expand = false; w4.Fill = false; // Container child dialog1_VBox.Gtk.Box+BoxChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; // Container child hbox2.Gtk.Box+BoxChild this.comboMap = global::Gtk.ComboBox.NewText (); this.comboMap.AppendText (global::Mono.Unix.Catalog.GetString ("RGB")); this.comboMap.AppendText (global::Mono.Unix.Catalog.GetString ("Luminosity")); this.comboMap.Name = "comboMap"; this.comboMap.Active = 1; this.hbox2.Add (this.comboMap); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.comboMap])); w5.Position = 0; w5.Expand = false; w5.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.alignment3 = new global::Gtk.Alignment (1F, 0.5F, 0F, 0F); this.alignment3.Name = "alignment3"; // Container child alignment3.Gtk.Container+ContainerChild this.labelPoint = new global::Gtk.Label (); this.labelPoint.Name = "labelPoint"; this.labelPoint.LabelProp = global::Mono.Unix.Catalog.GetString ("(256, 256)"); this.alignment3.Add (this.labelPoint); this.hbox2.Add (this.alignment3); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.alignment3])); w7.PackType = ((global::Gtk.PackType)(1)); w7.Position = 2; w7.Expand = false; w7.Fill = false; w1.Add (this.hbox2); global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(w1 [this.hbox2])); w8.Position = 1; w8.Expand = false; w8.Fill = false; // Container child dialog1_VBox.Gtk.Box+BoxChild this.drawing = new global::Gtk.DrawingArea (); this.drawing.WidthRequest = 256; this.drawing.HeightRequest = 256; this.drawing.CanFocus = true; this.drawing.Events = ((global::Gdk.EventMask)(795646)); this.drawing.Name = "drawing"; w1.Add (this.drawing); global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(w1 [this.drawing])); w9.Position = 2; w9.Padding = ((uint)(8)); // Container child dialog1_VBox.Gtk.Box+BoxChild this.hbox3 = new global::Gtk.HBox (); this.hbox3.Name = "hbox3"; // Container child hbox3.Gtk.Box+BoxChild this.checkRed = new global::Gtk.CheckButton (); this.checkRed.CanFocus = true; this.checkRed.Name = "checkRed"; this.checkRed.Label = global::Mono.Unix.Catalog.GetString ("Red "); this.checkRed.Active = true; this.checkRed.DrawIndicator = true; this.checkRed.UseUnderline = true; this.hbox3.Add (this.checkRed); global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.checkRed])); w10.Position = 0; // Container child hbox3.Gtk.Box+BoxChild this.checkGreen = new global::Gtk.CheckButton (); this.checkGreen.CanFocus = true; this.checkGreen.Name = "checkGreen"; this.checkGreen.Label = global::Mono.Unix.Catalog.GetString ("Green"); this.checkGreen.Active = true; this.checkGreen.DrawIndicator = true; this.checkGreen.UseUnderline = true; this.hbox3.Add (this.checkGreen); global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.checkGreen])); w11.Position = 1; // Container child hbox3.Gtk.Box+BoxChild this.checkBlue = new global::Gtk.CheckButton (); this.checkBlue.CanFocus = true; this.checkBlue.Name = "checkBlue"; this.checkBlue.Label = global::Mono.Unix.Catalog.GetString ("Blue "); this.checkBlue.Active = true; this.checkBlue.DrawIndicator = true; this.checkBlue.UseUnderline = true; this.hbox3.Add (this.checkBlue); global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.checkBlue])); w12.Position = 2; // Container child hbox3.Gtk.Box+BoxChild this.alignment1 = new global::Gtk.Alignment (0.5F, 0.5F, 1F, 1F); this.alignment1.Name = "alignment1"; this.hbox3.Add (this.alignment1); global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.alignment1])); w13.Position = 3; // Container child hbox3.Gtk.Box+BoxChild this.buttonReset = new global::Gtk.Button (); this.buttonReset.WidthRequest = 81; this.buttonReset.HeightRequest = 30; this.buttonReset.CanFocus = true; this.buttonReset.Name = "buttonReset"; this.buttonReset.UseUnderline = true; this.buttonReset.Label = global::Mono.Unix.Catalog.GetString ("Reset"); this.hbox3.Add (this.buttonReset); global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.buttonReset])); w14.Position = 4; w14.Expand = false; w14.Fill = false; w1.Add (this.hbox3); global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(w1 [this.hbox3])); w15.Position = 3; w15.Expand = false; w15.Fill = false; // Container child dialog1_VBox.Gtk.Box+BoxChild this.labelTip = new global::Gtk.Label (); this.labelTip.Name = "labelTip"; this.labelTip.LabelProp = global::Mono.Unix.Catalog.GetString ("Tip: Right-click to remove control points."); w1.Add (this.labelTip); global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(w1 [this.labelTip])); w16.Position = 4; w16.Expand = false; w16.Fill = false; // Internal child Pinta.Effects.CurvesDialog.ActionArea global::Gtk.HButtonBox w17 = this.ActionArea; w17.Name = "dialog1_ActionArea"; w17.Spacing = 10; w17.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild this.buttonCancel = new global::Gtk.Button (); this.buttonCancel.CanDefault = true; this.buttonCancel.CanFocus = true; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseStock = true; this.buttonCancel.UseUnderline = true; this.buttonCancel.Label = "gtk-cancel"; this.AddActionWidget (this.buttonCancel, -6); global::Gtk.ButtonBox.ButtonBoxChild w18 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w17 [this.buttonCancel])); w18.Expand = false; w18.Fill = false; // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild this.buttonOk = new global::Gtk.Button (); this.buttonOk.CanDefault = true; this.buttonOk.CanFocus = true; this.buttonOk.Name = "buttonOk"; this.buttonOk.UseStock = true; this.buttonOk.UseUnderline = true; this.buttonOk.Label = "gtk-ok"; this.AddActionWidget (this.buttonOk, -5); global::Gtk.ButtonBox.ButtonBoxChild w19 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w17 [this.buttonOk])); w19.Position = 1; w19.Expand = false; w19.Fill = false; if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 269; this.DefaultHeight = 418; this.checkRed.Hide (); this.checkGreen.Hide (); this.checkBlue.Hide (); this.Show (); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Compatibility.dll // Description: Supports DotSpatial interfaces organized for a MapWindow 4 plugin context. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 1/21/2009 1:00:46 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Windows.Forms; using DotSpatial.Controls; namespace DotSpatial.Compatibility { /// <summary> /// MapWin /// </summary> public class MapWin : IMapWin { #region Private Variables // New Stuff // Legacy Stuff private readonly IUserInteraction _userInteraction; private IAppInfo _appInfo; private bool _displayFullProjectPath; private string _lastError; private ILegend _legend; private Form _mainForm; private IBasicMap _map; private MenuStrip _menuStrip; #endregion /// <summary> /// Constructs a new empty instance of this interface wrapper that is mostly used /// for backwards compatibility. /// </summary> public MapWin() { _appInfo = new AppInfo(); } /// <summary> /// Constructs a new instance of a MapWin interface where the Map, Legend, Form and MenuStrip /// are all specified. /// </summary> /// <param name="inMap">Any valid implementation of IBasicMap</param> /// <param name="inLegend">Any valid implementation of ILegend</param> /// <param name="inMainForm">Any valid windows Form</param> /// <param name="inMenuStrip">Any valid windows MenuStrip</param> public MapWin(IBasicMap inMap, ILegend inLegend, Form inMainForm, MenuStrip inMenuStrip) { _map = inMap; _legend = inLegend; _mainForm = inMainForm; _menuStrip = inMenuStrip; _userInteraction = new UserInteraction(); } #region Methods /// <summary> /// Returns dialog title for the main window to the default "project name" title. /// </summary> public void ClearCustomWindowTitle() { _mainForm.Text = "DotSpatial 6.0"; } /// <summary> /// In The new context, this return whatever the BasicMap is. /// </summary> public object GetOCX { get { return _map; } } /// <summary> /// Prompt the user to select a projection, and return the PROJ4 representation of this /// projection. Specify the dialog caption and an optional default projection ("" for none). /// </summary> /// <param name="dialogCaption">The text to be displayed on the dialog, e.g. "Please select a projection."</param> /// <param name="defaultProjection">The PROJ4 projection string of the projection to default to, "" for none.</param> /// <returns></returns> public string GetProjectionFromUser(string dialogCaption, string defaultProjection) { //bool TO_DO_PROJECTION_RETRIEVAL_FORMS = true; throw new NotImplementedException(); } /// <summary> /// Refreshes the DotSpatial display. /// </summary> public void Refresh() { _map.RefreshMap(_map.ClientRectangle); } /// <summary> /// Refreshes Dynamic Visibility /// </summary> public void RefreshDynamicVisibility() { //bool To_DO_DYNAMIC_VISIBILITY = true; throw new NotImplementedException(); } /// <summary> /// Sets the dialog title to be displayed after the "AppInfo" name for the main window. /// Overrides the default "project name" title. /// </summary> public void SetCustomWindowTitle(string newTitleText) { _mainForm.Text = newTitleText; } /// <summary> /// Displays the DotSpatial error dialog. /// </summary> /// <param name="ex"></param> public void ShowErrorDialog(Exception ex) { //bool TO_DO_ERROR_DIALOG = true; throw new NotImplementedException(); } /// <summary> /// Displays the DotSpatial error dialog, sending to a specific address. /// </summary> /// <param name="ex"></param> /// <param name="sendEmailTo"></param> public void ShowErrorDialog(Exception ex, string sendEmailTo) { //bool TO_DO_ERROR_DIALOG = true; throw new NotImplementedException(); } #endregion #region Properties /// <summary> /// Provides control over application-level settings like the app name. /// </summary> public IAppInfo ApplicationInfo { get { return _appInfo; } set { _appInfo = value; } } /// <summary> /// Specify whether the full project path should be specified rather than just fileName, in title bar for main window. /// </summary> public bool DisplayFullProjectPath { get { return _displayFullProjectPath; } set { _displayFullProjectPath = value; } } /// <summary> /// Gets the last error message set. Note: This error message could have been set at any time. /// </summary> public string LastError { get { return _lastError; } set { _lastError = value; } } /// <summary> /// Returns the <c>Layers</c> object that handles layers. /// </summary> public ILayers Layers { get { throw new NotImplementedException(); } } /// <summary> /// Returns the <c>Menus</c> object that manages the menus. /// </summary> public IMenus Menus { get { return new Menus(_menuStrip); } } /// <summary> /// Returns the <c>Plugins</c> object that manages plugins. /// </summary> public IPlugins Plugins { get { throw new NotImplementedException(); } } /// <summary> /// Returns the <c>PreviewMap</c> object that manages the preview map. /// </summary> public IPreviewMap PreviewMap { get { throw new NotImplementedException(); } } /// <summary> /// Provides control over project and configuration files. /// </summary> public IProject Project { get { throw new NotImplementedException(); } } /// <summary> /// Provides access to report generation methods and properties. /// </summary> public IReports Reports { get { throw new NotImplementedException(); } } /// <summary> /// Returns the <c>StausBar</c> object that manages the status bar. /// </summary> public IStatusBar StatusBar { get { throw new NotImplementedException(); } } /// <summary> /// Returns the <c>Toolbar</c> object that manages toolbars. /// </summary> public IToolbar Toolbar { get { throw new NotImplementedException(); } } /// <summary> /// Provides access to the user panel in the lower right of the DotSpatial form. /// </summary> public IUIPanel UiPanel { get { throw new NotImplementedException(); } } /// <summary> /// User-interactive functions. Used to prompt users to enter things, or otherwise prompt users. /// </summary> public IUserInteraction UserInteraction { get { return _userInteraction; } } /// <summary> /// Returns the <c>View</c> object that handles the map view. /// </summary> public IViewOld View { get { throw new NotImplementedException(); } } #endregion #region Link Properties /// <summary> /// Gets or sets the basic map for this MapWin /// </summary> public IBasicMap Map { get { return _map; } set { _map = value; } } /// <summary> /// Gets or sets the legend to use for this MapWin /// </summary> public ILegend Legend { get { return _legend; } set { _legend = value; } } /// <summary> /// Gets or sets the main form to use for this MapWin /// </summary> public Form MainForm { get { return _mainForm; } set { _mainForm = value; } } /// <summary> /// Gets or sets the menu strip to use for this MapWin /// </summary> public MenuStrip MenuStrip { get { return _menuStrip; } set { _menuStrip = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// UIntPtr.ToUInt32() /// Converts the value of this instance to a 32-bit unsigned integer. /// This method is not CLS-compliant. /// </summary> public class UIntPtrToUInt32 { public static int Main() { UIntPtrToUInt32 testObj = new UIntPtrToUInt32(); TestLibrary.TestFramework.BeginTestCase("for method: UIntPtr.ToPointer()"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; const string c_TEST_DESC = "PosTest1: UIntPtr.Zero"; string errorDesc; UInt32 actualUI, expectedUI; UIntPtr uiPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUI = 0; uiPtr = UIntPtr.Zero; actualUI = uiPtr.ToUInt32(); actualResult = actualUI == expectedUI; if (!actualResult) { errorDesc = "Actual UInt32 from UIntPtr is not " + expectedUI + " as expected: Actual(" + actualUI + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_ID = "P002"; const string c_TEST_DESC = "PosTest2: UIntPtr with a random Int32 value "; string errorDesc; UInt32 actualUI, expectedUI; UIntPtr uiPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUI = (UInt32)TestLibrary.Generator.GetInt32(-55); uiPtr = new UIntPtr(expectedUI); actualUI = uiPtr.ToUInt32(); actualResult = actualUI == expectedUI; if (!actualResult) { errorDesc = "Actual UInt32 from UIntPtr is not " + expectedUI + " as expected: Actual(" + actualUI + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; const string c_TEST_DESC = "PosTest3: UIntPtr with a value greater than Int32.MaxValue"; string errorDesc; UInt32 actualUI, expectedUI; UIntPtr uiPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUI = (UInt32)Int32.MaxValue + (UInt32)TestLibrary.Generator.GetInt32(-55); uiPtr = new UIntPtr(expectedUI); actualUI = uiPtr.ToUInt32(); actualResult = actualUI == expectedUI; if (!actualResult) { errorDesc = "Actual hash code is not " + expectedUI + " as expected: Actual(" + actualUI + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: UIntPtr with a value UInt32.MaxValue"; string errorDesc; UInt32 actualUI, expectedUI; UIntPtr uiPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUI = UInt32.MaxValue; uiPtr = new UIntPtr(expectedUI); actualUI = uiPtr.ToUInt32(); actualResult = actualUI == expectedUI; if (!actualResult) { errorDesc = "Actual hash code is not " + expectedUI + " as expected: Actual(" + actualUI + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #region Negative tests //OverflowException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: On a 32-bit platform, the value of this instance is too large to represent as a 32-bit unsigned integer."; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (UIntPtr.Size != 8) // platform is 64-bit { UInt64 ui = UInt32.MaxValue + this.GetUInt64() % (UInt64.MaxValue - UInt32.MaxValue) + 1; UIntPtr actualUIntPtr = new UIntPtr(ui); errorDesc = "OverflowException is not thrown as expected"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } else { retVal = true; } } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("08" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion #region helper method for tests private UInt64 GetUInt64() { byte[] buffer = new byte[8]; UInt64 uiVal; TestLibrary.Generator.GetBytes(-55, buffer); // convert to UInt64 uiVal = 0; for (int i = 0; i < buffer.Length; i++) { uiVal |= ((UInt64)buffer[i] << (i * 8)); } TestLibrary.TestFramework.LogInformation("Random UInt64 produced: " + uiVal.ToString()); return uiVal; } #endregion }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using System; using System.IO; using System.Collections.Generic; using Aerospike.Client; namespace Aerospike.Demo { public class UserDefinedFunction : SyncExample { public UserDefinedFunction(Console console) : base(console) { } /// <summary> /// Register user defined function and call it. /// </summary> public override void RunExample(AerospikeClient client, Arguments args) { if (!args.hasUdf) { console.Info("User defined functions are not supported by the connected Aerospike server."); return; } Register(client, args); WriteUsingUdf(client, args); WriteIfGenerationNotChanged(client, args); WriteIfNotExists(client, args); WriteWithValidation(client, args); //WriteListMapUsingUdf(client, args); WriteBlobUsingUdf(client, args); ServerSideExists(client, args); } private void Register(AerospikeClient client, Arguments args) { string packageName = "record_example.lua"; console.Info("Register: " + packageName); LuaExample.Register(client, args.policy, packageName); } private void WriteUsingUdf(AerospikeClient client, Arguments args) { Key key = new Key(args.ns, args.set, "udfkey1"); Bin bin = new Bin(args.GetBinName("udfbin1"), "string value"); client.Execute(args.writePolicy, key, "record_example", "writeBin", Value.Get(bin.name), bin.value); Record record = client.Get(args.policy, key, bin.name); string expected = bin.value.ToString(); string received = (string)record.GetValue(bin.name); if (received != null && received.Equals(expected)) { console.Info("Data matched: namespace={0} set={1} key={2} bin={3} value={4}", key.ns, key.setName, key.userKey, bin.name, received); } else { console.Error("Data mismatch: Expected {0}. Received {1}.", expected, received); } } private void WriteIfGenerationNotChanged(AerospikeClient client, Arguments args) { Key key = new Key(args.ns, args.set, "udfkey2"); Bin bin = new Bin(args.GetBinName("udfbin2"), "string value"); // Seed record. client.Put(args.writePolicy, key, bin); // Get record generation. long gen = (long)client.Execute(args.writePolicy, key, "record_example", "getGeneration"); // Write record if generation has not changed. client.Execute(args.writePolicy, key, "record_example", "writeIfGenerationNotChanged", Value.Get(bin.name), bin.value, Value.Get(gen)); console.Info("Record written."); } private void WriteIfNotExists(AerospikeClient client, Arguments args) { Key key = new Key(args.ns, args.set, "udfkey3"); string binName = "udfbin3"; // Delete record if it already exists. client.Delete(args.writePolicy, key); // Write record only if not already exists. This should succeed. client.Execute(args.writePolicy, key, "record_example", "writeUnique", Value.Get(binName), Value.Get("first")); // Verify record written. Record record = client.Get(args.policy, key, binName); string expected = "first"; string received = (string)record.GetValue(binName); if (received != null && received.Equals(expected)) { console.Info("Record written: namespace={0} set={1} key={2} bin={3} value={4}", key.ns, key.setName, key.userKey, binName, received); } else { console.Error("Data mismatch: Expected {0}. Received {1}.", expected, received); } // Write record second time. This should fail. console.Info("Attempt second write."); client.Execute(args.writePolicy, key, "record_example", "writeUnique", Value.Get(binName), Value.Get("second")); // Verify record not written. record = client.Get(args.policy, key, binName); received = (string)record.GetValue(binName); if (received != null && received.Equals(expected)) { console.Info("Success. Record remained unchanged: namespace={0} set={1} key={2} bin={3} value={4}", key.ns, key.setName, key.userKey, binName, received); } else { console.Error("Data mismatch: Expected {0}. Received {1}.", expected, received); } } private void WriteWithValidation(AerospikeClient client, Arguments args) { Key key = new Key(args.ns, args.set, "udfkey4"); string binName = "udfbin4"; // Lua function writeWithValidation accepts number between 1 and 10. // Write record with valid value. console.Info("Write with valid value."); client.Execute(args.writePolicy, key, "record_example", "writeWithValidation", Value.Get(binName), Value.Get(4)); // Write record with invalid value. console.Info("Write with invalid value."); try { client.Execute(args.writePolicy, key, "record_example", "writeWithValidation", Value.Get(binName), Value.Get(11)); console.Error("UDF should not have succeeded!"); } catch (Exception) { console.Info("Success. UDF resulted in exception as expected."); } } private void WriteListMapUsingUdf(AerospikeClient client, Arguments args) { Key key = new Key(args.ns, args.set, "udfkey5"); List<object> inner = new List<object>(); inner.Add("string2"); inner.Add(8L); Dictionary<object, object> innerMap = new Dictionary<object, object>(); innerMap["a"] = 1L; innerMap[2L] = "b"; innerMap["list"] = inner; List<object> list = new List<object>(); list.Add("string1"); list.Add(4L); list.Add(inner); list.Add(innerMap); string binName = args.GetBinName("udfbin5"); client.Execute(args.writePolicy, key, "record_example", "writeBin", Value.Get(binName), Value.Get(list)); object received = client.Execute(args.writePolicy, key, "record_example", "readBin", Value.Get(binName)); string receivedString = Util.ListToString((List<object>)received); string expectedString = Util.ListToString(list); if (receivedString.Equals(expectedString)) { console.Info("UDF data matched: namespace={0} set={1} key={2} bin={3} value={4}", key.ns, key.setName, key.userKey, binName, received); } else { console.Error("UDF data mismatch"); console.Error("Expected " + list); console.Error("Received " + received); } } private void WriteBlobUsingUdf(AerospikeClient client, Arguments args) { Key key = new Key(args.ns, args.set, "udfkey6"); string binName = args.GetBinName("udfbin6"); byte[] blob; // Create packed blob using standard C# tools. using (MemoryStream ms = new MemoryStream()) { Formatter.Default.Serialize(ms, 9845); Formatter.Default.Serialize(ms, "Hello world."); blob = ms.ToArray(); } client.Execute(args.writePolicy, key, "record_example", "writeBin", Value.Get(binName), Value.Get(blob)); byte[] received = (byte[])client.Execute(args.writePolicy, key, "record_example", "readBin", Value.Get(binName)); string receivedString = Util.BytesToString(received); string expectedString = Util.BytesToString(blob); if (receivedString.Equals(expectedString)) { console.Info("Blob data matched: namespace={0} set={1} key={2} bin={3} value={4}", key.ns, key.setName, key.userKey, binName, receivedString); } else { throw new Exception(string.Format("Mismatch: expected={0} received={1}", expectedString, receivedString)); } } private void ServerSideExists(AerospikeClient client, Arguments args) { console.Info("Write list."); List<int> list = new List<int>(); list.Add(64); list.Add(3702); list.Add(-5); Key key = new Key(args.ns, args.set, "udfkey7"); Bin bin = new Bin("udfbin7", list); client.Put(args.writePolicy, key, bin); ServerSideExists(client, args.writePolicy, key, bin, 3702, true); ServerSideExists(client, args.writePolicy, key, bin, 65, false); } private void ServerSideExists(AerospikeClient client, WritePolicy policy, Key key, Bin bin, int search, bool expected) { long lexists = (long)client.Execute(policy, key, "record_example", "valueExists", Value.Get(bin.name), Value.Get(search)); bool exists = (lexists != 0); if (expected && exists) { console.Info("Value found as expected."); return; } if (!expected && !exists) { console.Info("Value not found as expected."); return; } console.Error("Data mismatch. Expected " + expected + " Received " + exists); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Caching; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Sprites; using osuTK; namespace osu.Framework.Text { /// <summary> /// A text builder for <see cref="SpriteText"/> and other text-based display components. /// </summary> public class TextBuilder : IHasLineBaseHeight { /// <summary> /// The bounding size of the composite text. /// </summary> public Vector2 Bounds { get; private set; } /// <summary> /// The characters generated by this <see cref="TextBuilder"/>. /// </summary> public readonly List<TextBuilderGlyph> Characters; private readonly char[] neverFixedWidthCharacters; private readonly char fallbackCharacter; private readonly char fixedWidthReferenceCharacter; private readonly ITexturedGlyphLookupStore store; private readonly FontUsage font; private readonly bool useFontSizeAsHeight; private readonly Vector2 startOffset; private readonly Vector2 spacing; private readonly float maxWidth; private Vector2 currentPos; private float currentLineHeight; private float? currentLineBase; private bool currentNewLine = true; /// <summary> /// Gets the current base height of the text in this <see cref="TextBuilder"/>. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown when attempting to access this property on a <see cref="TextBuilder"/> with multiple lines added. /// </exception> public float LineBaseHeight { get { if (currentPos.Y > startOffset.Y) throw new InvalidOperationException($"Cannot return a {nameof(LineBaseHeight)} from a text builder with multiple lines."); return currentLineBase ?? 0f; } } /// <summary> /// Creates a new <see cref="TextBuilder"/>. /// </summary> /// <param name="store">The store from which glyphs are to be retrieved from.</param> /// <param name="font">The font to use for glyph lookups from <paramref name="store"/>.</param> /// <param name="useFontSizeAsHeight">True to use the provided <see cref="font"/> size as the height for each line. False if the height of each individual glyph should be used.</param> /// <param name="startOffset">The offset at which characters should begin being added at.</param> /// <param name="spacing">The spacing between characters.</param> /// <param name="maxWidth">The maximum width of the resulting text bounds.</param> /// <param name="characterList">That list to contain all resulting <see cref="TextBuilderGlyph"/>s.</param> /// <param name="neverFixedWidthCharacters">The characters for which fixed width should never be applied.</param> /// <param name="fallbackCharacter">The character to use if a glyph lookup fails.</param> /// <param name="fixedWidthReferenceCharacter">The character to use to calculate the fixed width width. Defaults to 'm'.</param> public TextBuilder(ITexturedGlyphLookupStore store, FontUsage font, float maxWidth = float.MaxValue, bool useFontSizeAsHeight = true, Vector2 startOffset = default, Vector2 spacing = default, List<TextBuilderGlyph> characterList = null, char[] neverFixedWidthCharacters = null, char fallbackCharacter = '?', char fixedWidthReferenceCharacter = 'm') { this.store = store; this.font = font; this.useFontSizeAsHeight = useFontSizeAsHeight; this.startOffset = startOffset; this.spacing = spacing; this.maxWidth = maxWidth; Characters = characterList ?? new List<TextBuilderGlyph>(); this.neverFixedWidthCharacters = neverFixedWidthCharacters ?? Array.Empty<char>(); this.fallbackCharacter = fallbackCharacter; this.fixedWidthReferenceCharacter = fixedWidthReferenceCharacter; currentPos = startOffset; } /// <summary> /// Resets this <see cref="TextBuilder"/> to a default state. /// </summary> public virtual void Reset() { Bounds = Vector2.Zero; Characters.Clear(); currentPos = startOffset; currentLineBase = null; currentLineHeight = 0; currentNewLine = true; } /// <summary> /// Whether characters can be added to this <see cref="TextBuilder"/>. /// </summary> protected virtual bool CanAddCharacters => true; /// <summary> /// Appends text to this <see cref="TextBuilder"/>. /// </summary> /// <param name="text">The text to append.</param> public void AddText(string text) { foreach (char c in text) { if (!AddCharacter(c)) break; } } /// <summary> /// Appends a character to this <see cref="TextBuilder"/>. /// </summary> /// <param name="character">The character to append.</param> /// <returns>Whether characters can still be added.</returns> public bool AddCharacter(char character) { if (!CanAddCharacters) return false; if (!tryCreateGlyph(character, out var glyph)) return true; // For each character that is added: // 1. Add the kerning to the current position if required. // 2. Draw the character at the current position offset by the glyph. // The offset is not applied to the current position, it is only a value to be used at draw-time. // 3. If this character has a different baseline from the previous, adjust either the previous characters or this character's to align on one baseline. // 4. Advance the current position by glyph's XAdvance. float kerning = 0; // Spacing + kerning are only applied if the current line is not empty if (!currentNewLine) { if (Characters.Count > 0) kerning = glyph.GetKerning(Characters[^1].Glyph); kerning += spacing.X; } // Check if there is enough space for the character and let subclasses decide whether to continue adding the character if not if (!HasAvailableSpace(kerning + glyph.XAdvance)) { OnWidthExceeded(); if (!CanAddCharacters) return false; } // The kerning is only added after it is guaranteed that the character will be added, to not leave the current position in a bad state currentPos.X += kerning; glyph.DrawRectangle = new RectangleF(new Vector2(currentPos.X + glyph.XOffset, currentPos.Y + glyph.YOffset), new Vector2(glyph.Width, glyph.Height)); glyph.OnNewLine = currentNewLine; if (glyph.Baseline > currentLineBase) { for (int i = Characters.Count - 1; i >= 0; --i) { var previous = Characters[i]; previous.DrawRectangle = previous.DrawRectangle.Offset(0, glyph.Baseline - currentLineBase.Value); Characters[i] = previous; if (previous.OnNewLine) break; } } else if (glyph.Baseline < currentLineBase) glyph.DrawRectangle = glyph.DrawRectangle.Offset(0, currentLineBase.Value - glyph.Baseline); Characters.Add(glyph); currentPos.X += glyph.XAdvance; currentLineBase = currentLineBase == null ? glyph.Baseline : Math.Max(currentLineBase.Value, glyph.Baseline); currentLineHeight = Math.Max(currentLineHeight, getGlyphHeight(ref glyph)); currentNewLine = false; Bounds = Vector2.ComponentMax(Bounds, currentPos + new Vector2(0, currentLineHeight)); return true; } /// <summary> /// Adds a new line to this <see cref="TextBuilder"/>. /// </summary> /// <remarks> /// A height equal to that of the font size will be assumed if the current line is empty, regardless of <see cref="useFontSizeAsHeight"/>. /// </remarks> public void AddNewLine() { if (currentNewLine) currentLineHeight = font.Size; // Reset + vertically offset the current position currentPos.X = startOffset.X; currentPos.Y += currentLineHeight + spacing.Y; currentLineBase = null; currentLineHeight = 0; currentNewLine = true; } /// <summary> /// Removes the last character added to this <see cref="TextBuilder"/>. /// If the character is the first character on a new line, the new line is also removed. /// </summary> public void RemoveLastCharacter() { if (Characters.Count == 0) return; TextBuilderGlyph removedCharacter = Characters[^1]; TextBuilderGlyph? previousCharacter = Characters.Count == 1 ? null : (TextBuilderGlyph?)Characters[^2]; Characters.RemoveAt(Characters.Count - 1); // For each character that is removed: // 1. Calculate the new baseline and line height of the last line. // 2. If the character is the first on a new line, move the current position upwards by the calculated line height and to the end of the previous line. // The position at the end of the line is the post-XAdvanced position. // 3. If the character is not the first on a new line, move the current position backwards by the XAdvance and the kerning from the previous glyph. // This brings the current position to the post-XAdvanced position of the previous glyph. // 4. Also if the character is not the first on a new line and removing it changed the baseline, adjust the characters behind it to the new baseline. float? lastLineBase = currentLineBase; currentLineBase = null; currentLineHeight = 0; // This is O(n^2) for removing all characters within a line, but is generally not used in such a case for (int i = Characters.Count - 1; i >= 0; i--) { var character = Characters[i]; currentLineBase = currentLineBase == null ? character.Baseline : Math.Max(currentLineBase.Value, character.Baseline); currentLineHeight = Math.Max(currentLineHeight, getGlyphHeight(ref character)); if (character.OnNewLine) break; } if (removedCharacter.OnNewLine) { // Move up to the previous line currentPos.Y -= currentLineHeight; // If this is the first line (ie. there are no characters remaining) we shouldn't be removing the spacing, // as there is no spacing applied to the first line. if (Characters.Count > 0) currentPos.Y -= spacing.Y; currentPos.X = 0; if (previousCharacter != null) { // The character's draw rectangle is the only marker that keeps a constant state for the position, but it has the glyph's XOffset added into it // So the post-kerned position can be retrieved by taking the XOffset away, and the post-XAdvanced position is retrieved by adding the XAdvance back in currentPos.X = previousCharacter.Value.DrawRectangle.Left - previousCharacter.Value.XOffset + previousCharacter.Value.XAdvance; } } else { // Move back within the current line, reversing the operations in AddCharacter() currentPos.X -= removedCharacter.XAdvance; if (previousCharacter != null) currentPos.X -= removedCharacter.GetKerning(previousCharacter.Value) + spacing.X; // Adjust the alignment of the previous characters if the baseline position lowered after removing the character. if (currentLineBase < lastLineBase) { for (int i = Characters.Count - 1; i >= 0; i--) { var character = Characters[i]; character.DrawRectangle = character.DrawRectangle.Offset(0, currentLineBase.Value - lastLineBase.Value); Characters[i] = character; if (character.OnNewLine) break; } } } Bounds = Vector2.Zero; for (int i = 0; i < Characters.Count; i++) { // As above, the bounds are calculated through the character draw rectangles Bounds = Vector2.ComponentMax( Bounds, new Vector2( Characters[i].DrawRectangle.Left - Characters[i].XOffset + Characters[i].XAdvance, Characters[i].DrawRectangle.Top - Characters[i].YOffset + currentLineHeight) ); } // The new line is removed when the first character on the line is removed, thus the current position is never on a new line // after a character is removed except when there are no characters remaining in the builder if (Characters.Count == 0) currentNewLine = true; } /// <summary> /// Invoked when a character is being added that exceeds the maximum width of the text bounds. /// </summary> /// <remarks> /// The character will not continue being added if <see cref="CanAddCharacters"/> is changed during this invocation. /// </remarks> protected virtual void OnWidthExceeded() { } /// <summary> /// Whether there is enough space in the available text bounds. /// </summary> /// <param name="length">The space requested.</param> protected virtual bool HasAvailableSpace(float length) => currentPos.X + length <= maxWidth; /// <summary> /// Retrieves the height of a glyph. /// </summary> /// <param name="glyph">The glyph to retrieve the height of.</param> /// <returns>The height of the glyph.</returns> private float getGlyphHeight<T>(ref T glyph) where T : ITexturedCharacterGlyph { if (useFontSizeAsHeight) return font.Size; // Space characters typically have heights that exceed the height of all other characters in the font // Thus, the height is forced to 0 such that only non-whitespace character heights are considered if (glyph.IsWhiteSpace()) return 0; return glyph.YOffset + glyph.Height; } private readonly Cached<float> constantWidthCache = new Cached<float>(); private float getConstantWidth() => constantWidthCache.IsValid ? constantWidthCache.Value : constantWidthCache.Value = getTexturedGlyph(fixedWidthReferenceCharacter)?.Width ?? 0; private bool tryCreateGlyph(char character, out TextBuilderGlyph glyph) { var fontStoreGlyph = getTexturedGlyph(character); if (fontStoreGlyph == null) { glyph = default; return false; } // Array.IndexOf is used to avoid LINQ if (font.FixedWidth && Array.IndexOf(neverFixedWidthCharacters, character) == -1) glyph = new TextBuilderGlyph(fontStoreGlyph, font.Size, getConstantWidth()); else glyph = new TextBuilderGlyph(fontStoreGlyph, font.Size); return true; } private ITexturedCharacterGlyph getTexturedGlyph(char character) { return store.Get(font.FontName, character) ?? store.Get(null, character) ?? store.Get(font.FontName, fallbackCharacter) ?? store.Get(null, fallbackCharacter); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace MongoDB.Bson { /// <summary> /// Class that knows how to format a native object into bson bits. /// </summary> public class BsonWriter { private const int BufferLength = 256; private readonly byte[] _buffer; private readonly IBsonObjectDescriptor _descriptor; private readonly int _maxChars; private readonly Stream _stream; private readonly BinaryWriter _writer; /// <summary> /// Initializes a new instance of the <see cref = "BsonWriter" /> class. /// </summary> /// <param name = "stream">The stream.</param> /// <param name = "settings">The settings.</param> public BsonWriter(Stream stream, BsonWriterSettings settings) { if(settings == null) throw new ArgumentNullException("settings"); _stream = stream; _descriptor = settings.Descriptor; _writer = new BinaryWriter(_stream); _buffer = new byte[BufferLength]; _maxChars = BufferLength/Encoding.UTF8.GetMaxByteCount(1); } /// <summary> /// Initializes a new instance of the <see cref = "BsonWriter" /> class. /// </summary> /// <param name = "stream">The stream.</param> /// <param name = "descriptor">The descriptor.</param> public BsonWriter(Stream stream, IBsonObjectDescriptor descriptor) { _stream = stream; _descriptor = descriptor; _writer = new BinaryWriter(_stream); _buffer = new byte[BufferLength]; _maxChars = BufferLength/Encoding.UTF8.GetMaxByteCount(1); } /// <summary> /// Writes the value. /// </summary> /// <param name = "type">Type of the data.</param> /// <param name = "obj">The obj.</param> public void WriteValue(BsonType type, Object obj) { switch(type) { case BsonType.MinKey: case BsonType.MaxKey: case BsonType.Null: return; case BsonType.Boolean: _writer.Write((bool)obj); return; case BsonType.Integer: _writer.Write((int)obj); return; case BsonType.Long: if(obj is TimeSpan) _writer.Write(((TimeSpan)obj).Ticks); else _writer.Write((long)obj); return; case BsonType.Date: Write((DateTime)obj); return; case BsonType.Oid: Write((Oid)obj); return; case BsonType.Number: _writer.Write(Convert.ToDouble(obj)); return; case BsonType.String: if(obj is string) Write((string)obj); else Write(obj.ToString()); return; case BsonType.Obj: if(obj is DBRef) Write((DBRef)obj); else WriteObject(obj); return; case BsonType.Array: WriteArray((IEnumerable)obj); return; case BsonType.Regex: if(obj is Regex) Write(new MongoRegex((Regex)obj)); else Write((MongoRegex)obj); return; case BsonType.Code: Write((Code)obj); return; case BsonType.Symbol: WriteValue(BsonType.String, ((MongoSymbol)obj).Value); return; case BsonType.CodeWScope: Write((CodeWScope)obj); return; case BsonType.Binary: { if(obj is Guid) Write((Guid)obj); else if(obj is byte[]) Write((byte[])obj); else Write((Binary)obj); return; } default: throw new NotImplementedException(String.Format("Writing {0} types not implemented.", obj.GetType().Name)); } } /// <summary> /// Writes the specified id. /// </summary> /// <param name = "id">The id.</param> private void Write(Oid id) { _writer.Write(id.ToByteArray()); } /// <summary> /// Writes the specified binary. /// </summary> /// <param name = "binary">The binary.</param> private void Write(Binary binary) { if(binary.Subtype == BinarySubtype.General) { _writer.Write(binary.Bytes.Length + 4); _writer.Write((byte)binary.Subtype); _writer.Write(binary.Bytes.Length); } else { _writer.Write(binary.Bytes.Length); _writer.Write((byte)binary.Subtype); } _writer.Write(binary.Bytes); } /// <summary> /// Writes the specified GUID. /// </summary> /// <param name = "guid">The GUID.</param> private void Write(Guid guid) { _writer.Write(16); _writer.Write((byte)3); _writer.Write(guid.ToByteArray()); } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name = "bytes">The bytes.</param> private void Write(byte[] bytes) { Write(new Binary(bytes)); } /// <summary> /// Writes the specified code scope. /// </summary> /// <param name = "codeScope">The code scope.</param> private void Write(CodeWScope codeScope) { _writer.Write(CalculateSize(codeScope)); WriteValue(BsonType.String, codeScope.Value); WriteValue(BsonType.Obj, codeScope.Scope); } /// <summary> /// Writes the specified code. /// </summary> /// <param name = "code">The code.</param> private void Write(Code code) { WriteValue(BsonType.String, code.Value); } /// <summary> /// Writes the specified regex. /// </summary> /// <param name = "regex">The regex.</param> private void Write(MongoRegex regex) { Write(regex.Expression, false); Write(regex.RawOptions, false); } /// <summary> /// Writes the specified reference. /// </summary> /// <param name = "reference">The reference.</param> public void Write(DBRef reference) { WriteObject((Document)reference); } /// <summary> /// Writes the specified data time. /// </summary> /// <param name = "dateTime">The data time.</param> private void Write(DateTime dateTime) { var diff = dateTime.ToUniversalTime() - BsonInfo.Epoch; var time = Math.Floor(diff.TotalMilliseconds); _writer.Write((long)time); } /// <summary> /// Writes the object. /// </summary> /// <param name = "obj">The obj.</param> public void WriteObject(object obj) { obj = _descriptor.BeginObject(obj); WriteElements(obj); _descriptor.EndObject(obj); } /// <summary> /// Writes the elements. /// </summary> /// <param name = "obj">The obj.</param> private void WriteElements(object obj) { var properties = _descriptor.GetProperties(obj); var size = CalculateSizeObject(obj, properties); if(size >= BsonInfo.MaxDocumentSize) throw new ArgumentException("Maximum document size exceeded."); _writer.Write(size); foreach(var property in properties) { _descriptor.BeginProperty(obj, property); var bsonType = TranslateToBsonType(property.Value); _writer.Write((byte)bsonType); Write(property.Name, false); WriteValue(bsonType, property.Value); _descriptor.EndProperty(obj, property); } _writer.Write((byte)0); } /// <summary> /// Writes the array. /// </summary> /// <param name = "enumerable">The enumerable.</param> public void WriteArray(IEnumerable enumerable) { var obj = _descriptor.BeginArray(enumerable); WriteElements(obj); _descriptor.EndArray(obj); } /// <summary> /// Writes the specified value. /// </summary> /// <param name = "value">The value.</param> private void Write(string value) { Write(value, true); } /// <summary> /// Writes the specified value. /// </summary> /// <param name = "value">The value.</param> /// <param name = "includeLength">if set to <c>true</c> [include length].</param> public void Write(string value, bool includeLength) { if(includeLength) _writer.Write(CalculateSize(value, false)); var byteCount = Encoding.UTF8.GetByteCount(value); if(byteCount < BufferLength) { Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer, 0); _writer.Write(_buffer, 0, byteCount); } else { int charCount; var totalCharsWritten = 0; for(var i = value.Length; i > 0; i -= charCount) { charCount = (i > _maxChars) ? _maxChars : i; var count = Encoding.UTF8.GetBytes(value, totalCharsWritten, charCount, _buffer, 0); _writer.Write(_buffer, 0, count); totalCharsWritten += charCount; } } _writer.Write((byte)0); } /// <summary> /// Calculates the size. /// </summary> /// <param name = "obj">The obj.</param> /// <returns></returns> public int CalculateSize(Object obj) { if(obj == null) return 0; switch(TranslateToBsonType(obj)) { case BsonType.MinKey: case BsonType.MaxKey: case BsonType.Null: return 0; case BsonType.Boolean: return 1; case BsonType.Integer: return 4; case BsonType.Long: case BsonType.Date: return 8; case BsonType.Oid: return 12; case BsonType.Number: return sizeof(Double); case BsonType.String: if(obj is string) return CalculateSize((string)obj); return CalculateSize(obj.ToString()); case BsonType.Obj: return obj.GetType() == typeof(DBRef) ? CalculateSize((DBRef)obj) : CalculateSizeObject(obj); case BsonType.Array: return CalculateSize((IEnumerable)obj); case BsonType.Regex: if(obj is Regex) return CalculateSize(new MongoRegex((Regex)obj)); return CalculateSize((MongoRegex)obj); case BsonType.Code: return CalculateSize((Code)obj); case BsonType.CodeWScope: return CalculateSize((CodeWScope)obj); case BsonType.Binary: { if(obj is Guid) return CalculateSize((Guid)obj); if(obj is byte[]) return CalculateSize((byte[])obj); return CalculateSize((Binary)obj); } case BsonType.Symbol: return CalculateSize(((MongoSymbol)obj).Value, true); } throw new NotImplementedException(String.Format("Calculating size of {0} is not implemented.", obj.GetType().Name)); } /// <summary> /// Calculates the size. /// </summary> /// <param name = "code">The code.</param> /// <returns></returns> private int CalculateSize(Code code) { return CalculateSize(code.Value, true); } /// <summary> /// Calculates the size. /// </summary> /// <param name = "regex">The regex.</param> /// <returns></returns> public int CalculateSize(MongoRegex regex) { var size = CalculateSize(regex.Expression, false); size += CalculateSize(regex.RawOptions, false); return size; } /// <summary> /// Calculates the size. /// </summary> /// <param name = "codeScope">The code scope.</param> /// <returns></returns> public int CalculateSize(CodeWScope codeScope) { var size = 4; size += CalculateSize(codeScope.Value, true); size += CalculateSizeObject(codeScope.Scope); return size; } /// <summary> /// Calculates the size. /// </summary> /// <param name = "binary">The binary.</param> /// <returns></returns> public int CalculateSize(Binary binary) { var size = 4; //size int size += 1; //subtype if(binary.Subtype == BinarySubtype.General) size += 4; //embedded size int size += binary.Bytes.Length; return size; } /// <summary> /// Calculates the size. /// </summary> /// <param name = "bytes">The bytes.</param> /// <returns></returns> public int CalculateSize(byte[] bytes) { return CalculateSize(new Binary(bytes)); } /// <summary> /// Calculates the size. /// </summary> /// <param name = "guid">The GUID.</param> /// <returns></returns> public int CalculateSize(Guid guid) { return 21; } /// <summary> /// Calculates the size. /// </summary> /// <param name = "reference">The reference.</param> /// <returns></returns> public int CalculateSize(DBRef reference) { return CalculateSizeObject((Document)reference); } /// <summary> /// Calculates the size object. /// </summary> /// <param name = "obj">The obj.</param> /// <returns></returns> public int CalculateSizeObject(object obj) { obj = _descriptor.BeginObject(obj); var properties = _descriptor.GetProperties(obj); var size = CalculateSizeObject(obj, properties); _descriptor.EndObject(obj); return size; } /// <summary> /// Calculates the size object. /// </summary> /// <param name = "obj">The obj.</param> /// <param name = "propertys">The propertys.</param> /// <returns></returns> private int CalculateSizeObject(object obj, IEnumerable<BsonProperty> propertys) { var size = 4; foreach(var property in propertys) { var elsize = 1; //type _descriptor.BeginProperty(obj, property); elsize += CalculateSize(property.Name, false); elsize += CalculateSize(property.Value); _descriptor.EndProperty(obj, property); size += elsize; } size += 1; //terminator return size; } /// <summary> /// Calculates the size. /// </summary> /// <param name = "enumerable">The enumerable.</param> /// <returns></returns> public int CalculateSize(IEnumerable enumerable) { var obj = _descriptor.BeginArray(enumerable); var properties = _descriptor.GetProperties(obj); var size = CalculateSizeObject(obj, properties); _descriptor.EndArray(obj); return size; } /// <summary> /// Calculates the size. /// </summary> /// <param name = "value">The value.</param> /// <returns></returns> public int CalculateSize(String value) { return CalculateSize(value, true); } /// <summary> /// Calculates the size. /// </summary> /// <param name = "value">The value.</param> /// <param name = "includeLength">if set to <c>true</c> [include length].</param> /// <returns></returns> public int CalculateSize(String value, bool includeLength) { var size = 1; //terminator if(includeLength) size += 4; if(value != null) size += Encoding.UTF8.GetByteCount(value); return size; } /// <summary> /// Flushes this instance. /// </summary> public void Flush() { _writer.Flush(); } /// <summary> /// Translates the type of to bson. /// </summary> /// <param name = "obj">The obj.</param> /// <returns></returns> protected BsonType TranslateToBsonType(object obj) { //TODO:Convert to use a dictionary if(obj == null) return BsonType.Null; var type = obj.GetType(); if(obj is Enum) //special case enums type = Enum.GetUnderlyingType(type); if(type == typeof(Double)) return BsonType.Number; if(type == typeof(Single)) return BsonType.Number; if(type == typeof(String)) return BsonType.String; if(type == typeof(Uri)) return BsonType.String; if(type == typeof(int)) return BsonType.Integer; if(type == typeof(long)) return BsonType.Long; if(type == typeof(bool)) return BsonType.Boolean; if(type == typeof(Oid)) return BsonType.Oid; if(type == typeof(DateTime)) return BsonType.Date; if(type == typeof(TimeSpan)) return BsonType.Long; if(type == typeof(MongoRegex)) return BsonType.Regex; if(type == typeof(Regex)) return BsonType.Regex; if(type == typeof(DBRef)) return BsonType.Obj; if(type == typeof(Code)) return BsonType.Code; if(type == typeof(CodeWScope)) return BsonType.CodeWScope; if(type == typeof(DBNull)) return BsonType.Null; if(type == typeof(Binary)) return BsonType.Binary; if(type == typeof(Guid)) return BsonType.Binary; if(type == typeof(MongoMinKey)) return BsonType.MinKey; if(type == typeof(MongoMaxKey)) return BsonType.MaxKey; if(type == typeof(MongoSymbol)) return BsonType.Symbol; if(type == typeof(byte[])) return BsonType.Binary; if(_descriptor.IsArray(obj)) return BsonType.Array; if(_descriptor.IsObject(obj)) return BsonType.Obj; if(type == typeof(Decimal)) throw new ArgumentOutOfRangeException("Decimal is not supported in the BSON spec. So it is also not supported in MongoDB. " + "You could convert it to double or store it as Binary instead."); throw new ArgumentOutOfRangeException(String.Format("Type: {0} not recognized", type.FullName)); } } }
// ----- // GNU General Public License // The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. // The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. // See the GNU Lesser General Public License for more details. // ----- using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace fxpa { public class FxpaIndicator : BasicIndicator { /// <summary> /// Dynamically collected using reflection. /// </summary> List<ParameterInfo> _inputDefaultArrayParameters = new List<ParameterInfo>(); /// <summary> /// Dynamically collected using reflection. /// </summary> List<ParameterInfo> _intputParameters = new List<ParameterInfo>(); public List<ParameterInfo> IntputParameters { get { return _intputParameters; } } /// <summary> /// Dynamically collected using reflection. /// </summary> List<ParameterInfo> _outputArraysParameters = new List<ParameterInfo>(); /// <summary> /// Set by the user of the indicator. /// </summary> object[] _inputParametersValues = new object[] { }; public object[] InputParametersValues { get { return _inputParametersValues; } } MethodInfo _methodInfo; /// <summary> /// Default null means indicator does not use it. /// </summary> BarData.DataValueSourceEnum? _realInputArraySource = null; /// <summary> /// Used to fill the double[] realIn (or real0In) array if the indicator requires it. /// </summary> public BarData.DataValueSourceEnum? RealInputArraySource { get { return _realInputArraySource; } set { _realInputArraySource = value; } } /// <summary> /// Default null means indicator does not use it. /// </summary> BarData.DataValueSourceEnum? _real1InputArraySource = null; /// <summary> /// Used to fill the double[] real1In array if the indicator requires it. /// </summary> public BarData.DataValueSourceEnum? Real1InputArraySource { get { return _real1InputArraySource; } set { _real1InputArraySource = value; } } FxpaIndicatorUI _ui; public override BasicIndicatorUI UI { get { return _ui; } } /// <summary> /// /// </summary> FxpaIndicator(string name, string description, bool? isTradeable, bool? isScaledToQuotes, string[] resultSetNames) : base(isTradeable, isScaledToQuotes, resultSetNames) { this.Name = name; this.Description = description; _ui = new FxpaIndicatorUI(this); _ui.IndicatorUIUpdatedEvent += new BasicIndicatorUI.IndicatorUIUpdatedDelegate(_ui_IndicatorUIUpdatedEvent); } void _ui_IndicatorUIUpdatedEvent(BasicIndicatorUI ui) { this.Calculate(); } public bool SetInputParameters(object[] parameters) { lock (this) { if (_intputParameters.Count != parameters.Length) { return false; } for (int i = 0; i < parameters.Length; i++) { if (_intputParameters[i].ParameterType != parameters[i].GetType()) { return false; } } _inputParametersValues = parameters; } return true; } // Parameters format of TaLibCore functions. //int startIdx, - mandatory //int endIdx, - mandatory //double[] inReal[added 0/1] or/and inOpen or/and inLow or/and inHigh or/and inClose //int/double optIn[NAME] or/and another one or none - parameters //out int outBegIdx, //out int outNBElement, //double/int[] out[Real/Integer] and or another one // Example: //TicTacTec.TA.Library.Core.RetCode code = TicTacTec.TA.Library.Core.Sma(0, indecesCount - 1, _closeResultValues, Period, out beginIndex, out number, ma); } public static FxpaIndicator CreateInstance(MethodInfo methodInfo, string description, bool? isTradeable, bool? isScaledToQuotes) { //if (methodInfo == null) //{ // return null; //} //Type returnType = methodInfo.ReturnType; //if (returnType != typeof(TicTacTec.TA.Library.Core.RetCode)) //{ // return null; //} //ParameterInfo[] parameters = methodInfo.GetParameters(); //if (parameters.Length < 5) //{ // return null; //} //int index = 0; //if (parameters[index].ParameterType != typeof(int) || // parameters[index].Name != "startIdx") //{ // return null; //} //index++; //if (parameters[index].ParameterType != typeof(int) || // parameters[index].Name != "endIdx") //{ // return null; //} //index++; //List<ParameterInfo> indicatorParameters = new List<ParameterInfo>(); //while (parameters.Length > index && parameters[index].ParameterType == typeof(double[])) //{ // if (parameters[index].Name != "inReal" && // parameters[index].Name != "inReal0" && // parameters[index].Name != "inReal1" && // parameters[index].Name != "inHigh" && // parameters[index].Name != "inLow" && // parameters[index].Name != "inOpen" && // parameters[index].Name != "inClose" && // parameters[index].Name != "inVolume" // ) // { // return null; // } // indicatorParameters.Add(parameters[index]); // index++; //} //// optIn parameters //List<ParameterInfo> indicatorInputParameters = new List<ParameterInfo>(); //while(parameters.Length > index && parameters[index].Name.StartsWith("optIn")) //{ // if (parameters[index].ParameterType == typeof(int) || // parameters[index].ParameterType != typeof(double) || // parameters[index].ParameterType != typeof(TicTacTec.TA.Library.Core.MAType)) // { // indicatorInputParameters.Add(parameters[index]); // } // else // {// Invalid type. // return null; // } // index++; //} //if (parameters.Length <= index || parameters[index].IsOut == false // || parameters[index].Name != "outBegIdx") //{ // return null; //} //index++; //if (parameters.Length <= index || parameters[index].IsOut == false // || parameters[index].Name != "outNBElement") //{ // return null; //} //index++; //List<ParameterInfo> indicatorOutputArrayParameters = new List<ParameterInfo>(); //List<string> indicatorOutputArrayParametersNames = new List<string>(); //while (parameters.Length > index) //{ // if (parameters[index].Name.StartsWith("out") == false) // { // return null; // } // if (parameters[index].ParameterType == typeof(double[]) // || parameters[index].ParameterType == typeof(int[])) // { // indicatorOutputArrayParametersNames.Add(parameters[index].Name); // indicatorOutputArrayParameters.Add(parameters[index]); // } // else // { // return null; // } // index++; //} //if (parameters.Length != index) //{// Parameters left unknown. // return null; //} ParameterInfo[] parameters = methodInfo.GetParameters(); List<ParameterInfo> indicatorOutputArrayParameters = new List<ParameterInfo>(); List<string> indicatorOutputArrayParametersNames = new List<string>(); List<ParameterInfo> indicatorInputParameters = new List<ParameterInfo>(); List<ParameterInfo> indicatorParameters = new List<ParameterInfo>(); indicatorInputParameters.Add(parameters[1]); indicatorParameters.Add(parameters[0]); indicatorOutputArrayParameters.Add(parameters[2]); indicatorOutputArrayParametersNames.Add(parameters[2].Name); FxpaIndicator indicator = new FxpaIndicator(methodInfo.Name, description, isTradeable, isScaledToQuotes, indicatorOutputArrayParametersNames.ToArray()); indicator._inputDefaultArrayParameters.AddRange(indicatorParameters); indicator._outputArraysParameters.AddRange(indicatorOutputArrayParameters); indicator._intputParameters.AddRange(indicatorInputParameters); indicator._methodInfo = methodInfo; return indicator; } static Double[] method(Double[] inReal) { Double[] outReal = inReal; return outReal; } double[] GetInputArrayValues(string valueArrayTypeName, int startingIndex, int indexCount) { if (valueArrayTypeName == "inLow") { return DataProvider.GetDataValues(BarData.DataValueSourceEnum.Low, startingIndex, indexCount); } else if (valueArrayTypeName == "inHigh") { return DataProvider.GetDataValues(BarData.DataValueSourceEnum.High, startingIndex, indexCount); } else if (valueArrayTypeName == "inOpen") { return DataProvider.GetDataValues(BarData.DataValueSourceEnum.Open, startingIndex, indexCount); } else if (valueArrayTypeName == "inClose") { return DataProvider.GetDataValues(BarData.DataValueSourceEnum.Close, startingIndex, indexCount); } else if (valueArrayTypeName == "inVolume") { return DataProvider.GetDataValues(BarData.DataValueSourceEnum.Volume, startingIndex, indexCount); } else if (valueArrayTypeName == "inReal") { if (_realInputArraySource.HasValue) { return DataProvider.GetDataValues(_realInputArraySource.Value, startingIndex, indexCount); } else { Console.WriteLine("inReal parameter not assigned."); } } else if (valueArrayTypeName == "inReal0") { if (_realInputArraySource.HasValue) { return DataProvider.GetDataValues(_realInputArraySource.Value, startingIndex, indexCount); } else { Console.WriteLine("inReal parameter not assigned."); } } else if (valueArrayTypeName == "inReal1") { if (_real1InputArraySource.HasValue) { return DataProvider.GetDataValues(_real1InputArraySource.Value, startingIndex, indexCount); } else { Console.WriteLine("inReal parameter not assigned."); } } Console.WriteLine("Class operation logic error."); return null; } protected override void OnCalculate(int startingIndex, int indexCount) { // Format of a TA method. //int startIdx, - mandatory //int endIdx, - mandatory //double[] inReal[added 0/1] or/and inOpen or/and inLow or/and inHigh or/and inClose //int/double optIn[NAME] or/and another one or none - parameters //out int outBegIdx, //out int outNBElement, //double/int[] out[Real/Integer] and or another one // Example: //TicTacTec.TA.Library.Core.RetCode code = TicTacTec.TA.Library.Core.Sma(0, indecesCount - 1, _closeResultValues, Period, out beginIndex, out number, ma); } // Consider the result returned. List<object> parameters = new List<object>(); parameters.Add(0); parameters.Add(indexCount - 1); int outBeginIdxPosition = 0; lock (this) { foreach (ParameterInfo info in _inputDefaultArrayParameters) { // parameters.Add(GetInputArrayValues(info.Name, startingIndex, indexCount)); parameters.Add(DataProvider.DataUnits); } foreach (object parameter in _inputParametersValues) { parameters.Add(parameter); } outBeginIdxPosition = parameters.Count; // outBeginIdx parameters.Add(0); // outNBElemenet parameters.Add(DataProvider.DataUnits.Count); foreach (ParameterInfo info in _outputArraysParameters) { if (info.ParameterType == typeof(double[])) {// Passed arrays must be prepared to the proper size. double[] array = new double[indexCount]; parameters.Add(array); } else if (info.ParameterType == typeof(int[])) {// Passed arrays must be prepared to the proper size. int[] array = new int[indexCount]; parameters.Add(array); } else { Console.WriteLine("Class operation logic error."); } } // This is how the normal call looks like. //TicTacTec.TA.Library.Core.Adx((int)parameters[0], (int)parameters[1], (double[])parameters[2], // (double[])parameters[3], (double[])parameters[4], (int)parameters[5], // out outBeginIdx, out outNBElemenet, (double[])parameters[8]); } object[] parametersArray = parameters.ToArray(); //TicTacTec.TA.Library.Core.RetCode code = (TicTacTec.TA.Library.Core.RetCode) // _methodInfo.Invoke(null, parametersArray); FxRSI fxi = new FxRSI(); int k = 0; foreach (BarData bar in (List<BarData>)parameters[2]) { ((double[])parameters[parameters.Count - 1])[k] = fxi.handleFullCandle(bar); k++; } lock (this) { int outBeginIdx = (int)parametersArray[outBeginIdxPosition]; int outNBElemenet = (int)parametersArray[outBeginIdxPosition + 1]; for (int i = 0; i < _outputArraysParameters.Count; i++) { int index = outBeginIdxPosition + 2 + i; if (parametersArray[index].GetType() == typeof(double[])) { Results.SetResultSetValues(_outputArraysParameters[i].Name, outBeginIdx, outNBElemenet, (double[])parametersArray[index]); } else if (parametersArray[index].GetType() == typeof(int[])) {// Valid scenario, implement. //SystemMonitor.NotImplementedCritical(); Results.SetResultSetValues(_outputArraysParameters[i].Name, outBeginIdx, outNBElemenet, GeneralHelper.IntsToDoubles((int[])parametersArray[index])); } } } } /// <summary> /// Does not include results. /// </summary> /// <returns></returns> public override BasicIndicator SimpleClone() { Console.WriteLine((this.DataProvider != null).ToString()); FxpaIndicator newIndicator = CreateInstance(_methodInfo, Description, Tradeable, ScaledToQuotes); newIndicator._inputDefaultArrayParameters = new List<ParameterInfo>(_inputDefaultArrayParameters); newIndicator._intputParameters = new List<ParameterInfo>(_intputParameters); newIndicator._outputArraysParameters = new List<ParameterInfo>(_outputArraysParameters); newIndicator._inputParametersValues = (object[])_inputParametersValues.Clone(); newIndicator._realInputArraySource = _realInputArraySource; newIndicator._real1InputArraySource = _real1InputArraySource; //GenericTALibIndicator newIndicator = (GenericTALibIndicator)this.MemberwiseClone(); //// Still pointing to old indicator UI, deatach. //newIndicator._ui.IndicatorUIUpdatedEvent -= new PlatformIndicatorUI.IndicatorUIUpdatedDelegate(_ui_IndicatorUIUpdatedEvent); // Create and attach. //newIndicator._ui = new GenericTALibIndicatorUI(newIndicator); //newIndicator._ui.IndicatorUIUpdatedEvent += new PlatformIndicatorUI.IndicatorUIUpdatedDelegate(_ui_IndicatorUIUpdatedEvent); //lock (this) //{ // List<string> resultSetsNames = new List<string>(); // foreach (IndicatorResultSet set in _results.ResultSets) // { // resultSetsNames.Add(set.Name); // } // newIndicator._results = new IndicatorResults(newIndicator, resultSetsNames.ToArray()); //} return newIndicator; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; using Microsoft.Rest.Azure; using Models; /// <summary> /// SubscriptionInCredentialsOperations operations. /// </summary> internal partial class SubscriptionInCredentialsOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInCredentialsOperations { /// <summary> /// Initializes a new instance of the SubscriptionInCredentialsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubscriptionInCredentialsOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// POST method with subscriptionId modeled in credentials. Set the /// credential subscriptionId to '1234-5678-9012-3456' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PostMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PostMethodGlobalValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/azurespecials/subscriptionId/method/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString(); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// POST method with subscriptionId modeled in credentials. Set the /// credential subscriptionId to null, and client-side validation should /// prevent you from making this call /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PostMethodGlobalNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PostMethodGlobalNull", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/azurespecials/subscriptionId/method/string/none/path/global/null/{subscriptionId}").ToString(); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// POST method with subscriptionId modeled in credentials. Set the /// credential subscriptionId to '1234-5678-9012-3456' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PostMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PostMethodGlobalNotProvidedValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/azurespecials/subscriptionId/method/string/none/path/globalNotProvided/1234-5678-9012-3456/{subscriptionId}").ToString(); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// POST method with subscriptionId modeled in credentials. Set the /// credential subscriptionId to '1234-5678-9012-3456' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PostPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PostPathGlobalValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/azurespecials/subscriptionId/path/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString(); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// POST method with subscriptionId modeled in credentials. Set the /// credential subscriptionId to '1234-5678-9012-3456' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PostSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PostSwaggerGlobalValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/azurespecials/subscriptionId/swagger/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString(); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Security.Permissions; using System.Windows.Forms; using XenCenterLib; using Message = System.Windows.Forms.Message; using System.Runtime.InteropServices; namespace XenAdmin.Controls { public partial class SnapshotTreeView : ListView { private const int straightLineLength = 8; private SnapshotIcon root; //We need this fake thing to make the scrollbars work with the customdrawdate. private ListViewItem whiteIcon = new ListViewItem(); private Color linkLineColor = SystemColors.ControlDark; private float linkLineWidth = 2.0f; private int hGap = 50; private int vGap = 20; private readonly CustomLineCap linkLineArrow = new AdjustableArrowCap(4f, 4f, true); #region Properties [Browsable(true), Category("Appearance"), Description("Color used to draw connecting lines")] [DefaultValue(typeof(Color), "ControlDark")] public Color LinkLineColor { get { return linkLineColor; } set { linkLineColor = value; Invalidate(); } } [Browsable(true), Category("Appearance"), Description("Width of connecting lines")] [DefaultValue(2.0f)] public float LinkLineWidth { get { return linkLineWidth; } set { linkLineWidth = value; Invalidate(); } } [Browsable(true), Category("Appearance"), Description("Horizontal gap between icons")] [DefaultValue(50)] public int HGap { get { return hGap; } set { if (value < 4 * straightLineLength) value = 4 * straightLineLength; hGap = value; PerformLayout(this, "HGap"); } } [Browsable(true), Category("Appearance"), Description("Vertical gap between icons")] [DefaultValue(20)] public int VGap { get { return vGap; } set { if (value < 0) value = 0; vGap = value; PerformLayout(this, "VGap"); } } #endregion private ImageList imageList = new ImageList(); public SnapshotTreeView(IContainer container) { if (container == null) throw new ArgumentNullException("container"); container.Add(this); InitializeComponent(); DoubleBuffered = true; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); base.Items.Add(whiteIcon); //Init image list imageList.ColorDepth = ColorDepth.Depth32Bit; imageList.ImageSize=new Size(32,32); imageList.Images.Add(Properties.Resources._000_HighLightVM_h32bit_32); imageList.Images.Add(Properties.Resources.VMTemplate_h32bit_32); imageList.Images.Add(Properties.Resources.VMTemplate_h32bit_32); imageList.Images.Add(Properties.Resources._000_VMSnapShotDiskOnly_h32bit_32); imageList.Images.Add(Properties.Resources._000_VMSnapshotDiskMemory_h32bit_32); imageList.Images.Add(Properties.Resources._000_ScheduledVMsnapshotDiskOnly_h32bit_32); imageList.Images.Add(Properties.Resources._000_ScheduledVMSnapshotDiskMemory_h32bit_32); imageList.Images.Add(Properties.Resources.SpinningFrame0); imageList.Images.Add(Properties.Resources.SpinningFrame1); imageList.Images.Add(Properties.Resources.SpinningFrame2); imageList.Images.Add(Properties.Resources.SpinningFrame3); imageList.Images.Add(Properties.Resources.SpinningFrame4); imageList.Images.Add(Properties.Resources.SpinningFrame5); imageList.Images.Add(Properties.Resources.SpinningFrame6); imageList.Images.Add(Properties.Resources.SpinningFrame7); this.LargeImageList = imageList; } internal ListViewItem AddSnapshot(SnapshotIcon snapshot) { if (snapshot == null) throw new ArgumentNullException("snapshot"); if (snapshot.Parent != null) { snapshot.Parent.AddChild(snapshot); snapshot.Parent.Invalidate(); } else if (root != null) { throw new InvalidOperationException("Adding a new root!"); } else { root = snapshot; } if (snapshot.ImageIndex == SnapshotIcon.VMImageIndex) { //Sort all the parents of the VM to make the path to the VM the first one. SnapshotIcon current = snapshot; while (current.Parent != null) { if (current.Parent.Children.Count > 1) { int indexCurrent = current.Parent.Children.IndexOf(current); SnapshotIcon temp = current.Parent.Children[0]; current.Parent.Children[0] = current; current.Parent.Children[indexCurrent] = temp; } current.IsInVMBranch = true; current = current.Parent; } } ListViewItem item = Items.Add(snapshot); if (Items.Count == 1) Items.Add(whiteIcon); return item; } public new void Clear() { base.Clear(); RemoveSnapshot(root); } internal void RemoveSnapshot(SnapshotIcon snapshot) { if (snapshot != null && snapshot.Parent != null) { IList<SnapshotIcon> siblings = snapshot.Parent.Children; int pos = siblings.IndexOf(snapshot); siblings.Remove(snapshot); // add our children in our place foreach (SnapshotIcon child in snapshot.Children) { siblings.Insert(pos++, child); child.Parent = snapshot.Parent; } snapshot.Parent.Invalidate(); snapshot.Parent = null; } else { root = null; } } protected override void OnSelectedIndexChanged(EventArgs e) { if (SelectedItems.Count == 1) { SnapshotIcon item = SelectedItems[0] as SnapshotIcon; if (item != null && !item.Selectable) { item.Selected = false; item.Focused = false; } } else if (this.SelectedItems.Count > 1) { foreach (ListViewItem item in SelectedItems) { SnapshotIcon snapItem = item as SnapshotIcon; if (snapItem != null && !snapItem.Selectable) { item.Selected = false; item.Focused = false; } } } base.OnSelectedIndexChanged(e); } protected override void OnMouseUp(MouseEventArgs e) { ListViewItem item = this.HitTest(e.X, e.Y).Item; if (item == null) { ListViewItem item2 = this.HitTest(e.X, e.Y - 23).Item; if (item2 != null) { item2.Selected = true; item2.Focused = true; } else { base.OnMouseUp(new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y - 23, e.Delta)); return; } } base.OnMouseUp(e); } #region Layout protected override void OnLayout(LayoutEventArgs levent) { if (root != null && this.Parent != null) { //This is needed to maximize and minimize properly, there is some issue in the ListView Control Win32.POINT pt = new Win32.POINT(); IntPtr hResult = SendMessage(Handle, LVM_GETORIGIN, IntPtr.Zero, ref pt); origin = pt; root.InvalidateAll(); int x = Math.Max(this.HGap, this.Size.Width / 2 - root.SubtreeWidth / 2); int y = Math.Max(this.VGap, this.Size.Height / 2 - root.SubtreeHeight / 2); PositionSnapshots(root, x, y); Invalidate(); whiteIcon.Position = new Point(x + origin.X, y + root.SubtreeHeight - 20 + origin.Y); } } protected override void OnParentChanged(EventArgs e) { //We need to cancel the parent changes when we change to the other view } private void PositionSnapshots(SnapshotIcon icon, int x, int y) { try { Size iconSize = icon.DefaultSize; Point newPoint = new Point(x, y + icon.CentreHeight - iconSize.Height / 2); icon.Position = new Point(newPoint.X + origin.X, newPoint.Y + origin.Y); x += iconSize.Width + HGap; for (int i = 0; i < icon.Children.Count; i++) { SnapshotIcon child = icon.Children[i]; PositionSnapshots(child, x, y); y += child.SubtreeHeight; } } catch (Exception) { // Debugger.Break(); } } public const int LVM_GETORIGIN = 0x1000 + 41; private Win32.POINT origin = new Win32.POINT(); [DllImport("user32.dll")] internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref Win32.POINT pt); #endregion #region Drawing private bool m_empty = false; [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { const int WM_HSCROLL = 0x0114; const int WM_VSCROLL = 0x0115; const int WM_MOUSEWHEEL = 0x020A; const int WM_PAINT = 0x000F; base.WndProc(ref m); if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL || (m.Msg == WM_MOUSEWHEEL && (IsVerticalScrollBarVisible(this) || IsHorizontalScrollBarVisible(this)))) { Invalidate(); } if (m.Msg == WM_PAINT) { Graphics gg = CreateGraphics(); if (this.Items.Count == 0) { m_empty = true; Graphics g = CreateGraphics(); string text = Messages.SNAPSHOTS_EMPTY; SizeF proposedSize = g.MeasureString(text, Font, 275); float x = this.Width / 2 - proposedSize.Width / 2; float y = this.Height / 2 - proposedSize.Height / 2; RectangleF rect = new RectangleF(x, y, proposedSize.Width, proposedSize.Height); using (var brush = new SolidBrush(BackColor)) g.FillRectangle(brush, rect); g.DrawString(text, Font, Brushes.Black, rect); } } else if (m_empty && this.Items.Count > 0) { m_empty = false; this.Invalidate(); } } private const int WS_HSCROLL = 0x100000; private const int WS_VSCROLL = 0x200000; private const int GWL_STYLE = (-16); [System.Runtime.InteropServices.DllImport("user32", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern int GetWindowLong(IntPtr hwnd, int nIndex); internal static bool IsVerticalScrollBarVisible(Control ctrl) { if (!ctrl.IsHandleCreated) return false; return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_VSCROLL) != 0; } internal static bool IsHorizontalScrollBarVisible(Control ctrl) { if (!ctrl.IsHandleCreated) return false; return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_HSCROLL) != 0; } private void SnapshotTreeView_DrawItem(object sender, DrawListViewItemEventArgs e) { if (this.Parent != null) { e.DrawDefault = true; SnapshotIcon icon = e.Item as SnapshotIcon; if (icon == null) return; DrawDate(e, icon, false); if (icon.Parent != null) PaintLine(e.Graphics, icon.Parent, icon, icon.IsInVMBranch); for (int i = 0; i < icon.Children.Count; i++) { SnapshotIcon child = icon.Children[i]; PaintLine(e.Graphics, icon, child, child.IsInVMBranch); } } } public void DrawRoundRect(Graphics g, Brush b, float x, float y, float width, float height, float radius) { GraphicsPath gp = new GraphicsPath(); gp.AddLine(x + radius, y, x + width - (radius * 2), y); // Line gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner gp.CloseFigure(); g.FillPath(b, gp); } private void DrawDate(DrawListViewItemEventArgs e, SnapshotIcon icon, bool background) { StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; //Time int timeX = e.Bounds.X; int timeY = e.Bounds.Y + e.Bounds.Height; Size proposedSizeName = new Size(e.Bounds.Width, Int32.MaxValue); Size timeSize = TextRenderer.MeasureText(e.Graphics, icon.LabelCreationTime, new Font(this.Font.FontFamily, this.Font.Size - 1), proposedSizeName, TextFormatFlags.WordBreak); timeSize = new Size(e.Bounds.Width, timeSize.Height); Rectangle timeRect = new Rectangle(new Point(timeX, timeY), timeSize); if (background) { e.Graphics.FillRectangle(Brushes.GreenYellow, timeRect); } e.Graphics.DrawString(icon.LabelCreationTime, new Font(this.Font.FontFamily, this.Font.Size - 1), Brushes.Black, timeRect, stringFormat); } private void PaintLine(Graphics g, SnapshotIcon icon, SnapshotIcon child, bool highlight) { if (child.Index == -1) return; try { Rectangle leftItemBounds = icon.GetBounds(ItemBoundsPortion.Entire); Rectangle rightItemBounds = child.GetBounds(ItemBoundsPortion.Entire); leftItemBounds.Size = icon.DefaultSize; rightItemBounds.Size = child.DefaultSize; int left = leftItemBounds.Right + 6; int right = rightItemBounds.Left; int mid = (left + right) / 2; Point start = new Point(left, (leftItemBounds.Bottom + leftItemBounds.Top) / 2); Point end = new Point(right, (rightItemBounds.Top + rightItemBounds.Bottom) / 2); Point curveStart = start; curveStart.Offset(straightLineLength, 0); Point curveEnd = end; curveEnd.Offset(-straightLineLength, 0); Point control1 = new Point(mid + straightLineLength, start.Y); Point control2 = new Point(mid - straightLineLength, end.Y); Color lineColor = LinkLineColor; float lineWidth = LinkLineWidth; if (highlight) { lineColor = Color.ForestGreen; lineWidth = 2.5f; } using (Pen p = new Pen(lineColor, lineWidth)) { p.SetLineCap(LineCap.Round, LineCap.Custom, DashCap.Flat); p.CustomEndCap = linkLineArrow; g.SmoothingMode = SmoothingMode.AntiAlias; GraphicsPath path = new GraphicsPath(); path.AddLine(start, curveStart); path.AddBezier(curveStart, control1, control2, curveEnd); path.AddLine(curveEnd, end); g.DrawPath(p, path); } } catch (Exception) { //Debugger.Break(); } } #endregion private string _spinningMessage = ""; public string SpinningMessage { get { return _spinningMessage; } } internal void ChangeVMToSpinning(bool p, string message) { _spinningMessage = message; foreach (var item in Items) { if (item is SnapshotIcon snapshotIcon && (snapshotIcon.ImageIndex == SnapshotIcon.VMImageIndex || snapshotIcon.ImageIndex > SnapshotIcon.UnknownImage)) { snapshotIcon.ChangeSpinningIcon(p, _spinningMessage); return; } } } } internal class SnapshotIcon : ListViewItem { public const int VMImageIndex = 0; public const int Template = 1; public const int CustomTemplate = 2; public const int DiskSnapshot = 3; public const int DiskAndMemorySnapshot = 4; public const int ScheduledDiskSnapshot = 5; public const int ScheduledDiskMemorySnapshot = 6; public const int UnknownImage = 6; private SnapshotIcon parent; private readonly SnapshotTreeView treeView; private readonly List<SnapshotIcon> children = new List<SnapshotIcon>(); private readonly string _name; private readonly string _creationTime; public Size DefaultSize = new Size(70, 64); private Timer spinningTimer = new Timer(); #region Cached dimensions private int subtreeWidth; private int subtreeHeight; private int subtreeWeight; private int centreHeight; #endregion #region Properties public string LabelCreationTime { get { return _creationTime; } } public string LabelName { get { return _name; } } internal SnapshotIcon Parent { get { return parent; } set { parent = value; } } internal IList<SnapshotIcon> Children { get { return children; } } internal bool Selectable { get { // It's selectable if it's a snapshot; otherwise not return ImageIndex == DiskSnapshot || ImageIndex == DiskAndMemorySnapshot || ImageIndex == ScheduledDiskSnapshot || ImageIndex == ScheduledDiskMemorySnapshot; } } #endregion public SnapshotIcon(string name, string createTime, SnapshotIcon parent, SnapshotTreeView treeView, int imageIndex) : base(name.Ellipsise(35)) { this._name = name.Ellipsise(35); this._creationTime = createTime; this.parent = parent; this.treeView = treeView; this.UseItemStyleForSubItems = false; this.ToolTipText = String.Format("{0} {1}", name, createTime); this.ImageIndex = imageIndex; if (imageIndex == SnapshotIcon.VMImageIndex) { spinningTimer.Tick += new EventHandler(timer_Tick); spinningTimer.Interval = 150; } } private int currentSpinningFrame = 7; private void timer_Tick(object sender, EventArgs e) { this.ImageIndex = currentSpinningFrame <= 14 ? currentSpinningFrame++ : currentSpinningFrame = 7; } internal void ChangeSpinningIcon(bool enabled, string message) { if (this.ImageIndex > UnknownImage || this.ImageIndex == VMImageIndex) { this.ImageIndex = enabled ? 7 : VMImageIndex; this.Text = enabled ? message : Messages.NOW; if (enabled) spinningTimer.Start(); else spinningTimer.Stop(); } } private bool _isInVMBranch = false; public bool IsInVMBranch { get { return _isInVMBranch; } set { _isInVMBranch = value; } } internal void AddChild(SnapshotIcon icon) { children.Add(icon); Invalidate(); } public override void Remove() { SnapshotTreeView view = (SnapshotTreeView)ListView; view.RemoveSnapshot(this); base.Remove(); view.PerformLayout(); } /// <summary> /// Causes the item and its ancestors to forget their cached dimensions. /// </summary> public void Invalidate() { subtreeWeight = 0; subtreeHeight = 0; centreHeight = 0; subtreeWidth = 0; if (parent != null) parent.Invalidate(); } /// <summary> /// Causes the item and all its descendents to forget their cached dimensions. /// </summary> public void InvalidateAll() { subtreeWeight = 0; subtreeHeight = 0; centreHeight = 0; subtreeWidth = 0; foreach (SnapshotIcon icon in children) { icon.InvalidateAll(); } } #region Layout/Dimensions public int SubtreeWidth { get { if (subtreeWidth == 0) { int currentWidth = this.DefaultSize.Width + treeView.HGap; if (children.Count > 0) { int maxWidth = 0; foreach (SnapshotIcon icon in children) { int childSubtree = icon.SubtreeWidth; if (currentWidth + childSubtree > maxWidth) maxWidth = currentWidth + childSubtree; } if (maxWidth > currentWidth) subtreeWidth = maxWidth; else subtreeWidth = currentWidth; } } return subtreeWidth; } } /// <summary> /// Height of the subtree rooted at this node, including the margin above and below. /// </summary> public int SubtreeHeight { get { if (subtreeHeight == 0) { subtreeHeight = this.DefaultSize.Height + treeView.VGap; if (children.Count > 0) { int height = 0; foreach (SnapshotIcon icon in children) { height += icon.SubtreeHeight; // recurse } if (height > subtreeHeight) subtreeHeight = height; } } return subtreeHeight; } } /// <summary> /// The number of items rooted at this node (including the node itself) /// </summary> public int SubtreeWeight { get { if (subtreeWeight == 0) { int weight = 1; // this foreach (SnapshotIcon icon in children) { weight += icon.SubtreeWeight; } subtreeWeight = weight; } return subtreeWeight; } } /// <summary> /// The weighted mean centre height for this node, within the range 0 - SubtreeHeight /// </summary> public int CentreHeight { get { if (centreHeight == 0) { int top = 0; int totalWeight = 0; int weightedCentre = 0; foreach (SnapshotIcon icon in children) { int iconWeight = icon.SubtreeWeight; totalWeight += iconWeight; weightedCentre += iconWeight * (top + icon.CentreHeight); // recurse top += icon.SubtreeHeight; } if (totalWeight > 0) centreHeight = weightedCentre / totalWeight; else centreHeight = (top + SubtreeHeight) / 2; } return centreHeight; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Internal.TypeSystem; using Internal.IL; namespace Internal.IL { // // Corresponds to "I.12.3.2.1 The evaluation stack" in ECMA spec // internal enum StackValueKind { /// <summary>An unknow type.</summary> Unknown, /// <summary>Any signed or unsigned integer values that can be represented as a 32-bit entity.</summary> Int32, /// <summary>Any signed or unsigned integer values that can be represented as a 64-bit entity.</summary> Int64, /// <summary>Underlying platform pointer type represented as an integer of the appropriate size.</summary> NativeInt, /// <summary>Any float value.</summary> Float, /// <summary>A managed pointer.</summary> ByRef, /// <summary>An object reference.</summary> ObjRef, /// <summary>A value type which is not any of the primitive one.</summary> ValueType } internal partial class ILImporter { private BasicBlock[] _basicBlocks; // Maps IL offset to basic block private BasicBlock _currentBasicBlock; private int _currentOffset; private BasicBlock _pendingBasicBlocks; // // IL stream reading // private byte ReadILByte() { return _ilBytes[_currentOffset++]; } private UInt16 ReadILUInt16() { UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } private UInt32 ReadILUInt32() { UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } private int ReadILToken() { return (int)ReadILUInt32(); } private ulong ReadILUInt64() { ulong value = ReadILUInt32(); value |= (((ulong)ReadILUInt32()) << 32); return value; } private unsafe float ReadILFloat() { uint value = ReadILUInt32(); return *(float*)(&value); } private unsafe double ReadILDouble() { ulong value = ReadILUInt64(); return *(double*)(&value); } private void SkipIL(int bytes) { _currentOffset += bytes; } // // Basic block identification // private void FindBasicBlocks() { _basicBlocks = new BasicBlock[_ilBytes.Length]; CreateBasicBlock(0); FindJumpTargets(); FindEHTargets(); } private BasicBlock CreateBasicBlock(int offset) { BasicBlock basicBlock = _basicBlocks[offset]; if (basicBlock == null) { basicBlock = new BasicBlock() { StartOffset = offset }; _basicBlocks[offset] = basicBlock; } return basicBlock; } private void FindJumpTargets() { _currentOffset = 0; while (_currentOffset < _ilBytes.Length) { MarkInstructionBoundary(); ILOpcode opCode = (ILOpcode)ReadILByte(); again: switch (opCode) { case ILOpcode.ldarg_s: case ILOpcode.ldarga_s: case ILOpcode.starg_s: case ILOpcode.ldloc_s: case ILOpcode.ldloca_s: case ILOpcode.stloc_s: case ILOpcode.ldc_i4_s: case ILOpcode.unaligned: SkipIL(1); break; case ILOpcode.ldarg: case ILOpcode.ldarga: case ILOpcode.starg: case ILOpcode.ldloc: case ILOpcode.ldloca: case ILOpcode.stloc: SkipIL(2); break; case ILOpcode.ldc_i4: case ILOpcode.ldc_r4: SkipIL(4); break; case ILOpcode.ldc_i8: case ILOpcode.ldc_r8: SkipIL(8); break; case ILOpcode.jmp: case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: case ILOpcode.cpobj: case ILOpcode.ldobj: case ILOpcode.ldstr: case ILOpcode.newobj: case ILOpcode.castclass: case ILOpcode.isinst: case ILOpcode.unbox: case ILOpcode.ldfld: case ILOpcode.ldflda: case ILOpcode.stfld: case ILOpcode.ldsfld: case ILOpcode.ldsflda: case ILOpcode.stsfld: case ILOpcode.stobj: case ILOpcode.box: case ILOpcode.newarr: case ILOpcode.ldelema: case ILOpcode.ldelem: case ILOpcode.stelem: case ILOpcode.unbox_any: case ILOpcode.refanyval: case ILOpcode.mkrefany: case ILOpcode.ldtoken: case ILOpcode.ldftn: case ILOpcode.ldvirtftn: case ILOpcode.initobj: case ILOpcode.constrained: case ILOpcode.sizeof_: SkipIL(4); break; case ILOpcode.prefix1: opCode = (ILOpcode)(0x100 + ReadILByte()); goto again; case ILOpcode.br_s: case ILOpcode.leave_s: { int delta = (sbyte)ReadILByte(); CreateBasicBlock(_currentOffset + delta); } break; case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: { int delta = (sbyte)ReadILByte(); CreateBasicBlock(_currentOffset + delta); CreateBasicBlock(_currentOffset); } break; case ILOpcode.br: case ILOpcode.leave: { int delta = (int)ReadILUInt32(); CreateBasicBlock(_currentOffset + delta); } break; case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: { int delta = (int)ReadILUInt32(); CreateBasicBlock(_currentOffset + delta); CreateBasicBlock(_currentOffset); } break; case ILOpcode.switch_: { uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); for (uint i = 0; i < count; i++) { int delta = (int)ReadILUInt32(); CreateBasicBlock(jmpBase + delta); } CreateBasicBlock(_currentOffset); } break; default: continue; } } } private void FindEHTargets() { for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; CreateBasicBlock(r.ILRegion.TryOffset).TryStart = true; if (r.ILRegion.Kind == ILExceptionRegionKind.Filter) CreateBasicBlock(r.ILRegion.FilterOffset).FilterStart = true; CreateBasicBlock(r.ILRegion.HandlerOffset).HandlerStart = true; } } // // Basic block importing // private void ImportBasicBlocks() { _pendingBasicBlocks = _basicBlocks[0]; while (_pendingBasicBlocks != null) { BasicBlock basicBlock = _pendingBasicBlocks; _pendingBasicBlocks = basicBlock.Next; StartImportingBasicBlock(basicBlock); ImportBasicBlock(basicBlock); EndImportingBasicBlock(basicBlock); } } private void MarkBasicBlock(BasicBlock basicBlock) { if (basicBlock.EndOffset == 0) { // Link basicBlock.Next = _pendingBasicBlocks; _pendingBasicBlocks = basicBlock; basicBlock.EndOffset = -1; } } private void ImportBasicBlock(BasicBlock basicBlock) { _currentBasicBlock = basicBlock; _currentOffset = basicBlock.StartOffset; for (;;) { StartImportingInstruction(); ILOpcode opCode = (ILOpcode)ReadILByte(); again: switch (opCode) { case ILOpcode.nop: ImportNop(); break; case ILOpcode.break_: ImportBreak(); break; case ILOpcode.ldarg_0: case ILOpcode.ldarg_1: case ILOpcode.ldarg_2: case ILOpcode.ldarg_3: ImportLoadVar(opCode - ILOpcode.ldarg_0, true); break; case ILOpcode.ldloc_0: case ILOpcode.ldloc_1: case ILOpcode.ldloc_2: case ILOpcode.ldloc_3: ImportLoadVar(opCode - ILOpcode.ldloc_0, false); break; case ILOpcode.stloc_0: case ILOpcode.stloc_1: case ILOpcode.stloc_2: case ILOpcode.stloc_3: ImportStoreVar(opCode - ILOpcode.stloc_0, false); break; case ILOpcode.ldarg_s: ImportLoadVar(ReadILByte(), true); break; case ILOpcode.ldarga_s: ImportAddressOfVar(ReadILByte(), true); break; case ILOpcode.starg_s: ImportStoreVar(ReadILByte(), true); break; case ILOpcode.ldloc_s: ImportLoadVar(ReadILByte(), false); break; case ILOpcode.ldloca_s: ImportAddressOfVar(ReadILByte(), false); break; case ILOpcode.stloc_s: ImportStoreVar(ReadILByte(), false); break; case ILOpcode.ldnull: ImportLoadNull(); break; case ILOpcode.ldc_i4_m1: ImportLoadInt(-1, StackValueKind.Int32); break; case ILOpcode.ldc_i4_0: case ILOpcode.ldc_i4_1: case ILOpcode.ldc_i4_2: case ILOpcode.ldc_i4_3: case ILOpcode.ldc_i4_4: case ILOpcode.ldc_i4_5: case ILOpcode.ldc_i4_6: case ILOpcode.ldc_i4_7: case ILOpcode.ldc_i4_8: ImportLoadInt(opCode - ILOpcode.ldc_i4_0, StackValueKind.Int32); break; case ILOpcode.ldc_i4_s: ImportLoadInt((sbyte)ReadILByte(), StackValueKind.Int32); break; case ILOpcode.ldc_i4: ImportLoadInt((int)ReadILUInt32(), StackValueKind.Int32); break; case ILOpcode.ldc_i8: ImportLoadInt((long)ReadILUInt64(), StackValueKind.Int64); break; case ILOpcode.ldc_r4: ImportLoadFloat(ReadILFloat()); break; case ILOpcode.ldc_r8: ImportLoadFloat(ReadILDouble()); break; case ILOpcode.dup: ImportDup(); break; case ILOpcode.pop: ImportPop(); break; case ILOpcode.jmp: ImportJmp(ReadILToken()); break; case ILOpcode.call: ImportCall(opCode, ReadILToken()); break; case ILOpcode.calli: ImportCalli(ReadILToken()); break; case ILOpcode.ret: ImportReturn(); return; case ILOpcode.br_s: case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: { int delta = (sbyte)ReadILByte(); ImportBranch(opCode + (ILOpcode.br - ILOpcode.br_s), _basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br_s) ? _basicBlocks[_currentOffset] : null); } return; case ILOpcode.br: case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: { int delta = (int)ReadILUInt32(); ImportBranch(opCode, _basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br) ? _basicBlocks[_currentOffset] : null); } return; case ILOpcode.switch_: { uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); int[] jmpDelta = new int[count]; for (uint i = 0; i < count; i++) jmpDelta[i] = (int)ReadILUInt32(); ImportSwitchJump(jmpBase, jmpDelta, _basicBlocks[_currentOffset]); } return; case ILOpcode.ldind_i1: ImportLoadIndirect(WellKnownType.SByte); break; case ILOpcode.ldind_u1: ImportLoadIndirect(WellKnownType.Byte); break; case ILOpcode.ldind_i2: ImportLoadIndirect(WellKnownType.Int16); break; case ILOpcode.ldind_u2: ImportLoadIndirect(WellKnownType.UInt16); break; case ILOpcode.ldind_i4: ImportLoadIndirect(WellKnownType.Int32); break; case ILOpcode.ldind_u4: ImportLoadIndirect(WellKnownType.UInt32); break; case ILOpcode.ldind_i8: ImportLoadIndirect(WellKnownType.Int64); break; case ILOpcode.ldind_i: ImportLoadIndirect(WellKnownType.IntPtr); break; case ILOpcode.ldind_r4: ImportLoadIndirect(WellKnownType.Single); break; case ILOpcode.ldind_r8: ImportLoadIndirect(WellKnownType.Double); break; case ILOpcode.ldind_ref: ImportLoadIndirect(null); break; case ILOpcode.stind_ref: ImportStoreIndirect(null); break; case ILOpcode.stind_i1: ImportStoreIndirect(WellKnownType.SByte); break; case ILOpcode.stind_i2: ImportStoreIndirect(WellKnownType.Int16); break; case ILOpcode.stind_i4: ImportStoreIndirect(WellKnownType.Int32); break; case ILOpcode.stind_i8: ImportStoreIndirect(WellKnownType.Int64); break; case ILOpcode.stind_r4: ImportStoreIndirect(WellKnownType.Single); break; case ILOpcode.stind_r8: ImportStoreIndirect(WellKnownType.Double); break; case ILOpcode.add: case ILOpcode.sub: case ILOpcode.mul: case ILOpcode.div: case ILOpcode.div_un: case ILOpcode.rem: case ILOpcode.rem_un: case ILOpcode.and: case ILOpcode.or: case ILOpcode.xor: ImportBinaryOperation(opCode); break; case ILOpcode.shl: case ILOpcode.shr: case ILOpcode.shr_un: ImportShiftOperation(opCode); break; case ILOpcode.neg: case ILOpcode.not: ImportUnaryOperation(opCode); break; case ILOpcode.conv_i1: ImportConvert(WellKnownType.Byte, false, false); break; case ILOpcode.conv_i2: ImportConvert(WellKnownType.Int16, false, false); break; case ILOpcode.conv_i4: ImportConvert(WellKnownType.Int32, false, false); break; case ILOpcode.conv_i8: ImportConvert(WellKnownType.Int64, false, false); break; case ILOpcode.conv_r4: ImportConvert(WellKnownType.Single, false, false); break; case ILOpcode.conv_r8: ImportConvert(WellKnownType.Double, false, false); break; case ILOpcode.conv_u4: ImportConvert(WellKnownType.UInt32, false, false); break; case ILOpcode.conv_u8: ImportConvert(WellKnownType.UInt64, false, false); break; case ILOpcode.callvirt: ImportCall(opCode, ReadILToken()); break; case ILOpcode.cpobj: ImportCpOpj(ReadILToken()); break; case ILOpcode.ldobj: ImportLoadIndirect(ReadILToken()); break; case ILOpcode.ldstr: ImportLoadString(ReadILToken()); break; case ILOpcode.newobj: ImportCall(opCode, ReadILToken()); break; case ILOpcode.castclass: case ILOpcode.isinst: ImportCasting(opCode, ReadILToken()); break; case ILOpcode.conv_r_un: ImportConvert(WellKnownType.Double, false, true); break; case ILOpcode.unbox: ImportUnbox(ReadILToken(), opCode); break; case ILOpcode.throw_: ImportThrow(); return; case ILOpcode.ldfld: ImportLoadField(ReadILToken(), false); break; case ILOpcode.ldflda: ImportAddressOfField(ReadILToken(), false); break; case ILOpcode.stfld: ImportStoreField(ReadILToken(), false); break; case ILOpcode.ldsfld: ImportLoadField(ReadILToken(), true); break; case ILOpcode.ldsflda: ImportAddressOfField(ReadILToken(), true); break; case ILOpcode.stsfld: ImportStoreField(ReadILToken(), true); break; case ILOpcode.stobj: ImportStoreIndirect(ReadILToken()); break; case ILOpcode.conv_ovf_i1_un: ImportConvert(WellKnownType.SByte, true, true); break; case ILOpcode.conv_ovf_i2_un: ImportConvert(WellKnownType.Int16, true, true); break; case ILOpcode.conv_ovf_i4_un: ImportConvert(WellKnownType.Int32, true, true); break; case ILOpcode.conv_ovf_i8_un: ImportConvert(WellKnownType.Int64, true, true); break; case ILOpcode.conv_ovf_u1_un: ImportConvert(WellKnownType.Byte, true, true); break; case ILOpcode.conv_ovf_u2_un: ImportConvert(WellKnownType.UInt16, true, true); break; case ILOpcode.conv_ovf_u4_un: ImportConvert(WellKnownType.UInt32, true, true); break; case ILOpcode.conv_ovf_u8_un: ImportConvert(WellKnownType.UInt64, true, true); break; case ILOpcode.conv_ovf_i_un: ImportConvert(WellKnownType.IntPtr, true, true); break; case ILOpcode.conv_ovf_u_un: ImportConvert(WellKnownType.UIntPtr, true, true); break; case ILOpcode.box: ImportBox(ReadILToken()); break; case ILOpcode.newarr: ImportNewArray(ReadILToken()); break; case ILOpcode.ldlen: ImportLoadLength(); break; case ILOpcode.ldelema: ImportAddressOfElement(ReadILToken()); break; case ILOpcode.ldelem_i1: ImportLoadElement(WellKnownType.SByte); break; case ILOpcode.ldelem_u1: ImportLoadElement(WellKnownType.Byte); break; case ILOpcode.ldelem_i2: ImportLoadElement(WellKnownType.Int16); break; case ILOpcode.ldelem_u2: ImportLoadElement(WellKnownType.UInt16); break; case ILOpcode.ldelem_i4: ImportLoadElement(WellKnownType.Int32); break; case ILOpcode.ldelem_u4: ImportLoadElement(WellKnownType.UInt32); break; case ILOpcode.ldelem_i8: ImportLoadElement(WellKnownType.Int64); break; case ILOpcode.ldelem_i: ImportLoadElement(WellKnownType.IntPtr); break; case ILOpcode.ldelem_r4: ImportLoadElement(WellKnownType.Single); break; case ILOpcode.ldelem_r8: ImportLoadElement(WellKnownType.Double); break; case ILOpcode.ldelem_ref: ImportLoadElement(null); break; case ILOpcode.stelem_i: ImportStoreElement(WellKnownType.IntPtr); break; case ILOpcode.stelem_i1: ImportStoreElement(WellKnownType.SByte); break; case ILOpcode.stelem_i2: ImportStoreElement(WellKnownType.Int16); break; case ILOpcode.stelem_i4: ImportStoreElement(WellKnownType.Int32); break; case ILOpcode.stelem_i8: ImportStoreElement(WellKnownType.Int32); break; case ILOpcode.stelem_r4: ImportStoreElement(WellKnownType.Single); break; case ILOpcode.stelem_r8: ImportStoreElement(WellKnownType.Double); break; case ILOpcode.stelem_ref: ImportStoreElement(null); break; case ILOpcode.ldelem: ImportLoadElement(ReadILToken()); break; case ILOpcode.stelem: ImportStoreElement(ReadILToken()); break; case ILOpcode.unbox_any: ImportUnbox(ReadILToken(), opCode); break; case ILOpcode.conv_ovf_i1: ImportConvert(WellKnownType.SByte, true, false); break; case ILOpcode.conv_ovf_u1: ImportConvert(WellKnownType.Byte, true, false); break; case ILOpcode.conv_ovf_i2: ImportConvert(WellKnownType.Int16, true, false); break; case ILOpcode.conv_ovf_u2: ImportConvert(WellKnownType.UInt16, true, false); break; case ILOpcode.conv_ovf_i4: ImportConvert(WellKnownType.Int32, true, false); break; case ILOpcode.conv_ovf_u4: ImportConvert(WellKnownType.UInt32, true, false); break; case ILOpcode.conv_ovf_i8: ImportConvert(WellKnownType.Int64, true, false); break; case ILOpcode.conv_ovf_u8: ImportConvert(WellKnownType.UInt64, true, false); break; case ILOpcode.refanyval: ImportRefAnyVal(ReadILToken()); break; case ILOpcode.ckfinite: ImportCkFinite(); break; case ILOpcode.mkrefany: ImportMkRefAny(ReadILToken()); break; case ILOpcode.ldtoken: ImportLdToken(ReadILToken()); break; case ILOpcode.conv_u2: ImportConvert(WellKnownType.UInt16, false, false); break; case ILOpcode.conv_u1: ImportConvert(WellKnownType.Byte, false, false); break; case ILOpcode.conv_i: ImportConvert(WellKnownType.IntPtr, false, false); break; case ILOpcode.conv_ovf_i: ImportConvert(WellKnownType.IntPtr, true, false); break; case ILOpcode.conv_ovf_u: ImportConvert(WellKnownType.UIntPtr, true, false); break; case ILOpcode.add_ovf: case ILOpcode.add_ovf_un: case ILOpcode.mul_ovf: case ILOpcode.mul_ovf_un: case ILOpcode.sub_ovf: case ILOpcode.sub_ovf_un: ImportBinaryOperation(opCode); break; case ILOpcode.endfinally: //both endfinally and endfault ImportEndFinally(); return; case ILOpcode.leave: { int delta = (int)ReadILUInt32(); ImportLeave(_basicBlocks[_currentOffset + delta]); } return; case ILOpcode.leave_s: { int delta = (sbyte)ReadILByte(); ImportLeave(_basicBlocks[_currentOffset + delta]); } return; case ILOpcode.stind_i: ImportStoreIndirect(WellKnownType.IntPtr); break; case ILOpcode.conv_u: ImportConvert(WellKnownType.UIntPtr, false, false); break; case ILOpcode.prefix1: opCode = (ILOpcode)(0x100 + ReadILByte()); goto again; case ILOpcode.arglist: ImportArgList(); break; case ILOpcode.ceq: case ILOpcode.cgt: case ILOpcode.cgt_un: case ILOpcode.clt: case ILOpcode.clt_un: ImportCompareOperation(opCode); break; case ILOpcode.ldftn: case ILOpcode.ldvirtftn: ImportLdFtn(ReadILToken(), opCode); break; case ILOpcode.ldarg: ImportLoadVar(ReadILUInt16(), true); break; case ILOpcode.ldarga: ImportAddressOfVar(ReadILUInt16(), true); break; case ILOpcode.starg: ImportStoreVar(ReadILUInt16(), true); break; case ILOpcode.ldloc: ImportLoadVar(ReadILUInt16(), false); break; case ILOpcode.ldloca: ImportAddressOfVar(ReadILUInt16(), false); break; case ILOpcode.stloc: ImportStoreVar(ReadILUInt16(), false); break; case ILOpcode.localloc: ImportLocalAlloc(); break; case ILOpcode.endfilter: ImportEndFilter(); return; case ILOpcode.unaligned: ImportUnalignedPrefix(ReadILByte()); continue; case ILOpcode.volatile_: ImportVolatilePrefix(); continue; case ILOpcode.tail: ImportTailPrefix(); continue; case ILOpcode.initobj: ImportInitObj(ReadILToken()); break; case ILOpcode.constrained: ImportConstrainedPrefix(ReadILToken()); continue; case ILOpcode.cpblk: ImportCpBlk(); break; case ILOpcode.initblk: ImportInitBlk(); break; case ILOpcode.no: ImportNoPrefix(ReadILByte()); continue; case ILOpcode.rethrow: ImportRethrow(); return; case ILOpcode.sizeof_: ImportSizeOf(ReadILToken()); break; case ILOpcode.refanytype: ImportRefAnyType(); break; case ILOpcode.readonly_: ImportReadOnlyPrefix(); continue; default: throw new BadImageFormatException("Invalid opcode"); } BasicBlock nextBasicBlock = _basicBlocks[_currentOffset]; if (nextBasicBlock != null) { ImportFallthrough(nextBasicBlock); return; } EndImportingInstruction(); } } private void ImportLoadIndirect(WellKnownType wellKnownType) { ImportLoadIndirect(GetWellKnownType(wellKnownType)); } private void ImportStoreIndirect(WellKnownType wellKnownType) { ImportStoreIndirect(GetWellKnownType(wellKnownType)); } private void ImportLoadElement(WellKnownType wellKnownType) { ImportLoadElement(GetWellKnownType(wellKnownType)); } private void ImportStoreElement(WellKnownType wellKnownType) { ImportStoreElement(GetWellKnownType(wellKnownType)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Threading; using System.Collections.Generic; using System.Diagnostics; #pragma warning disable 618 namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client; [TestFixture] [Category("group4")] [Category("unicast_only")] [Category("generics")] public class OverflowTests : UnitTests { private DistributedSystem m_dsys = null; private const string DSYSName = "OverflowTest"; protected override ClientBase[] GetClients() { return null; } [TestFixtureSetUp] public override void InitTests() { base.InitTests(); m_dsys = CacheHelper.DSYS; } [TestFixtureTearDown] public override void EndTests() { try { CacheHelper.Close(); } finally { base.EndTests(); } } [SetUp] public void StartTest() { CacheHelper.Init(); } [TearDown] public override void EndTest() { CacheHelper.Close(); base.EndTest(); } #region Private functions used by the tests private IRegion<object, object> CreateOverflowRegion(string regionName, string libraryName, string factoryFunctionName) { RegionFactory rf = CacheHelper.DCache.CreateRegionFactory(RegionShortcut.LOCAL); rf.SetCachingEnabled(true); rf.SetLruEntriesLimit(20); rf.SetInitialCapacity(1000); rf.SetDiskPolicy(DiskPolicyType.Overflows); Properties<string, string> sqliteProperties = new Properties<string, string>(); sqliteProperties.Insert("PageSize", "65536"); sqliteProperties.Insert("MaxFileSize", "512000000"); String sqlite_dir = "SqLiteDir" + Process.GetCurrentProcess().Id.ToString(); sqliteProperties.Insert("PersistenceDirectory", sqlite_dir); rf.SetPersistenceManager(libraryName, factoryFunctionName, sqliteProperties); CacheHelper.Init(); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); if ((region != null) && !region.IsDestroyed) { region.GetLocalView().DestroyRegion(); Assert.IsTrue(region.IsDestroyed, "IRegion<object, object> {0} was not destroyed.", regionName); } region = rf.Create<object, object>(regionName); Assert.IsNotNull(region, "IRegion<object, object> was not created."); return region; } // Testing for attibute validation. private void ValidateAttributes(IRegion<object, object> region) { Apache.Geode.Client.RegionAttributes<object, object> regAttr = region.Attributes; int initialCapacity = regAttr.InitialCapacity; Assert.AreEqual(1000, initialCapacity, "Expected initial capacity to be 1000"); Assert.AreEqual(DiskPolicyType.Overflows, regAttr.DiskPolicy, "Expected Action to be overflow to disk"); } private string GetSqLiteFileName(string sqliteDir, string regionName) { return Path.Combine(Directory.GetCurrentDirectory(), sqliteDir, regionName, regionName + ".db"); } private IRegion<object, object> CreateSubRegion(IRegion<object, object> region, string subRegionName, string libraryName, string factoryFunctionName) { AttributesFactory<object, object> attrsFact = new AttributesFactory<object, object>(region.Attributes); Properties<string, string> sqliteProperties = new Properties<string, string>(); sqliteProperties.Insert("PageSize", "65536"); sqliteProperties.Insert("MaxPageCount", "512000000"); String sqlite_dir = "SqLiteDir" + Process.GetCurrentProcess().Id.ToString(); sqliteProperties.Insert("PersistenceDirectory", sqlite_dir); attrsFact.SetPersistenceManager(libraryName, factoryFunctionName, sqliteProperties); IRegion<object, object> subRegion = region.CreateSubRegion(subRegionName, attrsFact.CreateRegionAttributes()); Assert.IsNotNull(subRegion, "Expected region to be non null"); Assert.IsTrue(File.Exists(GetSqLiteFileName(sqlite_dir, subRegionName)), "Persistence file is not present"); DoNput(subRegion, 50); DoNget(subRegion, 50); return subRegion; } private void DoNput(IRegion<object, object> region, int num) { //CacheableString cVal = new CacheableString(new string('A', 1024)); string cVal = new string('A', 1024); for (int i = 0; i < num; i++) { Util.Log("Putting key = key-{0}", i); region["key-" + i.ToString()] = cVal; } } private void DoNget(IRegion<object, object> region, int num) { string cVal; string expectVal = new string('A', 1024); for (int i = 0; i < num; i++) { cVal = region["key-" + i.ToString()] as string; Util.Log("Getting key = key-{0}", i); Assert.IsNotNull(cVal, "Key[key-{0}] not found.", i); Assert.AreEqual(expectVal, cVal, "Did not find the expected value."); } } private bool IsOverflowed(/*IGeodeSerializable*/ object cVal) { //Util.Log("IsOverflowed:: value is: {0}; type is: {1}", cVal.ToString(), cVal.GetType()); return cVal.ToString() == "CacheableToken::OVERFLOWED"; } private void CheckOverflowToken(IRegion<object, object> region, int num, int lruLimit) { //IGeodeSerializable cVal; //ICacheableKey[] cKeys = region.GetKeys(); object cVal; ICollection<object> cKeys = region.GetLocalView().Keys; Assert.AreEqual(num, cKeys.Count, "Number of keys does not match."); int count = 0; foreach (object cKey in cKeys) { RegionEntry<object, object> entry = region.GetEntry(cKey); cVal = entry.Value; if (IsOverflowed(cVal)) { count++; } } Assert.AreEqual(0, count, "Number of overflowed entries should be zero"); } private void CheckNumOfEntries(IRegion<object, object> region, int lruLimit) { //ICollection<object> cVals = region.GetLocalView().Values; ICollection<object> cVals = region.Values; Assert.AreEqual(lruLimit, cVals.Count, "Number of values does not match."); } private void TestGetOp(IRegion<object, object> region, int num) { DoNput(region, num); ICollection<object> cKeys = region.GetLocalView().Keys; object cVal; Assert.AreEqual(num, cKeys.Count, "Number of keys does not match."); foreach (object cKey in cKeys) { RegionEntry<object, object> entry = region.GetEntry(cKey); cVal = entry.Value; if (IsOverflowed(cVal)) { cVal = region[cKey]; Assert.IsFalse(IsOverflowed(cVal), "Overflow token even after a Region.Get"); } } } private void TestEntryDestroy(IRegion<object, object> region) { //ICollection<object> cKeys = region.Keys; ICollection<object> cKeys = region.GetLocalView().Keys; string[] arrKeys = new string[cKeys.Count]; cKeys.CopyTo(arrKeys, 0); for (int i = 50; i < 60; i++) { try { region.GetLocalView().Remove(arrKeys[i]); } catch (Exception ex) { Util.Log("Entry missing for {0}. Exception: {1}", arrKeys[i], ex.ToString()); } } cKeys = region.GetLocalView().Keys; Assert.AreEqual(90, cKeys.Count, "Number of keys is not correct."); } #endregion [Test] public void OverflowPutGet() { IRegion<object, object> region = CreateOverflowRegion("OverFlowRegion", "SqLiteImpl", "createSqLiteInstance"); ValidateAttributes(region); //Console.WriteLine("TEST-2"); // put some values into the cache. DoNput(region, 100); //Console.WriteLine("TEST-2.1 All PUts Donee"); CheckNumOfEntries(region, 100); //Console.WriteLine("TEST-3"); // check whether value get evicted and token gets set as overflow CheckOverflowToken(region, 100, 20); // do some gets... printing what we find in the cache. DoNget(region, 100); TestEntryDestroy(region); TestGetOp(region, 100); //Console.WriteLine("TEST-4"); // test to verify same region repeatedly to ensure that the persistece // files are created and destroyed correctly IRegion<object, object> subRegion; String sqlite_dir = "SqLiteDir" + Process.GetCurrentProcess().Id.ToString(); for (int i = 0; i < 1; i++) { subRegion = CreateSubRegion(region, "SubRegion", "SqLiteImpl", "createSqLiteInstance"); subRegion.DestroyRegion(); Assert.IsTrue(subRegion.IsDestroyed, "Expected region to be destroyed"); Assert.IsFalse(File.Exists(GetSqLiteFileName(sqlite_dir, "SubRegion")), "Persistence file present after region destroy"); } //Console.WriteLine("TEST-5"); } [Test] public void OverflowPutGetManaged() { IRegion<object, object> region = CreateOverflowRegion("OverFlowRegion", "Apache.Geode.Plugins.SqLite", "Apache.Geode.Plugins.SqLite.SqLiteImpl<System.Object,System.Object>.Create"); ValidateAttributes(region); //Console.WriteLine("TEST-2"); // put some values into the cache. DoNput(region, 100); //Console.WriteLine("TEST-2.1 All PUts Donee"); CheckNumOfEntries(region, 100); //Console.WriteLine("TEST-3"); // check whether value get evicted and token gets set as overflow CheckOverflowToken(region, 100, 20); // do some gets... printing what we find in the cache. DoNget(region, 100); TestEntryDestroy(region); TestGetOp(region, 100); //Console.WriteLine("TEST-4"); // test to verify same region repeatedly to ensure that the persistece // files are created and destroyed correctly IRegion<object, object> subRegion; String sqlite_dir = "SqLiteDir" + Process.GetCurrentProcess().Id.ToString(); for (int i = 0; i < 10; i++) { subRegion = CreateSubRegion(region, "SubRegion", "Apache.Geode.Plugins.SqLite", "Apache.Geode.Plugins.SqLite.SqLiteImpl<System.Object,System.Object>.Create"); subRegion.DestroyRegion(); Assert.IsTrue(subRegion.IsDestroyed, "Expected region to be destroyed"); Assert.IsFalse(File.Exists(GetSqLiteFileName(sqlite_dir, "SubRegion")), "Persistence file present after region destroy"); } //Console.WriteLine("TEST-5"); } [Test] public void OverflowPutGetManagedMT() { IRegion<object, object> region = CreateOverflowRegion("OverFlowRegion", "Apache.Geode.Plugins.SqLite", "Apache.Geode.Plugins.SqLite.SqLiteImpl<System.Object,System.Object>.Create"); ValidateAttributes(region); List<Thread> threadsList = new List<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(delegate() { // put some values into the cache. DoNput(region, 100); CheckNumOfEntries(region, 100); // check whether value get evicted and token gets set as overflow CheckOverflowToken(region, 100, 20); // do some gets... printing what we find in the cache. DoNget(region, 100); TestEntryDestroy(region); TestGetOp(region, 100); }); threadsList.Add(t); t.Start(); } for (int i = 0; i < 10; i++) { threadsList[i].Join(); } region.DestroyRegion(); //Console.WriteLine("TEST-5"); } [Test] public void OverflowPutGetManagedSetInstance() { RegionFactory rf = CacheHelper.DCache.CreateRegionFactory(RegionShortcut.LOCAL); rf.SetCachingEnabled(true); rf.SetLruEntriesLimit(20); rf.SetInitialCapacity(1000); rf.SetDiskPolicy(DiskPolicyType.Overflows); Properties<string, string> sqliteProperties = new Properties<string, string>(); sqliteProperties.Insert("PageSize", "65536"); sqliteProperties.Insert("MaxFileSize", "512000000"); String sqlite_dir = "SqLiteDir" + Process.GetCurrentProcess().Id.ToString(); sqliteProperties.Insert("PersistenceDirectory", sqlite_dir); //rf.SetPersistenceManager(new Apache.Geode.Plugins.SQLite.SqLiteImpl<object, object>(), sqliteProperties); rf.SetPersistenceManager("SqLiteImpl", "createSqLiteInstance", sqliteProperties); CacheHelper.Init(); IRegion<object, object> region = CacheHelper.GetRegion<object, object>("OverFlowRegion"); if ((region != null) && !region.IsDestroyed) { region.GetLocalView().DestroyRegion(); Assert.IsTrue(region.IsDestroyed, "IRegion<object, object> OverFlowRegion was not destroyed."); } region = rf.Create<object, object>("OverFlowRegion"); Assert.IsNotNull(region, "IRegion<object, object> was not created."); ValidateAttributes(region); //Console.WriteLine("TEST-2"); // put some values into the cache. DoNput(region, 100); //Console.WriteLine("TEST-2.1 All PUts Donee"); CheckNumOfEntries(region, 100); //Console.WriteLine("TEST-3"); // check whether value get evicted and token gets set as overflow CheckOverflowToken(region, 100, 20); // do some gets... printing what we find in the cache. DoNget(region, 100); TestEntryDestroy(region); TestGetOp(region, 100); //Console.WriteLine("TEST-4"); // test to verify same region repeatedly to ensure that the persistece // files are created and destroyed correctly IRegion<object, object> subRegion; for (int i = 0; i < 1; i++) { subRegion = CreateSubRegion(region, "SubRegion", "Apache.Geode.Plugins.SqLite", "SqLiteImpl<object,object>.Create()"); subRegion.DestroyRegion(); Assert.IsTrue(subRegion.IsDestroyed, "Expected region to be destroyed"); Assert.IsFalse(File.Exists(GetSqLiteFileName(sqlite_dir, "SubRegion")), "Persistence file present after region destroy"); } //Console.WriteLine("TEST-5"); } [Test] public void XmlCacheCreationWithOverflow() { Cache cache = null; IRegion<object, object> region1; IRegion<object, object> region2; IRegion<object, object> region3; IRegion<object, object>[] rootRegions; //Region<object, object>[] subRegions; ICollection<IRegion<object, object>> subRegions; /*string host_name = "XML_CACHE_CREATION_TEST";*/ const UInt32 totalSubRegionsRoot1 = 2; const UInt32 totalRootRegions = 3; try { CacheHelper.CloseCache(); Util.Log("Creating cache with the configurations provided in valid_overflowAttr.xml"); string cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "valid_overflowAttr.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Util.Log("Successfully created the cache."); rootRegions = cache.RootRegions<object, object>(); Assert.IsNotNull(rootRegions); Assert.AreEqual(totalRootRegions, rootRegions.Length); Util.Log("Root regions in Cache: "); foreach (IRegion<object, object> rg in rootRegions) { Util.Log('\t' + rg.Name); } region1 = rootRegions[0]; //subRegions = region1.SubRegions(true); subRegions = region1.SubRegions(true); Assert.IsNotNull(subRegions); Assert.AreEqual(subRegions.Count, totalSubRegionsRoot1); Util.Log("SubRegions for the root region: "); foreach (IRegion<object, object> rg in subRegions) { Util.Log('\t' + rg.Name); } Util.Log("Testing if the nesting of regions is correct..."); region2 = rootRegions[1]; subRegions = region2.SubRegions(true); string childName; string parentName; foreach (IRegion<object, object> rg in subRegions) { childName = rg.Name; IRegion<object, object> parent = rg.ParentRegion; parentName = parent.Name; if (childName == "SubSubRegion221") { Assert.AreEqual("SubRegion22", parentName); } } region3 = rootRegions[2]; //subRegions = region1.SubRegions(true); subRegions = region3.SubRegions(true); Assert.IsNotNull(subRegions); Assert.AreEqual(subRegions.Count, totalSubRegionsRoot1); Util.Log("SubRegions for the root region: "); foreach (IRegion<object, object> rg in subRegions) { Util.Log('\t' + rg.Name); } Apache.Geode.Client.RegionAttributes<object, object> attrs = region1.Attributes; //Util.Log("Attributes of root region Root1 are: "); bool cachingEnabled = attrs.CachingEnabled; Assert.IsTrue(cachingEnabled); uint lruEL = attrs.LruEntriesLimit; Assert.AreEqual(35, lruEL); int concurrency = attrs.ConcurrencyLevel; Assert.AreEqual(10, concurrency); int initialCapacity = attrs.InitialCapacity; Assert.AreEqual(25, initialCapacity); int regionIdleTO = attrs.RegionIdleTimeout; Assert.AreEqual(20, regionIdleTO); ExpirationAction action1 = attrs.RegionIdleTimeoutAction; Assert.AreEqual(ExpirationAction.Destroy, action1); DiskPolicyType type = attrs.DiskPolicy; Assert.AreEqual(DiskPolicyType.Overflows, type); string persistenceDir, maxPageCount, pageSize; string lib = attrs.PersistenceLibrary; string libFun = attrs.PersistenceFactory; Util.Log(" persistence library1 = " + lib); Util.Log(" persistence function1 = " + libFun); Properties<string, string> pconfig = attrs.PersistenceProperties; Assert.IsNotNull(pconfig, "Persistence properties should not be null for root1."); persistenceDir = (string)pconfig.Find("PersistenceDirectory"); maxPageCount = (string)pconfig.Find("MaxPageCount"); pageSize = (string)pconfig.Find("PageSize"); Assert.IsNotNull(persistenceDir, "Persistence directory should not be null."); Assert.AreNotEqual(0, persistenceDir.Length, "Persistence directory should not be empty."); Assert.IsNotNull(maxPageCount, "Persistence MaxPageCount should not be null."); Assert.AreNotEqual(0, maxPageCount.Length, "Persistence MaxPageCount should not be empty."); Assert.IsNotNull(pageSize, "Persistence PageSize should not be null."); Assert.AreNotEqual(0, pageSize.Length, "Persistence PageSize should not be empty."); Util.Log("****Attributes of Root1 are correctly set****"); Apache.Geode.Client.RegionAttributes<object, object> attrs2 = region2.Attributes; string lib2 = attrs2.PersistenceLibrary; string libFun2 = attrs2.PersistenceFactory; Util.Log(" persistence library2 = " + lib2); Util.Log(" persistence function2 = " + libFun2); Properties<string, string> pconfig2 = attrs2.PersistenceProperties; Assert.IsNotNull(pconfig2, "Persistence properties should not be null for root2."); persistenceDir = (string)pconfig2.Find("PersistenceDirectory"); maxPageCount = (string)pconfig2.Find("MaxPageCount"); maxPageCount = (string)pconfig2.Find("PageSize"); Assert.IsNotNull(persistenceDir, "Persistence directory should not be null."); Assert.AreNotEqual(0, persistenceDir.Length, "Persistence directory should not be empty."); Assert.IsNotNull(maxPageCount, "Persistence MaxPageCount should not be null."); Assert.AreNotEqual(0, maxPageCount.Length, "Persistence MaxPageCount should not be empty."); Assert.IsNotNull(pageSize, "Persistence PageSize should not be null."); Assert.AreNotEqual(0, pageSize.Length, "Persistence PageSize should not be empty."); Util.Log("****Attributes of Root2 are correctly set****"); Apache.Geode.Client.RegionAttributes<object, object> attrs3 = region3.Attributes; //Util.Log("Attributes of root region Root1 are: "); Assert.IsTrue(attrs3.CachingEnabled); Assert.AreEqual(35, attrs3.LruEntriesLimit); Assert.AreEqual(10, attrs3.ConcurrencyLevel); Assert.AreEqual(25, attrs3.InitialCapacity); Assert.AreEqual(20, attrs3.RegionIdleTimeout); Assert.AreEqual(ExpirationAction.Destroy, attrs3.RegionIdleTimeoutAction); Assert.AreEqual(DiskPolicyType.Overflows, attrs3.DiskPolicy); Util.Log(" persistence library1 = " + attrs3.PersistenceLibrary); Util.Log(" persistence function1 = " + attrs3.PersistenceFactory); Properties<string, string> pconfig3 = attrs.PersistenceProperties; Assert.IsNotNull(pconfig3, "Persistence properties should not be null for root1."); Assert.IsNotNull(pconfig3.Find("PersistenceDirectory"), "Persistence directory should not be null."); Assert.AreNotEqual(0, pconfig3.Find("PersistenceDirectory").Length, "Persistence directory should not be empty."); Assert.IsNotNull(pconfig3.Find("MaxPageCount"), "Persistence MaxPageCount should not be null."); Assert.AreNotEqual(0, pconfig3.Find("MaxPageCount").Length, "Persistence MaxPageCount should not be empty."); Assert.IsNotNull(pconfig3.Find("PageSize"), "Persistence PageSize should not be null."); Assert.AreNotEqual(0, pconfig3.Find("PageSize"), "Persistence PageSize should not be empty."); Util.Log("****Attributes of Root1 are correctly set****"); region1.DestroyRegion(null); region2.DestroyRegion(null); region3.DestroyRegion(null); if (!cache.IsClosed) { cache.Close(); } ////////////////////////////testing of cache.xml completed/////////////////// Util.Log("Create cache with the configurations provided in the invalid_overflowAttr1.xml."); Util.Log("Non existent XML; exception should be thrown"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "non-existent.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with non-existent.xml should fail!"); } catch (CacheXmlException ex) { Util.Log("Expected exception with non-existent.xml: {0}", ex); } Util.Log("This is a well-formed xml....attributes not provided for persistence manager. exception should be thrown"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "invalid_overflowAttr1.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with invalid_overflowAttr1.xml should fail!"); } catch (IllegalStateException ex) { Util.Log("Expected exception with invalid_overflowAttr1.xml: {0}", ex); } ///////////////testing of invalid_overflowAttr1.xml completed/////////////////// Util.Log("Create cache with the configurations provided in the invalid_overflowAttr2.xml."); Util.Log("This is a well-formed xml....attribute values is not provided for persistence library name......should throw an exception"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "invalid_overflowAttr2.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with invalid_overflowAttr2.xml should fail!"); } catch (CacheXmlException ex) { Util.Log("Expected exception with invalid_overflowAttr2.xml: {0}", ex); } ///////////////testing of invalid_overflowAttr2.xml completed/////////////////// Util.Log("Create cache with the configurations provided in the invalid_overflowAttr3.xml."); Util.Log("This is a well-formed xml....but region-attributes for persistence invalid......should throw an exception"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "invalid_overflowAttr3.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with invalid_overflowAttr3.xml should fail!"); } catch (CacheXmlException ex) { Util.Log("Expected exception with invalid_overflowAttr3.xml: {0}", ex); } ///////////////testing of invalid_overflowAttr3.xml completed/////////////////// } catch (Exception ex) { Assert.Fail("Caught exception: {0}", ex); } finally { if (cache != null && !cache.IsClosed) { cache.Close(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Timeout.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using UGFramework.UGEditor; using UGFramework.Log; using UGFramework.Utility; using UGFramework.Extension; using UnityEditor; using UnityEngine; namespace UGFramework.Res { public static class ResBuildManager { static BuildTarget _target; // Save builded resources to out path static string _outPath { get { string platformPrefixPath = null; if (_target == BuildTarget.iOS) { platformPrefixPath = ResConfig.PLATFORM_PREFIX_IOS; } else if (_target == BuildTarget.Android) { platformPrefixPath = ResConfig.PLATFORM_PREFIX_ANDROID; } else if (_target == BuildTarget.StandaloneWindows64) { platformPrefixPath = ResConfig.PLATFORM_PREFIX_WIN; } else if (_target == BuildTarget.StandaloneOSXUniversal) { platformPrefixPath = ResConfig.PLATFORM_PREFIX_OSX; } return Application.streamingAssetsPath + "/" + platformPrefixPath + "/" + ResConfig.RES_ROOT.ToLower(); } } static BuildAssetBundleOptions _options = // BuildAssetBundleOptions.DisableWriteTypeTree | // BuildAssetBundleOptions.DeterministicAssetBundle | // BuildAssetBundleOptions.StrictMode | // BuildAssetBundleOptions.ForceRebuildAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression; // BuildAssetBundleOptions.UncompressedAssetBundle; public static void Clear() { EditorUtility.DisplayProgressBar( "Clear AssetBundles", string.Format("Removing..."), 1f); if (Directory.Exists(Application.streamingAssetsPath)) { Directory.Delete(Application.streamingAssetsPath, true); Directory.CreateDirectory(Application.streamingAssetsPath); } EditorUtility.ClearProgressBar(); ResBuildUtility.ClearAssetBundleConfigurations(); AssetDatabase.Refresh(); } static void BeforeBuild(BuildTarget targetPlatform) { EditorUtility.DisplayProgressBar( "Building AssetBundles", string.Format("Starting building..."), 0); _target = targetPlatform; if (Directory.Exists(_outPath) == false) Directory.CreateDirectory(_outPath); ResBuildUtility.ClearAssetBundleConfigurations(); } static void AfterBuild() { EditorUtility.ClearProgressBar(); } public static void Build(BuildTarget targetPlatform) { BeforeBuild(targetPlatform); // Build var resPath = Application.dataPath + "/" + ResConfig.RES_ROOT; var files = ResBuildUtility.GetFiles(resPath); BuildBundles(targetPlatform, files); AfterBuild(); } static void BuildBundles(BuildTarget targetPlatform, string[] files) { var buildInfos = new Dictionary<string, AssetBundleBuild>(); var filters = new List<ResAbstractBuildFilter>() { new ResLuaBuildFilter(), new ResSpriteBuildFilter(), // Assets contain dependence new ResPrefabBuildFilter(), }; // 10 var basePercent = 0f; var percent = 10f; var index = 0f; var count = filters.Count; // BeforeBuild EditorUtility.DisplayProgressBar( "Building AssetBundles", string.Format("Before building..."), ((1) * percent + basePercent) / 100); foreach (var filter in filters) { filter.BeforeBuild(); index++; } // 30 basePercent = basePercent + percent; percent = 20f; index = 0; count = files.Length * filters.Count; // Prepare build EditorUtility.DisplayProgressBar( "Building AssetBundles", string.Format("Preparing..."), ((1) * percent + basePercent) / 100); foreach (var file in files) { foreach (var filter in filters) { index++; if (filter.Filtered(file)) { AssetBundleBuild? buildInfoNullable = filter.PrepareBuild(file); if (buildInfoNullable != null) { var buildInfo = (AssetBundleBuild)buildInfoNullable; buildInfos[file] = buildInfo; } if (filter.BlockOthers) break; } } } // 50 basePercent = basePercent + percent; percent = 20f; index = 0; count = files.Length * buildInfos.Count; try { var filteredBuildInfos = new List<AssetBundleBuild>(); // Real build foreach (var pair in buildInfos) { var filepath = pair.Key; var buildInfo = pair.Value; { // Add dependent buildInfos ResBuildUtility.AppendDependencies(buildInfo, filteredBuildInfos); // Add self buildInfo filteredBuildInfos.Add(buildInfo); } } // 60 basePercent = basePercent + percent; percent = 10f; index = 0; count = filters.Count; // Additive build foreach (var filter in filters) { EditorUtility.DisplayProgressBar( "Building AssetBundles", string.Format(filter.GetType().Name + " override building..."), ((index / count) * percent + basePercent) / 100); index++; filter.OverrideBuild(_outPath, filteredBuildInfos); } // 80 basePercent = basePercent + percent; percent = 20f; index = 0; count = filteredBuildInfos.Count; // Set bundle name EditorUtility.DisplayProgressBar( "Building AssetBundles", string.Format("Setting bundleNames..."), ((1) * percent + basePercent) / 100); for (var i = 0; i < filteredBuildInfos.Count; ++i) { index++; var buildInfo = filteredBuildInfos[i]; ResBuildUtility.ResetBundleName(ref buildInfo); filteredBuildInfos[i] = buildInfo; } // Build BuildPipeline.BuildAssetBundles( _outPath, // filteredBuildInfos.ToArray(), _options, targetPlatform ); // 100 basePercent = basePercent + percent; percent = 20f; index = 1; count = 1; // Build version file EditorUtility.DisplayProgressBar( "Building AssetBundles", string.Format("Building version file..."), ((index / count) * percent + basePercent) / 100); var bundlesPath = _outPath; files = ResBuildUtility.GetFiles(bundlesPath); BuildVersionFile(files); } catch (Exception e) { LogManager.Error(e.Message); } finally { // After build foreach (var filter in filters) { filter.AfterBuild(); } } } static ResVersionFile BuildVersionFile(string[] files) { var versionFile = new ResVersionFile(files.Length); for (var i = 0; i < files.Length; ++i) { var file = files[i]; var versionInfo = new ResVersionInfo(); versionInfo.File = file.ReplaceFirst(_outPath + "/", ""); versionInfo.MD5 = MD5Utility.GetFileMD5(file); versionInfo.Size = (ulong)FileUtility.ReadFileBytes(file).Length; versionFile.Infos[i] = versionInfo; } var filePath = Application.dataPath + "/" + ResConfig.RES_ROOT + "/" + ResConfig.VERSION_FILE; FileUtility.WriteFile(filePath, versionFile.Serialize()); AssetDatabase.Refresh(); var buildInfo = new AssetBundleBuild(); buildInfo.assetBundleName = ResConfig.VERSION_FILE; var assetName = "Assets/" + ResConfig.RES_ROOT + "/" + ResConfig.VERSION_FILE; buildInfo.assetNames = new string[] { assetName }; ResBuildUtility.ResetBundleName(ref buildInfo); var options = _options & (~BuildAssetBundleOptions.ForceRebuildAssetBundle); BuildPipeline.BuildAssetBundles( _outPath, // new AssetBundleBuild[] { buildInfo }, options, _target ); // Copy & Remove temp versionFile FileUtility.CopyFile(filePath, _outPath + "/" + ResConfig.VERSION_FILE); FileUtility.DeleteFile(filePath); return versionFile; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using VowTracker.Areas.HelpPage.ModelDescriptions; using VowTracker.Areas.HelpPage.Models; namespace VowTracker.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Text; using OLEDB.Test.ModuleCore; using XmlCoreTest.Common; using Xunit; namespace XmlWriterAPI.Test { public partial class XmlWriterTestModule : CTestModule { private static void RunTestCase(Func<CTestBase> testCaseGenerator) { var module = new XmlWriterTestModule(); module.Init(null); module.AddChild(testCaseGenerator()); module.Execute(); Assert.Equal(0, module.FailCount); } private static void RunTest(Func<CTestBase> testCaseGenerator) { CModInfo.CommandLine = "/WriterType UnicodeWriter"; RunTestCase(testCaseGenerator); CModInfo.CommandLine = "/WriterType UnicodeWriter /Async true"; RunTestCase(testCaseGenerator); CModInfo.CommandLine = "/WriterType UTF8Writer"; RunTestCase(testCaseGenerator); CModInfo.CommandLine = "/WriterType UTF8Writer /Async true"; RunTestCase(testCaseGenerator); } [Fact] [OuterLoop] static public void TCErrorState() { RunTest(() => new TCErrorState() { Attribute = new TestCase() { Name = "Invalid State Combinations" } }); } [Fact] [OuterLoop] static public void TCAutoComplete() { RunTest(() => new TCAutoComplete() { Attribute = new TestCase() { Name = "Auto-completion of tokens" } }); } [Fact] [OuterLoop] static public void TCDocument() { RunTest(() => new TCDocument() { Attribute = new TestCase() { Name = "WriteStart/EndDocument" } }); } [Fact] [OuterLoop] static public void TCDocType() { RunTest(() => new TCDocType() { Attribute = new TestCase() { Name = "WriteDocType" } }); } [Fact] [OuterLoop] static public void TCElement() { RunTest(() => new TCElement() { Attribute = new TestCase() { Name = "WriteStart/EndElement" } }); } [Fact] [OuterLoop] static public void TCAttribute() { RunTest(() => new TCAttribute() { Attribute = new TestCase() { Name = "WriteStart/EndAttribute" } }); } [Fact] [OuterLoop] static public void TCWriteAttributes() { RunTest(() => new TCWriteAttributes() { Attribute = new TestCase() { Name = "WriteAttributes(CoreReader)", Param = "COREREADER" } }); } [Fact] [OuterLoop] static public void TCWriteNode_XmlReader() { RunTest(() => new TCWriteNode_XmlReader() { Attribute = new TestCase() { Name = "WriteNode(CoreReader)", Param = "COREREADER" } }); } [Fact] [OuterLoop] static public void TCWriteNode_With_ReadValueChunk() { RunTest(() => new TCWriteNode_With_ReadValueChunk() { Attribute = new TestCase() { Name = "WriteNode with streaming API ReadValueChunk - COREREADER", Param = "COREREADER" } }); } [Fact] [OuterLoop] [ActiveIssue(1491)] static public void TCFullEndElement() { RunTest(() => new TCFullEndElement() { Attribute = new TestCase() { Name = "WriteFullEndElement" } }); } [Fact] [OuterLoop] static public void TCEOFHandling() { RunTest(() => new TCEOFHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineHandling" } }); } [Fact] [OuterLoop] static public void TCErrorConditionWriter() { RunTest(() => new TCErrorConditionWriter() { Attribute = new TestCase() { Name = "ErrorCondition" } }); } [Fact] [OuterLoop] static public void TCNamespaceHandling() { RunTest(() => new TCNamespaceHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NamespaceHandling" } }); } [Fact] [OuterLoop] static public void TCDefaultWriterSettings() { RunTest(() => new TCDefaultWriterSettings() { Attribute = new TestCase() { Name = "XmlWriterSettings: Default Values" } }); } [Fact] [OuterLoop] static public void TCWriterSettingsMisc() { RunTest(() => new TCWriterSettingsMisc() { Attribute = new TestCase() { Name = "XmlWriterSettings: Reset/Clone" } }); } [Fact] [OuterLoop] static public void TCOmitXmlDecl() { RunTest(() => new TCOmitXmlDecl() { Attribute = new TestCase() { Name = "XmlWriterSettings: OmitXmlDeclaration" } }); } [Fact] [OuterLoop] static public void TCCheckChars() { RunTest(() => new TCCheckChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: CheckCharacters" } }); } [Fact] [OuterLoop] static public void TCNewLineHandling() { RunTest(() => new TCNewLineHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineHandling" } }); } [Fact] [OuterLoop] static public void TCNewLineChars() { RunTest(() => new TCNewLineChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineChars" } }); } [Fact] [OuterLoop] static public void TCIndent() { RunTest(() => new TCIndent() { Attribute = new TestCase() { Name = "XmlWriterSettings: Indent" } }); } [Fact] [OuterLoop] static public void TCIndentChars() { RunTest(() => new TCIndentChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: IndentChars" } }); } [Fact] [OuterLoop] static public void TCNewLineOnAttributes() { RunTest(() => new TCNewLineOnAttributes() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineOnAttributes" } }); } [Fact] [OuterLoop] static public void TCStandAlone() { RunTest(() => new TCStandAlone() { Attribute = new TestCase() { Name = "Standalone" } }); } [Fact] [OuterLoop] static public void TCCloseOutput() { RunTest(() => new TCCloseOutput() { Attribute = new TestCase() { Name = "XmlWriterSettings: CloseOutput" } }); } [Fact] [OuterLoop] static public void TCFragmentCL() { RunTest(() => new TCFragmentCL() { Attribute = new TestCase() { Name = "CL = Fragment Tests" } }); } [Fact] [OuterLoop] static public void TCAutoCL() { RunTest(() => new TCAutoCL() { Attribute = new TestCase() { Name = "CL = Auto Tests" } }); } [Fact] [OuterLoop] static public void TCFlushClose() { RunTest(() => new TCFlushClose() { Attribute = new TestCase() { Name = "Close()/Flush()" } }); } [Fact] [OuterLoop] static public void TCWriterWithMemoryStream() { RunTest(() => new TCWriterWithMemoryStream() { Attribute = new TestCase() { Name = "XmlWriter with MemoryStream" } }); } [Fact] [OuterLoop] static public void TCWriteEndDocumentOnCloseTest() { RunTest(() => new TCWriteEndDocumentOnCloseTest() { Attribute = new TestCase() { Name = "XmlWriterSettings: WriteEndDocumentOnClose" } }); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Hatchet.Extensions; using Hatchet.Reflection; namespace Hatchet { internal class Serializer { private const string LineEnding = "\n"; private const int IndentCount = 2; private PrettyPrinter PrettyPrinter { get; } private SerializeOptions SerializeOptions { get; } private int IndentLevel => PrettyPrinter.IndentLevel; private readonly List<object> _metObjects; public Serializer( PrettyPrinter prettyPrinter, SerializeOptions serializeOptions) { PrettyPrinter = prettyPrinter; SerializeOptions = serializeOptions; _metObjects = new List<object>(); } public void Serialize(object input, bool forceClassName = false) { PushObjectRef(input); var context = new SerializationContext(forceClassName); switch (input) { case Array arrayInput when arrayInput.GetType().IsArray: SerializeArray(arrayInput); break; case IDictionary dictionaryInput: SerializeDictionary(dictionaryInput); break; case object genericEnumerable when genericEnumerable.GetType().GenericTypeArguments.Length == 1: SerializeGenericEnumerable(genericEnumerable, context); break; case string strInput: SerializeString(strInput); break; case DateTime dateTimeInput: SerializeDateTime(dateTimeInput); break; case bool boolInput: SerializeBoolean(boolInput); break; case object simpleValue when IsSimpleValue(simpleValue.GetType()): SerializeSimpleValue(simpleValue); break; case ICollection collectionInput: SerializeCollection(collectionInput, context); break; case Enum enumValue when enumValue.GetType().IsEnum: SerializeEnum(enumValue); break; case object classOrStruct when classOrStruct.GetType().IsClass || classOrStruct.GetType().IsValueType: SerializeClassOrStruct(classOrStruct, context); break; default: throw new HatchetException($"Could not serialize {input} of type {input.GetType()}"); } PopObjectRef(input); } private bool IsSimpleValue(Type inputType) { return inputType.IsPrimitive || inputType == typeof(decimal) || inputType == typeof(DateTime) || inputType == typeof(Guid); } private void SerializeClassOrStruct(object input, SerializationContext context) { var inputType = input.GetType(); var customOutputValue = inputType .GetNonIgnoredProperties() .SingleOrDefault(x => x.HasAttribute<HatchetValueAttribute>()); if (customOutputValue != null) { var value = customOutputValue.GetValue(input); PrettyPrinter.Append(value); return; } PrettyPrinter.AppendOpenBlock(); if (context.ForceClassName) { WriteClassName(inputType); } SerializeFieldsAndProperties(input); PrettyPrinter.AppendCloseBlock(); } private void SerializeFieldsAndProperties(object input) { var propertiesAndFields = GetPropertiesAndFields(input); foreach (var member in propertiesAndFields) { SerializeMember(member); } } private void SerializeMember(ISerializableMember member) { SerializeKeyValue(member.Name, member.Value, member.IsValueAbstract); } private void WriteClassName(Type inputType) { PrettyPrinter.Append(' ', IndentLevel * IndentCount); PrettyPrinter.Append(' ', IndentCount); PrettyPrinter.AppendFormat("Class {0}", inputType.Name); PrettyPrinter.Append(LineEnding); } private void SerializeKeyValue(string key, object value, bool forceClassName = false) { if (value == null) return; if (key.Contains(" ")) { throw new HatchetException( $"`{key}` is an invalid key. Key cannot contain spaces."); } var type = value.GetType(); if (type.IsValueType) { var comparable = Activator.CreateInstance(type); if (value.Equals(comparable) && !SerializeOptions.IncludeDefaultValues) return; } PrettyPrinter.Append(' ', IndentLevel * IndentCount); PrettyPrinter.Append(' ', IndentCount); PrettyPrinter.Append(key); PrettyPrinter.Append(' '); IndentAndSerialize(value, forceClassName); PrettyPrinter.Append(LineEnding); } private void IndentAndSerialize(object value, bool forceClassName) { PrettyPrinter.Indent(); Serialize(value, forceClassName); PrettyPrinter.Deindent(); } private static IEnumerable<ISerializableMember> GetPropertiesAndFields(object input) { var inputType = input.GetType(); foreach (var property in inputType.GetPropertiesToSerialize()) { yield return new SerializableProperty(property, input); } foreach (var field in inputType.GetFieldsToSerialize()) { yield return new SerializableField(field, input); } } private void SerializeEnum(object value) { PrettyPrinter.AppendEnum(value); } private void SerializeSimpleValue(object input) { PrettyPrinter.Append(input); } private void SerializeGenericEnumerable(object input, SerializationContext context) { var forceClassName = context.ForceClassName; var elementType = input.GetType().GenericTypeArguments[0]; if (elementType.IsAbstract) forceClassName = true; var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType); PrettyPrinter.Append("["); if (enumerableType.IsInstanceOfType(input)) { var enumerator = ((IEnumerable) input).GetEnumerator(); var addSpace = false; while (enumerator.MoveNext()) { if (addSpace) PrettyPrinter.AppendFormat(" "); addSpace = true; var element = enumerator.Current; IndentAndSerialize(element, forceClassName); } } PrettyPrinter.Append("]"); } private void SerializeDictionary(IDictionary input) { if (input.Count == 0) { PrettyPrinter.Append("{}"); return; } PrettyPrinter.AppendOpenBlock(); foreach (var key in input.Keys) { SerializeKeyValue(key.ToString(), input[key]); } PrettyPrinter.AppendCloseBlock(); } private void SerializeCollection(IEnumerable collectionInput, SerializationContext context) { var forceClassName = context.ForceClassName; foreach (var item in collectionInput) { IndentAndSerialize(item, forceClassName); } } private void SerializeArray(Array inputArray) { var values = inputArray.Select(x => HatchetConvert.Serialize(x, SerializeOptions)); PrettyPrinter.AppendFormat("[{0}]", string.Join(" ", values)); } private void SerializeString(string input) { PrettyPrinter.AppendString(input); } private void SerializeDateTime(DateTime input) { PrettyPrinter.AppendDateTime(input); } private void SerializeBoolean(bool input) { PrettyPrinter.Append(input ? "true" : "false"); } private void PushObjectRef(object obj) { var type = obj.GetType(); if (obj is string) return; if (type.IsValueType) return; if (_metObjects.Contains(obj)) throw new CircularReferenceException(obj); _metObjects.Add(obj); } private void PopObjectRef(object obj) { _metObjects.Remove(obj); } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; using System.IO; using System.Collections.Generic; #if WINDOWS_STOREAPP using System.Threading.Tasks; using Windows.Storage; #endif namespace Spine { public class SkeletonBinary { public const int TIMELINE_SCALE = 0; public const int TIMELINE_ROTATE = 1; public const int TIMELINE_TRANSLATE = 2; public const int TIMELINE_ATTACHMENT = 3; public const int TIMELINE_COLOR = 4; public const int TIMELINE_FLIPX = 5; public const int TIMELINE_FLIPY = 6; public const int CURVE_LINEAR = 0; public const int CURVE_STEPPED = 1; public const int CURVE_BEZIER = 2; private AttachmentLoader attachmentLoader; public float Scale { get; set; } private char[] chars = new char[32]; private byte[] buffer = new byte[4]; public SkeletonBinary (params Atlas[] atlasArray) : this(new AtlasAttachmentLoader(atlasArray)) { } public SkeletonBinary (AttachmentLoader attachmentLoader) { if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader cannot be null."); this.attachmentLoader = attachmentLoader; Scale = 1; } #if WINDOWS_STOREAPP private async Task<SkeletonData> ReadFile(string path) { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; using (var input = new BufferedStream(await folder.GetFileAsync(path).AsTask().ConfigureAwait(false))) { SkeletonData skeletonData = ReadSkeletonData(input); skeletonData.Name = Path.GetFileNameWithoutExtension(path); return skeletonData; } } public SkeletonData ReadSkeletonData (String path) { return this.ReadFile(path).Result; } #else public SkeletonData ReadSkeletonData (String path) { #if WINDOWS_PHONE using (var input = new BufferedStream(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) { #else using (var input = new BufferedStream(new FileStream(path, FileMode.Open))) { #endif SkeletonData skeletonData = ReadSkeletonData(input); skeletonData.name = Path.GetFileNameWithoutExtension(path); return skeletonData; } } #endif public SkeletonData ReadSkeletonData (Stream input) { if (input == null) throw new ArgumentNullException("input cannot be null."); float scale = Scale; var skeletonData = new SkeletonData(); skeletonData.hash = ReadString(input); if (skeletonData.hash.Length == 0) skeletonData.hash = null; skeletonData.version = ReadString(input); if (skeletonData.version.Length == 0) skeletonData.version = null; skeletonData.width = ReadFloat(input); skeletonData.height = ReadFloat(input); bool nonessential = ReadBoolean(input); if (nonessential) { skeletonData.imagesPath = ReadString(input); if (skeletonData.imagesPath.Length == 0) skeletonData.imagesPath = null; } // Bones. for (int i = 0, n = ReadInt(input, true); i < n; i++) { String name = ReadString(input); BoneData parent = null; int parentIndex = ReadInt(input, true) - 1; if (parentIndex != -1) parent = skeletonData.bones.Items[parentIndex]; BoneData boneData = new BoneData(name, parent); boneData.x = ReadFloat(input) * scale; boneData.y = ReadFloat(input) * scale; boneData.scaleX = ReadFloat(input); boneData.scaleY = ReadFloat(input); boneData.rotation = ReadFloat(input); boneData.length = ReadFloat(input) * scale; boneData.flipX = ReadBoolean(input); boneData.flipY = ReadBoolean(input); boneData.inheritScale = ReadBoolean(input); boneData.inheritRotation = ReadBoolean(input); if (nonessential) ReadInt(input); // Skip bone color. skeletonData.bones.Add(boneData); } // IK constraints. for (int i = 0, n = ReadInt(input, true); i < n; i++) { IkConstraintData ikConstraintData = new IkConstraintData(ReadString(input)); for (int ii = 0, nn = ReadInt(input, true); ii < nn; ii++) ikConstraintData.bones.Add(skeletonData.bones.Items[ReadInt(input, true)]); ikConstraintData.target = skeletonData.bones.Items[ReadInt(input, true)]; ikConstraintData.mix = ReadFloat(input); ikConstraintData.bendDirection = ReadSByte(input); skeletonData.ikConstraints.Add(ikConstraintData); } // Slots. for (int i = 0, n = ReadInt(input, true); i < n; i++) { String slotName = ReadString(input); BoneData boneData = skeletonData.bones.Items[ReadInt(input, true)]; SlotData slotData = new SlotData(slotName, boneData); int color = ReadInt(input); slotData.r = ((color & 0xff000000) >> 24) / 255f; slotData.g = ((color & 0x00ff0000) >> 16) / 255f; slotData.b = ((color & 0x0000ff00) >> 8) / 255f; slotData.a = ((color & 0x000000ff)) / 255f; slotData.attachmentName = ReadString(input); slotData.blendMode = (BlendMode)ReadInt(input, true); skeletonData.slots.Add(slotData); } // Default skin. Skin defaultSkin = ReadSkin(input, "default", nonessential); if (defaultSkin != null) { skeletonData.defaultSkin = defaultSkin; skeletonData.skins.Add(defaultSkin); } // Skins. for (int i = 0, n = ReadInt(input, true); i < n; i++) skeletonData.skins.Add(ReadSkin(input, ReadString(input), nonessential)); // Events. for (int i = 0, n = ReadInt(input, true); i < n; i++) { EventData eventData = new EventData(ReadString(input)); eventData.Int = ReadInt(input, false); eventData.Float = ReadFloat(input); eventData.String = ReadString(input); skeletonData.events.Add(eventData); } // Animations. for (int i = 0, n = ReadInt(input, true); i < n; i++) ReadAnimation(ReadString(input), input, skeletonData); skeletonData.bones.TrimExcess(); skeletonData.slots.TrimExcess(); skeletonData.skins.TrimExcess(); skeletonData.events.TrimExcess(); skeletonData.animations.TrimExcess(); skeletonData.ikConstraints.TrimExcess(); return skeletonData; } /** @return May be null. */ private Skin ReadSkin (Stream input, String skinName, bool nonessential) { int slotCount = ReadInt(input, true); if (slotCount == 0) return null; Skin skin = new Skin(skinName); for (int i = 0; i < slotCount; i++) { int slotIndex = ReadInt(input, true); for (int ii = 0, nn = ReadInt(input, true); ii < nn; ii++) { String name = ReadString(input); skin.AddAttachment(slotIndex, name, ReadAttachment(input, skin, name, nonessential)); } } return skin; } private Attachment ReadAttachment (Stream input, Skin skin, String attachmentName, bool nonessential) { float scale = Scale; String name = ReadString(input); if (name == null) name = attachmentName; switch ((AttachmentType)input.ReadByte()) { case AttachmentType.region: { String path = ReadString(input); if (path == null) path = name; RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path); if (region == null) return null; region.Path = path; region.x = ReadFloat(input) * scale; region.y = ReadFloat(input) * scale; region.scaleX = ReadFloat(input); region.scaleY = ReadFloat(input); region.rotation = ReadFloat(input); region.width = ReadFloat(input) * scale; region.height = ReadFloat(input) * scale; int color = ReadInt(input); region.r = ((color & 0xff000000) >> 24) / 255f; region.g = ((color & 0x00ff0000) >> 16) / 255f; region.b = ((color & 0x0000ff00) >> 8) / 255f; region.a = ((color & 0x000000ff)) / 255f; region.UpdateOffset(); return region; } case AttachmentType.boundingbox: { BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name); if (box == null) return null; box.vertices = ReadFloatArray(input, scale); return box; } case AttachmentType.mesh: { String path = ReadString(input); if (path == null) path = name; MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); if (mesh == null) return null; mesh.Path = path; mesh.regionUVs = ReadFloatArray(input, 1); mesh.triangles = ReadShortArray(input); mesh.vertices = ReadFloatArray(input, scale); mesh.UpdateUVs(); int color = ReadInt(input); mesh.r = ((color & 0xff000000) >> 24) / 255f; mesh.g = ((color & 0x00ff0000) >> 16) / 255f; mesh.b = ((color & 0x0000ff00) >> 8) / 255f; mesh.a = ((color & 0x000000ff)) / 255f; mesh.HullLength = ReadInt(input, true) * 2; if (nonessential) { mesh.Edges = ReadIntArray(input); mesh.Width = ReadFloat(input) * scale; mesh.Height = ReadFloat(input) * scale; } return mesh; } case AttachmentType.skinnedmesh: { String path = ReadString(input); if (path == null) path = name; SkinnedMeshAttachment mesh = attachmentLoader.NewSkinnedMeshAttachment(skin, name, path); if (mesh == null) return null; mesh.Path = path; float[] uvs = ReadFloatArray(input, 1); int[] triangles = ReadShortArray(input); int vertexCount = ReadInt(input, true); var weights = new List<float>(uvs.Length * 3 * 3); var bones = new List<int>(uvs.Length * 3); for (int i = 0; i < vertexCount; i++) { int boneCount = (int)ReadFloat(input); bones.Add(boneCount); for (int nn = i + boneCount * 4; i < nn; i += 4) { bones.Add((int)ReadFloat(input)); weights.Add(ReadFloat(input) * scale); weights.Add(ReadFloat(input) * scale); weights.Add(ReadFloat(input)); } } mesh.bones = bones.ToArray(); mesh.weights = weights.ToArray(); mesh.triangles = triangles; mesh.regionUVs = uvs; mesh.UpdateUVs(); int color = ReadInt(input); mesh.r = ((color & 0xff000000) >> 24) / 255f; mesh.g = ((color & 0x00ff0000) >> 16) / 255f; mesh.b = ((color & 0x0000ff00) >> 8) / 255f; mesh.a = ((color & 0x000000ff)) / 255f; mesh.HullLength = ReadInt(input, true) * 2; if (nonessential) { mesh.Edges = ReadIntArray(input); mesh.Width = ReadFloat(input) * scale; mesh.Height = ReadFloat(input) * scale; } return mesh; } } return null; } private float[] ReadFloatArray (Stream input, float scale) { int n = ReadInt(input, true); float[] array = new float[n]; if (scale == 1) { for (int i = 0; i < n; i++) array[i] = ReadFloat(input); } else { for (int i = 0; i < n; i++) array[i] = ReadFloat(input) * scale; } return array; } private int[] ReadShortArray (Stream input) { int n = ReadInt(input, true); int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = (input.ReadByte() << 8) + input.ReadByte(); return array; } private int[] ReadIntArray (Stream input) { int n = ReadInt(input, true); int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = ReadInt(input, true); return array; } private void ReadAnimation (String name, Stream input, SkeletonData skeletonData) { var timelines = new ExposedList<Timeline>(); float scale = Scale; float duration = 0; // Slot timelines. for (int i = 0, n = ReadInt(input, true); i < n; i++) { int slotIndex = ReadInt(input, true); for (int ii = 0, nn = ReadInt(input, true); ii < nn; ii++) { int timelineType = input.ReadByte(); int frameCount = ReadInt(input, true); switch (timelineType) { case TIMELINE_COLOR: { ColorTimeline timeline = new ColorTimeline(frameCount); timeline.slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { float time = ReadFloat(input); int color = ReadInt(input); float r = ((color & 0xff000000) >> 24) / 255f; float g = ((color & 0x00ff0000) >> 16) / 255f; float b = ((color & 0x0000ff00) >> 8) / 255f; float a = ((color & 0x000000ff)) / 255f; timeline.SetFrame(frameIndex, time, r, g, b, a); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount * 5 - 5]); break; } case TIMELINE_ATTACHMENT: { AttachmentTimeline timeline = new AttachmentTimeline(frameCount); timeline.slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) timeline.SetFrame(frameIndex, ReadFloat(input), ReadString(input)); timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount - 1]); break; } } } } // Bone timelines. for (int i = 0, n = ReadInt(input, true); i < n; i++) { int boneIndex = ReadInt(input, true); for (int ii = 0, nn = ReadInt(input, true); ii < nn; ii++) { int timelineType = input.ReadByte(); int frameCount = ReadInt(input, true); switch (timelineType) { case TIMELINE_ROTATE: { RotateTimeline timeline = new RotateTimeline(frameCount); timeline.boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input)); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount * 2 - 2]); break; } case TIMELINE_TRANSLATE: case TIMELINE_SCALE: { TranslateTimeline timeline; float timelineScale = 1; if (timelineType == TIMELINE_SCALE) timeline = new ScaleTimeline(frameCount); else { timeline = new TranslateTimeline(frameCount); timelineScale = scale; } timeline.boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input) * timelineScale, ReadFloat(input) * timelineScale); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount * 3 - 3]); break; } case TIMELINE_FLIPX: case TIMELINE_FLIPY: { FlipXTimeline timeline = timelineType == TIMELINE_FLIPX ? new FlipXTimeline(frameCount) : new FlipYTimeline( frameCount); timeline.boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) timeline.SetFrame(frameIndex, ReadFloat(input), ReadBoolean(input)); timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount * 2 - 2]); break; } } } } // IK timelines. for (int i = 0, n = ReadInt(input, true); i < n; i++) { IkConstraintData ikConstraint = skeletonData.ikConstraints.Items[ReadInt(input, true)]; int frameCount = ReadInt(input, true); IkConstraintTimeline timeline = new IkConstraintTimeline(frameCount); timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(ikConstraint); for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadSByte(input)); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount * 3 - 3]); } // FFD timelines. for (int i = 0, n = ReadInt(input, true); i < n; i++) { Skin skin = skeletonData.skins.Items[ReadInt(input, true)]; for (int ii = 0, nn = ReadInt(input, true); ii < nn; ii++) { int slotIndex = ReadInt(input, true); for (int iii = 0, nnn = ReadInt(input, true); iii < nnn; iii++) { Attachment attachment = skin.GetAttachment(slotIndex, ReadString(input)); int frameCount = ReadInt(input, true); FFDTimeline timeline = new FFDTimeline(frameCount); timeline.slotIndex = slotIndex; timeline.attachment = attachment; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { float time = ReadFloat(input); float[] vertices; int vertexCount; if (attachment is MeshAttachment) vertexCount = ((MeshAttachment)attachment).vertices.Length; else vertexCount = ((SkinnedMeshAttachment)attachment).weights.Length / 3 * 2; int end = ReadInt(input, true); if (end == 0) { if (attachment is MeshAttachment) vertices = ((MeshAttachment)attachment).vertices; else vertices = new float[vertexCount]; } else { vertices = new float[vertexCount]; int start = ReadInt(input, true); end += start; if (scale == 1) { for (int v = start; v < end; v++) vertices[v] = ReadFloat(input); } else { for (int v = start; v < end; v++) vertices[v] = ReadFloat(input) * scale; } if (attachment is MeshAttachment) { float[] meshVertices = ((MeshAttachment)attachment).vertices; for (int v = 0, vn = vertices.Length; v < vn; v++) vertices[v] += meshVertices[v]; } } timeline.SetFrame(frameIndex, time, vertices); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount - 1]); } } } // Draw order timeline. int drawOrderCount = ReadInt(input, true); if (drawOrderCount > 0) { DrawOrderTimeline timeline = new DrawOrderTimeline(drawOrderCount); int slotCount = skeletonData.slots.Count; for (int i = 0; i < drawOrderCount; i++) { int offsetCount = ReadInt(input, true); int[] drawOrder = new int[slotCount]; for (int ii = slotCount - 1; ii >= 0; ii--) drawOrder[ii] = -1; int[] unchanged = new int[slotCount - offsetCount]; int originalIndex = 0, unchangedIndex = 0; for (int ii = 0; ii < offsetCount; ii++) { int slotIndex = ReadInt(input, true); // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; // Set changed items. drawOrder[originalIndex + ReadInt(input, true)] = originalIndex++; } // Collect remaining unchanged items. while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++; // Fill in unchanged items. for (int ii = slotCount - 1; ii >= 0; ii--) if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex]; timeline.SetFrame(i, ReadFloat(input), drawOrder); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[drawOrderCount - 1]); } // Event timeline. int eventCount = ReadInt(input, true); if (eventCount > 0) { EventTimeline timeline = new EventTimeline(eventCount); for (int i = 0; i < eventCount; i++) { float time = ReadFloat(input); EventData eventData = skeletonData.events.Items[ReadInt(input, true)]; Event e = new Event(eventData); e.Int = ReadInt(input, false); e.Float = ReadFloat(input); e.String = ReadBoolean(input) ? ReadString(input) : eventData.String; timeline.SetFrame(i, time, e); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[eventCount - 1]); } timelines.TrimExcess(); skeletonData.animations.Add(new Animation(name, timelines, duration)); } private void ReadCurve (Stream input, int frameIndex, CurveTimeline timeline) { switch (input.ReadByte()) { case CURVE_STEPPED: timeline.SetStepped(frameIndex); break; case CURVE_BEZIER: timeline.SetCurve(frameIndex, ReadFloat(input), ReadFloat(input), ReadFloat(input), ReadFloat(input)); break; } } private sbyte ReadSByte (Stream input) { int value = input.ReadByte(); if (value == -1) throw new EndOfStreamException(); return (sbyte)value; } private bool ReadBoolean (Stream input) { return input.ReadByte() != 0; } private float ReadFloat (Stream input) { buffer[3] = (byte)input.ReadByte(); buffer[2] = (byte)input.ReadByte(); buffer[1] = (byte)input.ReadByte(); buffer[0] = (byte)input.ReadByte(); return BitConverter.ToSingle(buffer, 0); } private int ReadInt (Stream input) { return (input.ReadByte() << 24) + (input.ReadByte() << 16) + (input.ReadByte() << 8) + input.ReadByte(); } private int ReadInt (Stream input, bool optimizePositive) { int b = input.ReadByte(); int result = b & 0x7F; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 28; } } } } return optimizePositive ? result : ((result >> 1) ^ -(result & 1)); } private string ReadString (Stream input) { int charCount = ReadInt(input, true); switch (charCount) { case 0: return null; case 1: return ""; } charCount--; char[] chars = this.chars; if (chars.Length < charCount) this.chars = chars = new char[charCount]; // Try to read 7 bit ASCII chars. int charIndex = 0; int b = 0; while (charIndex < charCount) { b = input.ReadByte(); if (b > 127) break; chars[charIndex++] = (char)b; } // If a char was not ASCII, finish with slow path. if (charIndex < charCount) ReadUtf8_slow(input, charCount, charIndex, b); return new String(chars, 0, charCount); } private void ReadUtf8_slow (Stream input, int charCount, int charIndex, int b) { char[] chars = this.chars; while (true) { switch (b >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: chars[charIndex] = (char)b; break; case 12: case 13: chars[charIndex] = (char)((b & 0x1F) << 6 | input.ReadByte() & 0x3F); break; case 14: chars[charIndex] = (char)((b & 0x0F) << 12 | (input.ReadByte() & 0x3F) << 6 | input.ReadByte() & 0x3F); break; } if (++charIndex >= charCount) break; b = input.ReadByte() & 0xFF; } } } }
// // Copyright 2010, 2011 Novell, Inc. // Copyright 2011, Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using MonoMac.ObjCRuntime; namespace MonoMac.AppKit { public enum NSRunResponse { Stopped = -1000, Aborted = -1001, Continues = -1002 } public enum NSApplicationActivationOptions { ActivateAllWindows = 1, ActivateIgnoringOtherWindows = 2 } public enum NSApplicationActivationPolicy { Regular, Accessory, Prohibited } public enum NSApplicationPresentationOptions { Default = 0, AutoHideDock = (1 << 0), HideDock = (1 << 1), AutoHideMenuBar = (1 << 2), HideMenuBar = (1 << 3), DisableAppleMenu = (1 << 4), DisableProcessSwitching = (1 << 5), DisableForceQuit = (1 << 6), DisableSessionTermination = (1 << 7), DisableHideApplication = (1 << 8), DisableMenuBarTransparency = (1 << 9), FullScreen = (1 << 10), AutoHideToolbar = (1 << 11) } public enum NSApplicationDelegateReply { Success, Cancel, Failure } public enum NSRequestUserAttentionType { CriticalRequest = 0, InformationalRequest = 10 } public enum NSApplicationTerminateReply { Cancel, Now, Later } public enum NSApplicationPrintReply { Cancelled, Success, Failure, ReplyLater } public enum NSApplicationLayoutDirection { LeftToRight = 0, RightToLeft = 1 } public enum NSImageInterpolation { Default, None, Low, Medium, High } public enum NSComposite { Clear, Copy, SourceOver, SourceIn, SourceOut, SourceAtop, DestinationOver, DestinationIn, DestinationOut, DestinationAtop, XOR, PlusDarker, Highlight, PlusLighter, } public enum NSBackingStore { Retained, Nonretained, Buffered } public enum NSWindowOrderingMode { Below = -1, Out, Above, } public enum NSFocusRingPlacement { RingOnly, RingBelow, RingAbove, } public enum NSFocusRingType { Default, None, Exterior } public enum NSColorRenderingIntent { Default, AbsoluteColorimetric, RelativeColorimetric, Perceptual, Saturation } public enum NSRectEdge { MinXEdge, MinYEdge, MaxXEdge, MaxYEdge } public enum NSUserInterfaceLayoutDirection { LeftToRight, RightToLeft } #region NSColorSpace public enum NSColorSpaceModel { Unknown = -1, Gray, RGB, CMYK, LAB, DeviceN, Indexed, Pattern } #endregion #region NSFileWrapper [Flags] public enum NSFileWrapperReadingOptions { Immediate = 1, WithoutMapping = 2 } #endregion #region NSParagraphStyle public enum NSTextTabType { Left, Right, Center, Decimal } public enum NSLineBreakMode { ByWordWrapping, CharWrapping, Clipping, TruncatingHead, TruncatingTail, TruncatingMiddle } #endregion #region NSCell Defines public enum NSType { Any = 0, Int = 1, PositiveInt = 2, Float = 3, PositiveFloat = 4, Double = 6, PositiveDouble = 7 } public enum NSCellType { Null, Text, Image } public enum NSCellAttribute { CellDisabled, CellState, PushInCell, CellEditable, ChangeGrayCell, CellHighlighted, CellLightsByContents, CellLightsByGray, ChangeBackgroundCell, CellLightsByBackground, CellIsBordered, CellHasOverlappingImage, CellHasImageHorizontal, CellHasImageOnLeftOrBottom, CellChangesContents, CellIsInsetButton, CellAllowsMixedState, } public enum NSCellImagePosition { NoImage, ImageOnly, ImageLeft, ImageRight, ImageBelow, ImageAbove, ImageOverlaps, } public enum NSImageScale { ProportionallyDown = 0, AxesIndependently, None, ProportionallyUpOrDown } public enum NSCellStateValue { Mixed = -1, Off, On } [Flags] public enum NSCellMask { NoCell = 0, ContentsCell = 1 << 0, PushInCell = 1 << 1, ChangeGrayCell = 1 << 2, ChangeBackgroundCell = 1 << 3 } [Flags] public enum NSCellHit { None, ContentArea = 1, EditableTextArea = 2, TrackableArae = 4 } public enum NSControlTint : uint { Default = 0, // system 'default' Blue = 1, Graphite = 6, Clear = 7 } public enum NSControlSize { Regular, Small, Mini } public enum NSBackgroundStyle { Light, Dark, Raised, Lowered } #endregion #region NSImage public enum NSImageLoadStatus { Completed, Cancelled, InvalidData, UnexpectedEOF, ReadError } public enum NSImageCacheMode { Default, Always, BySize, Never } #endregion #region NSAlert public enum NSAlertStyle { Warning, Informational, Critical } #endregion #region NSEvent public enum NSEventType { LeftMouseDown = 1, LeftMouseUp = 2, RightMouseDown = 3, RightMouseUp = 4, MouseMoved = 5, LeftMouseDragged = 6, RightMouseDragged = 7, MouseEntered = 8, MouseExited = 9, KeyDown = 10, KeyUp = 11, FlagsChanged = 12, AppKitDefined = 13, SystemDefined = 14, ApplicationDefined = 15, Periodic = 16, CursorUpdate = 17, ScrollWheel = 22, TabletPoint = 23, TabletProximity = 24, OtherMouseDown = 25, OtherMouseUp = 26, OtherMouseDragged = 27, Gesture = 29, Magnify = 30, Swipe = 31, Rotate = 18, BeginGesture = 19, EndGesture = 20, SmartMagnify = 32, QuickLook = 33 } [Flags] public enum NSEventMask : ulong { LeftMouseDown = 1 << NSEventType.LeftMouseDown, LeftMouseUp = 1 << NSEventType.LeftMouseUp, RightMouseDown = 1 << NSEventType.RightMouseDown, RightMouseUp = 1 << NSEventType.RightMouseUp, MouseMoved = 1 << NSEventType.MouseMoved, LeftMouseDragged = 1 << NSEventType.LeftMouseDragged, RightMouseDragged = 1 << NSEventType.RightMouseDragged, MouseEntered = 1 << NSEventType.MouseEntered, MouseExited = 1 << NSEventType.MouseExited, KeyDown = 1 << NSEventType.KeyDown, KeyUp = 1 << NSEventType.KeyUp, FlagsChanged = 1 << NSEventType.FlagsChanged, AppKitDefined = 1 << NSEventType.AppKitDefined, SystemDefined = 1 << NSEventType.SystemDefined, ApplicationDefined = 1 << NSEventType.ApplicationDefined, Periodic = 1 << NSEventType.Periodic, CursorUpdate = 1 << NSEventType.CursorUpdate, ScrollWheel = 1 << NSEventType.ScrollWheel, TabletPoint = 1 << NSEventType.TabletPoint, TabletProximity = 1 << NSEventType.TabletProximity, OtherMouseDown = 1 << NSEventType.OtherMouseDown, OtherMouseUp = 1 << NSEventType.OtherMouseUp, OtherMouseDragged = 1 << NSEventType.OtherMouseDragged, EventGesture = 1 << NSEventType.Gesture, EventMagnify = (uint)1 << NSEventType.Magnify, EventSwipe = (uint)1 << NSEventType.Swipe, EventRotate = (uint)1 << NSEventType.Rotate, EventBeginGesture = (uint)1 << NSEventType.BeginGesture, EventEndGesture = (uint)1 << NSEventType.EndGesture, AnyEvent = UInt32.MaxValue } [Flags] public enum NSEventModifierMask : uint { AlphaShiftKeyMask = 1 << 16, ShiftKeyMask = 1 << 17, ControlKeyMask = 1 << 18, AlternateKeyMask = 1 << 19, CommandKeyMask = 1 << 20, NumericPadKeyMask = 1 << 21, HelpKeyMask = 1 << 22, FunctionKeyMask = 1 << 23, DeviceIndependentModifierFlagsMask = 0xffff0000 } public enum NSPointingDeviceType { Unknown, Pen, Cursor, Eraser } [Flags] public enum NSPointingDeviceMask { Pen = 1, PenLower = 2, PenUpper = 4 } public enum NSKey { A = 0x00, S = 0x01, D = 0x02, F = 0x03, H = 0x04, G = 0x05, Z = 0x06, X = 0x07, C = 0x08, V = 0x09, B = 0x0B, Q = 0x0C, W = 0x0D, E = 0x0E, R = 0x0F, Y = 0x10, T = 0x11, D1 = 0x12, D2 = 0x13, D3 = 0x14, D4 = 0x15, D6 = 0x16, D5 = 0x17, Equal = 0x18, D9 = 0x19, D7 = 0x1A, Minus = 0x1B, D8 = 0x1C, D0 = 0x1D, RightBracket = 0x1E, O = 0x1F, U = 0x20, LeftBracket = 0x21, I = 0x22, P = 0x23, L = 0x25, J = 0x26, Quote = 0x27, K = 0x28, Semicolon = 0x29, Backslash = 0x2A, Comma = 0x2B, Slash = 0x2C, N = 0x2D, M = 0x2E, Period = 0x2F, Grave = 0x32, KeypadDecimal = 0x41, KeypadMultiply = 0x43, KeypadPlus = 0x45, KeypadClear = 0x47, KeypadDivide = 0x4B, KeypadEnter = 0x4C, KeypadMinus = 0x4E, KeypadEquals = 0x51, Keypad0 = 0x52, Keypad1 = 0x53, Keypad2 = 0x54, Keypad3 = 0x55, Keypad4 = 0x56, Keypad5 = 0x57, Keypad6 = 0x58, Keypad7 = 0x59, Keypad8 = 0x5B, Keypad9 = 0x5C, Return = 0x24, Tab = 0x30, Space = 0x31, Escape = 0x35, Command = 0x37, Shift = 0x38, CapsLock = 0x39, Option = 0x3A, Control = 0x3B, RightShift = 0x3C, RightOption = 0x3D, RightControl = 0x3E, Function = 0x3F, VolumeUp = 0x48, VolumeDown = 0x49, Mute = 0x4A, ForwardDelete = 0x75, UpArrow = 0xF700, DownArrow = 0xF701, LeftArrow = 0xF702, RightArrow = 0xF703, F1 = 0xF704, F2 = 0xF705, F3 = 0xF706, F4 = 0xF707, F5 = 0xF708, F6 = 0xF709, F7 = 0xF70A, F8 = 0xF70B, F9 = 0xF70C, F10 = 0xF70D, F11 = 0xF70E, F12 = 0xF70F, F13 = 0xF710, F14 = 0xF711, F15 = 0xF712, F16 = 0xF713, F17 = 0xF714, F18 = 0xF715, F19 = 0xF716, F20 = 0xF717, F21 = 0xF718, F22 = 0xF719, F23 = 0xF71A, F24 = 0xF71B, F25 = 0xF71C, F26 = 0xF71D, F27 = 0xF71E, F28 = 0xF71F, F29 = 0xF720, F30 = 0xF721, F31 = 0xF722, F32 = 0xF723, F33 = 0xF724, F34 = 0xF725, F35 = 0xF726, Insert = 0xF727, Delete = 51, Home = 0xF729, Begin = 0xF72A, End = 0xF72B, PageUp = 0xF72C, PageDown = 0xF72D, PrintScreen = 0xF72E, ScrollLock = 0xF72F, Pause = 0xF730, SysReq = 0xF731, Break = 0xF732, Reset = 0xF733, Stop = 0xF734, Menu = 0xF735, User = 0xF736, System = 0xF737, Print = 0xF738, ClearLine = 0xF739, ClearDisplay = 0xF73A, InsertLine = 0xF73B, DeleteLine = 0xF73C, InsertChar = 0xF73D, DeleteChar = 0xF73E, Prev = 0xF73F, Next = 0xF740, Select = 0xF741, Execute = 0xF742, Undo = 0xF743, Redo = 0xF744, Find = 0xF745, Help = 0xF746, ModeSwitch = 0xF747 } public enum NSEventSubtype { WindowExposed = 0, ApplicationActivated = 1, ApplicationDeactivated = 2, WindowMoved = 4, ScreenChanged = 8, AWT = 16 } public enum NSSystemDefinedEvents { NSPowerOffEventType = 1 } public enum NSEventMouseSubtype { Mouse, TablePoint, TabletProximity, Touch } #endregion #region NSView [Flags] public enum NSViewResizingMask { NotSizable = 0, MinXMargin = 1, WidthSizable = 2, MaxXMargin = 4, MinYMargin = 8, HeightSizable = 16, MaxYMargin = 32 } public enum NSBorderType { NoBorder, LineBorder, BezelBorder, GrooveBorder } public enum NSTextFieldBezelStyle { Square, Rounded } public enum NSViewLayerContentsRedrawPolicy { Never, OnSetNeedsDisplay, DuringViewResize, BeforeViewResize } public enum NSViewLayerContentsPlacement { ScaleAxesIndependently, ScaleProportionallyToFit, ScaleProportionallyToFill, Center, Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, TopLeft, } #endregion #region NSWindow [Flags] public enum NSWindowStyle { Borderless = 0, Titled = 1 << 0, Closable = 1 << 1, Miniaturizable = 1 << 2, Resizable = 1 << 3, Utility = 1 << 4, DocModal = 1 << 6, NonactivatingPanel = 1 << 7, TexturedBackground = 1 << 8, Unscaled = 1 << 11, UnifiedTitleAndToolbar = 1 << 12, Hud = 1 << 13, FullScreenWindow = 1 << 14 } public enum NSWindowSharingType { None, ReadOnly, ReadWrite } public enum NSWindowBackingLocation { Default, VideoMemory, MainMemory, } [Flags] public enum NSWindowCollectionBehavior { Default = 0, CanJoinAllSpaces = 1 << 0, MoveToActiveSpace = 1 << 1, Managed = 1 << 2, Transient = 1 << 3, Stationary = 1 << 4, ParticipatesInCycle = 1 << 5, IgnoresCycle = 1 << 6, FullScreenPrimary = 1 << 7, FullScreenAuxiliary = 1 << 8 } public enum NSWindowNumberListOptions { AllApplication = 1 << 0, AllSpaces = 1 << 4 } public enum NSSelectionDirection { Direct = 0, Next, Previous } public enum NSWindowButton { CloseButton, MiniaturizeButton, ZoomButton, ToolbarButton, DocumentIconButton, DocumentVersionsButton = 6, FullScreenButton } [Flags] public enum NSTouchPhase { Began = 1 << 0, Moved = 1 << 1, Stationary = 1 << 2, Ended = 1 << 3, Cancelled = 1 << 4, Touching = Began | Moved | Stationary, Any = -1 } #endregion #region NSAnimation public enum NSAnimationCurve { EaseInOut, EaseIn, EaseOut, Linear }; public enum NSAnimationBlockingMode { Blocking, Nonblocking, NonblockingThreaded }; #endregion #region NSBox public enum NSTitlePosition { NoTitle, AboveTop, AtTop, BelowTop, AboveBottom, AtBottom, BelowBottom }; public enum NSBoxType { NSBoxPrimary, NSBoxSecondary, NSBoxSeparator, NSBoxOldStyle, NSBoxCustom }; #endregion #region NSButtonCell public enum NSButtonType { MomentaryLightButton, PushOnPushOff, Toggle, Switch, Radio, MomentaryChange, OnOff, MomentaryPushIn } public enum NSBezelStyle { Rounded = 1, RegularSquare, ThickSquare, ThickerSquare, Disclosure, ShadowlessSquare, Circular, TexturedSquare, HelpButton, SmallSquare, TexturedRounded, RoundRect, Recessed, RoundedDisclosure, Inline } public enum NSGradientType { None, ConcaveWeak, ConcaveStrong, ConvexWeak, ConvexStrong } #endregion #region NSGraphics public enum NSWindowDepth { TwentyfourBitRgb = 0x208, SixtyfourBitRgb = 0x210, OneHundredTwentyEightBitRgb = 0x220 } public enum NSCompositingOperation { Clear, Copy, SourceOver, SourceIn, SourceOut, SourceAtop, DestinationOver, DestinationIn, DestinationOut, DestinationAtop, Xor, PlusDarker, Highlight, PlusLighter, } public enum NSAnimationEffect { DissapearingItemDefault = 0, EffectPoof = 10 } #endregion #region NSMatrix public enum NSMatrixMode { Radio, Highlight, List, Track } #endregion #region NSBrowser public enum NSBrowserColumnResizingType { None, Auto, User } public enum NSBrowserDropOperation { On, Above } #endregion #region NSColorPanel public enum NSColorPanelMode { None = -1, Gray = 0, RGB, CMYK, HSB, CustomPalette, ColorList, Wheel, Crayon }; [Flags] public enum NSColorPanelFlags { Gray = 0x00000001, RGB = 0x00000002, CMYK = 0x00000004, HSB = 0x00000008, CustomPalette= 0x00000010, ColorList = 0x00000020, Wheel = 0x00000040, Crayon = 0x00000080, All = 0x0000ffff } #endregion #region NSDocument public enum NSDocumentChangeType { Done, Undone, Cleared, ReadOtherContents, Autosaved, Redone, Discardable = 256 /* New in Lion */ } public enum NSSaveOperationType { Save, SaveAs, SaveTo, Autosave = 3, /* Deprecated name in Lion */ Elsewhere = 3, /* New Lion name */ InPlace = 4, /* New in Lion */ AutoSaveAs = 5 /* New in Mountain Lion */ } #endregion #region NSBezelPath public enum NSLineCapStyle { Butt, Round, Square } public enum NSLineJoinStyle { Miter, Round, Bevel } public enum NSWindingRule { NonZero, EvenOdd } public enum NSBezierPathElement { MoveTo, LineTo, CurveTo, ClosePath } #endregion #region NSRulerView public enum NSRulerOrientation { Horizontal, Vertical } #endregion [Flags] public enum NSDragOperation : uint { None, Copy = 1, Link = 2, Generic = 4, Private = 8, AllObsolete = 15, Move = 16, Delete = 32, All = UInt32.MaxValue } public enum NSTextAlignment { Left, Right, Center, Justified, Natural } [Flags] public enum NSWritingDirection { Natural = -1, LeftToRight, RightToLeft, Embedding = 0, Override = 2, } public enum NSTextMovement { Other = 0, Return = 0x10, Tab = 0x11, Backtab = 0x12, Left = 0x13, Right = 0x14, Up = 0x15, Down = 0x16, Cancel = 0x17 } [Flags] public enum NSMenuProperty { Title = 1 << 0, AttributedTitle = 1 << 1, KeyEquivalent = 1 << 2, Image = 1 << 3, Enabled = 1 << 4, AccessibilityDescription = 1 << 5 } public enum NSFontRenderingMode { Default, Antialiased, IntegerAdvancements, AntialiasedIntegerAdvancements } [Flags] public enum NSPasteboardReadingOptions { AsData = 0, AsString = 1, AsPropertyList = 2, AsKeyedArchive = 4 } public enum NSUnderlineStyle { None = 0x00, Single = 0x01, Thick = 0x02, Double = 0x09 } public enum NSUnderlinePattern { Solid = 0x0000, Dot = 0x0100, Dash = 0x0200, DashDot = 0x0300, DashDotDot = 0x0400 } public enum NSSelectionAffinity { Upstream, Downstream } public enum NSSelectionGranularity { Character, Word, Paragraph } #region NSTrackingArea [Flags] public enum NSTrackingAreaOptions { MouseEnteredAndExited = 0x01, MouseMoved = 0x02, CursorUpdate = 0x04, ActiveWhenFirstResponder = 0x10, ActiveInKeyWindow = 0x20, ActiveInActiveApp = 0x40, ActiveAlways = 0x80, AssumeInside = 0x100, InVisibleRect = 0x200, EnabledDuringMouseDrag = 0x400 } #endregion public enum NSLineSweepDirection { NSLineSweepLeft, NSLineSweepRight, NSLineSweepDown, NSLineSweepUp } public enum NSLineMovementDirection { None, Left, Right, Down, Up } public enum NSTiffCompression { None = 1, CcittFax3 = 3, CcittFax4 = 4, Lzw = 5, [Obsolete ("no longer supported")] Jpeg = 6, Next = 32766, PackBits = 32773, [Obsolete ("no longer supported")] OldJpeg = 32865 } public enum NSBitmapImageFileType { Tiff, Bmp, Gif, Jpeg, Png, Jpeg2000 } public enum NSImageRepLoadStatus { UnknownType = -1, ReadingHeader = -2, WillNeedAllData = -3, InvalidData = -4, UnexpectedEOF = -5, Completed = -6 } [Flags] public enum NSBitmapFormat { AlphaFirst = 1, AlphaNonpremultiplied = 2, FloatingPointSamples = 4 } public enum NSPrintingOrientation { Portrait, Landscape } public enum NSPrintingPaginationMode { Auto, Fit, Clip } [Flags] public enum NSGlyphStorageOptions { ShowControlGlyphs = 1, ShowInvisibleGlyphs = 2, WantsBidiLevels = 4 } [Flags] public enum NSTextStorageEditedFlags { EditedAttributed = 1, EditedCharacters = 2 } public enum NSPrinterTableStatus { Ok, NotFound, Error } public enum NSScrollArrowPosition { MaxEnd, MinEnd, DefaultSetting, None } public enum NSUsableScrollerParts { NoScroller, OnlyArrows, All } public enum NSScrollerPart { None, DecrementPage, Knob, IncrementPage, DecrementLine, IncrementLine, KnobSlot } public enum NSScrollerArrow { IncrementArrow, DecrementArrow } public enum NSPrintingPageOrder { Descending = -1, Special, Ascending, Unknown } [Flags] public enum NSPrintPanelOptions { ShowsCopies = 1, ShowsPageRange = 2, ShowsPaperSize = 4, ShowsOrientation = 8, ShowsScaling = 16, ShowsPrintSelection = 32, ShowsPageSetupAccessory = 256, ShowsPreview = 131072 } public enum NSTextBlockValueType { Absolute, Percentage } public enum NSTextBlockDimension { Width, MinimumWidth, MaximumWidth, Height, MinimumHeight, MaximumHeight } public enum NSTextBlockLayer { Padding = -1, Border, Margin } public enum NSTextBlockVerticalAlignment { Top, Middle, Bottom, Baseline } public enum NSTextTableLayoutAlgorithm { Automatic, Fixed } [Flags] public enum NSTextListOptions { PrependEnclosingMarker = 1 } [Flags] public enum NSFontSymbolicTraits : int { ItalicTrait = (1 << 0), BoldTrait = (1 << 1), ExpandedTrait = (1 << 5), CondensedTrait = (1 << 6), MonoSpaceTrait = (1 << 10), VerticalTrait = (1 << 11), UIOptimizedTrait = (1 << 12), UnknownClass = 0 << 28, OldStyleSerifsClass = 1 << 28, TransitionalSerifsClass = 2 << 28, ModernSerifsClass = 3 << 28, ClarendonSerifsClass = 4 << 28, SlabSerifsClass = 5 << 28, FreeformSerifsClass = 7 << 28, SansSerifClass = 8 << 28, OrnamentalsClass = 9 << 28, ScriptsClass = 10 << 28, SymbolicClass = 12 << 28, FamilyClassMask = (int) -268435456, } [Flags] public enum NSFontTraitMask { Italic = 1, Bold = 2, Unbold = 4, NonStandardCharacterSet = 8, Narrow = 0x10, Expanded = 0x20, Condensed = 0x40, SmallCaps = 0x80, Poster = 0x100, Compressed = 0x200, FixedPitch = 0x400, Unitalic = 0x1000000 } [Flags] public enum NSPasteboardWritingOptions { WritingPromised = 1 << 9 } public enum NSToolbarDisplayMode { Default, IconAndLabel, Icon, Label } public enum NSToolbarSizeMode { Default, Regular, Small } public enum NSAlertType { ErrorReturn = -2, OtherReturn, AlternateReturn, DefaultReturn } public enum NSPanelButtonType { Cancel, Ok } public enum NSTableViewColumnAutoresizingStyle { None = 0, Uniform, Sequential, ReverseSequential, LastColumnOnly, FirstColumnOnly } public enum NSTableViewSelectionHighlightStyle { None = -1, Regular = 0, SourceList = 1 } public enum NSTableViewDraggingDestinationFeedbackStyle { None = -1, Regular = 0, SourceList = 1 } public enum NSTableViewDropOperation { On, Above } [Flags] public enum NSTableColumnResizing { None = -1, Autoresizing = ( 1 << 0 ), UserResizingMask = ( 1 << 1 ) } [Flags] public enum NSTableViewGridStyle { None = 0, SolidVerticalLine = 1 << 0, SolidHorizontalLine = 1 << 1, DashedHorizontalGridLine = 1 << 3 } [Flags] public enum NSGradientDrawingOptions { None = 0, BeforeStartingLocation = (1 << 0), AfterEndingLocation = (1 << 1) } public enum NSImageAlignment { Center = 0, Top, TopLeft, TopRight, Left, Bottom, BottomLeft, BottomRight, Right } public enum NSImageFrameStyle { None = 0, Photo, GrayBezel, Groove, Button } public enum NSSpeechBoundary { Immediate = 0, hWord, Sentence } public enum NSSplitViewDividerStyle { Thick = 1, Thin = 2, PaneSplitter = 3 } public enum NSImageScaling { ProportionallyDown = 0, AxesIndependently, None, ProportionallyUpOrDown } public enum NSSegmentStyle { Automatic = 0, Rounded = 1, TexturedRounded = 2, RoundRect = 3, TexturedSquare = 4, Capsule = 5, SmallSquare = 6 } public enum NSSegmentSwitchTracking { SelectOne = 0, SelectAny = 1, Momentary = 2 } public enum NSTickMarkPosition { Below, Above, Left, Right } public enum NSSliderType { Linear = 0, Circular = 1 } public enum NSTokenStyle { Default, PlainText, Rounded } [Flags] public enum NSWorkspaceLaunchOptions { Print = 2, InhibitingBackgroundOnly = 0x80, WithoutAddingToRecents = 0x100, WithoutActivation = 0x200, Async = 0x10000, AllowingClassicStartup = 0x20000, PreferringClassic = 0x40000, NewInstance = 0x80000, Hide = 0x100000, HideOthers = 0x200000, Default = Async | AllowingClassicStartup } [Flags] public enum NSWorkspaceIconCreationOptions { NSExcludeQuickDrawElements = 1 << 1, NSExclude10_4Elements = 1 << 2 } public enum NSPathStyle { NSPathStyleStandard, NSPathStyleNavigationBar, NSPathStylePopUp } public enum NSTabViewType { NSTopTabsBezelBorder, NSLeftTabsBezelBorder, NSBottomTabsBezelBorder, NSRightTabsBezelBorder, NSNoTabsBezelBorder, NSNoTabsLineBorder, NSNoTabsNoBorder, } public enum NSTabState { Selected, Background, Pressed } public enum NSLevelIndicatorStyle { Relevancy, ContinuousCapacity, DiscreteCapacity, RatingLevel } [Flags] public enum NSFontCollectionOptions { ApplicationOnlyMask = 1 } public enum NSCollectionViewDropOperation { On = 0, Before = 1 } public enum NSDatePickerStyle { TextFieldAndStepper, ClockAndCalendar, TextField } public enum NSDatePickerMode { Single, Range } [Flags] public enum NSDatePickerElementFlags { HourMinute = 0xc, HourMinuteSecond = 0xe, TimeZone = 0x10, YearMonthDate = 0xc0, YearMonthDateDay = 0xe0, Era = 0x100 } public enum NSOpenGLContextParameter { [Obsolete] SwapRectangle = 200, [Obsolete] SwapRectangleEnable = 201, [Obsolete] RasterizationEnable = 221, [Obsolete] StateValidation = 301, [Obsolete] SurfaceSurfaceVolatile = 306, SwapInterval = 222, SurfaceOrder = 235, SurfaceOpacity = 236, [Lion] SurfaceBackingSize = 304, [Lion] ReclaimResources = 308, [Lion] CurrentRendererID = 309, [Lion] GpuVertexProcessing = 310, [Lion] GpuFragmentProcessing = 311, [Lion] HasDrawable = 314, [Lion] MpsSwapsInFlight = 315 } public enum NSSurfaceOrder { AboveWindow = 1, BelowWindow = -1 } public enum NSOpenGLPixelFormatAttribute { AllRenderers = 1, DoubleBuffer = 5, [Lion] TrippleBuffer = 3, Stereo = 6, AuxBuffers = 7, ColorSize = 8, AlphaSize = 11, DepthSize = 12, StencilSize = 13, AccumSize = 14, MinimumPolicy = 51, MaximumPolicy = 52, OffScreen = 53, FullScreen = 54, SampleBuffers = 55, Samples = 56, AuxDepthStencil = 57, ColorFloat = 58, Multisample = 59, Supersample = 60, SampleAlpha = 61, RendererID = 70, SingleRenderer = 71, NoRecovery = 72, Accelerated = 73, ClosestPolicy = 74, BackingStore = 76, Window = 80, Compliant = 83, ScreenMask = 84, PixelBuffer = 90, RemotePixelBuffer = 91, AllowOfflineRenderers = 96, AcceleratedCompute = 97, // Specify the profile [Lion] OpenGLProfile = 99, VirtualScreenCount = 128, [Obsolete] Robust = 75, [Obsolete] MPSafe = 78, [Obsolete] MultiScreen = 81 } public enum NSOpenGLProfile { VersionLegacy = 0x1000, // Legacy Version3_2Core = 0x3200 // 3.2 or better } public enum NSAlertButtonReturn { First = 1000, Second = 1001, Third = 1002, } public enum NSOpenGLGlobalOption { FormatCacheSize = 501, ClearFormatCache = 502, RetainRenderers = 503, [Lion] UseBuildCache = 506, [Obsolete] ResetLibrary = 504 } public enum NSGLTextureTarget { T2D = 0x0de1, CubeMap = 0x8513, RectangleExt = 0x84F5, } public enum NSGLFormat { RGB = 0x1907, RGBA = 0x1908, DepthComponent = 0x1902, } public enum NSGLTextureCubeMap { None = 0, PositiveX = 0x8515, PositiveY = 0x8517, PositiveZ = 0x8519, NegativeX = 0x8516, NegativeY = 0x8517, NegativeZ = 0x851A } public enum NSGLColorBuffer { Front = 0x0404, Back = 0x0405, Aux0 = 0x0409 } public enum NSProgressIndicatorThickness { Small = 10, Regular = 14, Aqua = 12, Large = 18 } public enum NSProgressIndicatorStyle { Bar, Spinning } public enum NSPopUpArrowPosition { None, Center, Bottom } public static class NSFileTypeForHFSTypeCode { public static readonly string ComputerIcon = "root"; public static readonly string DesktopIcon = "desk"; public static readonly string FinderIcon = "FNDR"; } // These constants specify the possible states of a drawer. public enum NSDrawerState { Closed = 0, Opening = 1, Open = 2, Closing = 3 } public enum NSWindowLevel { Normal = 0, Dock = 20, Floating = 3, MainMenu = 24, ModalPanel = 8, PopUpMenu = 101, ScreenSaver = 1000, Status = 25, Submenu = 3, TornOffMenu = 3 } public enum NSRuleEditorRowType{ Simple = 0, Compound } public enum NSRuleEditorNestingMode { Single, List, Compound, Simple } public enum NSGlyphInscription { Base, Below, Above, Overstrike, OverBelow } public enum NSTypesetterBehavior { Latest = -1, Original = 0, Specific_10_2_WithCompatibility = 1, Specific_10_2 = 2, Specific_10_3 = 3, Specific_10_4 = 4, } [Flags] public enum NSRemoteNotificationType { None = 0, Badge = 1 } public enum NSScrollViewFindBarPosition { AboveHorizontalRuler = 0, AboveContent, BelowContent } public enum NSScrollerStyle { Legacy = 0, Overlay } public enum NSScrollElasticity { Automatic = 0, None, Allowed } public enum NSScrollerKnobStyle { Default = 0, Dark = 1, Light = 2 } [Flags] public enum NSEventPhase { None, Began = 1, Stationary = 2, Changed = 4, Ended = 8, Cancelled = 16 } [Flags] public enum NSEventSwipeTrackingOptions { LockDirection = 1, ClampGestureAmount = 2 } public enum NSEventGestureAxis { None, Horizontal, Vertical } public enum NSLayoutRelation { LessThanOrEqual = -1, Equal = 0, GreaterThanOrEqual = 1 } public enum NSLayoutAttribute { NoAttribute = 0, Left = 1, Right, Top, Bottom, Leading, Trailing, Width, Height, CenterX, CenterY, Baseline } public enum NSLayoutFormatOptions { None = 0, AlignAllLeft = (1 << NSLayoutAttribute.Left), AlignAllRight = (1 << NSLayoutAttribute.Right), AlignAllTop = (1 << NSLayoutAttribute.Top), AlignAllBottom = (1 << NSLayoutAttribute.Bottom), AlignAllLeading = (1 << NSLayoutAttribute.Leading), AlignAllTrailing = (1 << NSLayoutAttribute.Trailing), AlignAllCenterX = (1 << NSLayoutAttribute.CenterX), AlignAllCenterY = (1 << NSLayoutAttribute.CenterY), AlignAllBaseline = (1 << NSLayoutAttribute.Baseline), AlignmentMask = 0xFFFF, /* choose only one of these three */ DirectionLeadingToTrailing = 0 << 16, // default DirectionLeftToRight = 1 << 16, DirectionRightToLeft = 2 << 16, DirectionMask = 0x3 << 16, } public enum NSLayoutConstraintOrientation { Horizontal, Vertical } public enum NSLayoutPriority { Required = 1000, DefaultHigh = 750, DragThatCanResizeWindow = 510, WindowSizeStayPut = 500, DragThatCannotResizeWindow = 490, DefaultLow = 250, FittingSizeCompression = 50, } public enum NSPopoverAppearance { Minimal, HUD } public enum NSPopoverBehavior { ApplicationDefined, Transient, Semitransient } public enum NSTableViewRowSizeStyle { Default = -1, Custom = 0, Small, Medium, Large } [Flags] public enum NSTableViewAnimation { None, Fade = 1, Gap = 2, SlideUp = 0x10, SlideDown = 0x20, SlideLeft = 0x30, SlideRight = 0x40 } [Flags] public enum NSDraggingItemEnumerationOptions { Concurrent = 1 << 0, ClearNonenumeratedImages = 1 << 16 } public enum NSDraggingFormation { Default, None, Pile, List, Stack } public enum NSDraggingContext { OutsideApplication, WithinApplication } public enum NSWindowAnimationBehavior { Default = 0, None = 2, DocumentWindow, UtilityWindow, AlertPanel } [Lion] public enum NSTextFinderAction { ShowFindInterface = 1, NextMatch = 2, PreviousMatch = 3, ReplaceAll = 4, Replace = 5, ReplaceAndFind = 6, SetSearchString = 7, ReplaceAllInSelection = 8, SelectAll = 9, SelectAllInSelection = 10, HideFindInterface = 11, ShowReplaceInterface = 12, HideReplaceInterface = 13 } [Flags] public enum NSFontPanelMode { FaceMask = 1 << 0, SizeMask = 1 << 1, CollectionMask = 1 << 2, UnderlineEffectMask = 1<<8, StrikethroughEffectMask = 1<<9, TextColorEffectMask = 1<< 10, DocumentColorEffectMask = 1<<11, ShadowEffectMask = 1<<12, AllEffectsMask = 0XFFF00, StandardMask = 0xFFFF, AllModesMask = unchecked( (int)0xFFFFFFFF ) } [Flags] public enum NSFontCollectionVisibility { Process = 1 << 0, User = 1 << 1, Computer = 1 << 2, } public enum NSSharingContentScope { Item, Partial, Full } public enum NSSharingServiceName { PostOnFacebook, PostOnTwitter, PostOnSinaWeibo, ComposeEmail, ComposeMessage, SendViaAirDrop, AddToSafariReadingList, AddToIPhoto, AddToAperture, UseAsTwitterProfileImage, UseAsDesktopPicture, PostImageOnFlickr, PostVideoOnVimeo, PostVideoOnYouku, PostVideoOnTudou } [Flags] public enum NSTypesetterControlCharacterAction { ZeroAdvancement = 1 << 0, Whitespace = 1 << 1, HorizontalTab = 1 << 2, LineBreak = 1 << 3, ParagraphBreak = 1 << 4, ContainerBreak = 1 << 5, } }
// // System.Data.SqlTypes.SqlBinary // // Author: // Rodrigo Moya (rodrigo@ximian.com) // Tim Coleman (tim@timcoleman.com) // Ville Palo (vi64pa@koti.soon.fi) // // (C) Ximian, Inc. // (C) Copyright 2002 Tim Coleman // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; namespace System.Data.SqlTypes { /// <summary> /// Represents a variable-length stream of binary data to be stored in or retrieved from a database. /// </summary> public struct SqlBinary : INullable, IComparable { #region Fields byte[] value; private bool notNull; public static readonly SqlBinary Null; #endregion #region Constructors public SqlBinary (byte[] value) { this.value = value; notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public byte this[int index] { get { if (this.IsNull) throw new SqlNullValueException ("The property contains Null."); else if (index >= this.Length) throw new IndexOutOfRangeException ("The index parameter indicates a position beyond the length of the byte array."); else return value [index]; } } public int Length { get { if (this.IsNull) throw new SqlNullValueException ("The property contains Null."); else return value.Length; } } public byte[] Value { get { if (this.IsNull) throw new SqlNullValueException ("The property contains Null."); else return value; } } #endregion #region Methods public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SqlBinary)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlBinary")); else if (((SqlBinary)value).IsNull) return 1; else return Compare (this, (SqlBinary)value); } public static SqlBinary Concat (SqlBinary x, SqlBinary y) { return (x + y); } public override bool Equals (object value) { if (!(value is SqlBinary)) return false; else if (this.IsNull && ((SqlBinary)value).IsNull) return true; else if (((SqlBinary)value).IsNull) return false; else return (bool) (this == (SqlBinary)value); } public static SqlBoolean Equals(SqlBinary x, SqlBinary y) { return (x == y); } public override int GetHashCode () { // FIXME: I'm not sure is this a right way int result = 10; for (int i = 0; i < value.Length; i++) { result = 91 * result + (int)value [i]; } return result; } #endregion #region Operators public static SqlBoolean GreaterThan (SqlBinary x, SqlBinary y) { return (x > y); } public static SqlBoolean GreaterThanOrEqual (SqlBinary x, SqlBinary y) { return (x >= y); } public static SqlBoolean LessThan (SqlBinary x, SqlBinary y) { return (x < y); } public static SqlBoolean LessThanOrEqual (SqlBinary x, SqlBinary y) { return (x <= y); } public static SqlBoolean NotEquals (SqlBinary x, SqlBinary y) { return (x != y); } public SqlGuid ToSqlGuid () { return (SqlGuid)this; } public override string ToString () { if (!notNull) return "Null"; return "SqlBinary(" + value.Length + ")"; } #endregion #region Operators [MonoTODO] public static SqlBinary operator + (SqlBinary x, SqlBinary y) { byte [] b = new byte [x.Value.Length + y.Value.Length]; int j = 0; int i; for (i = 0; i < x.Value.Length; i++) b [i] = x.Value [i]; for (; i < (x.Value.Length + y.Value.Length); i++) { b [i] = y.Value [j]; j++; } return new SqlBinary (b); } public static SqlBoolean operator == (SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (Compare (x, y) == 0); } public static SqlBoolean operator > (SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean (Compare (x, y) > 0); } public static SqlBoolean operator >= (SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean (Compare (x, y) >= 0); } public static SqlBoolean operator != (SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (Compare (x, y) != 0); } public static SqlBoolean operator < (SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean (Compare (x, y) < 0); } public static SqlBoolean operator <= (SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean (Compare (x, y) <= 0); } public static explicit operator byte[] (SqlBinary x) { return x.Value; } public static explicit operator SqlBinary (SqlGuid x) { return new SqlBinary (x.ToByteArray ()); } public static implicit operator SqlBinary (byte[] x) { return new SqlBinary (x); } #endregion // Helper method to Compare methods and operators. // Returns 0 if x == y // 1 if x > y // -1 if x < y private static int Compare(SqlBinary x, SqlBinary y) { int LengthDiff = 0; // If they are different size test are bytes something else than 0 if (x.Value.Length != y.Value.Length) { LengthDiff = x.Value.Length - y.Value.Length; // If more than zero, x is longer if (LengthDiff > 0) { for (int i = x.Value.Length - 1; i > x.Value.Length - LengthDiff; i--) { // If byte is more than zero the x is bigger if (x.Value [i] != (byte)0) return 1; } } else { for (int i = y.Value.Length - 1; i > y.Value.Length - LengthDiff; i--) { // If byte is more than zero then y is bigger if (y.Value [i] != (byte)0) return -1; } } } // choose shorter int lenght = (LengthDiff > 0) ? y.Value.Length : x.Value.Length; for (int i = lenght - 1 ; i > 0; i--) { byte X = x.Value [i]; byte Y = y.Value [i]; if (X > Y) return 1; else if (X < Y) return -1; } // If we are here, x and y were same size return 0; } } }
using System; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Xbehave.Test.Infrastructure; using Xunit; using Xunit.Abstractions; namespace Xbehave.Test { // In order to release allocated resources // As a developer // I want to register objects for disposal after a scenario has run public class ObjectDisposalFeature : Feature { [Background] public void Background() => "Given no events have occurred" .x(() => typeof(ObjectDisposalFeature).ClearTestEvents()); [Scenario] [Example(typeof(AStepWithThreeDisposables))] [Example(typeof(ThreeStepsWithDisposables))] [Example(typeof(AnAsyncStepWithThreeDisposables))] public void ManyDisposablesInASingleStep(Type feature, ITestResultMessage[] results) { $"Given {feature}" .x(() => { }); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "And there should be no failures" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "And the disposables should each have been disposed in reverse order" .x(() => Assert.Equal(new[] { "disposed3", "disposed2", "disposed1" }, typeof(ObjectDisposalFeature).GetTestEvents())); } [Scenario] public void ADisposableWhichThrowExceptionsWhenDisposed(Type feature, ITestResultMessage[] results) { "Given a step with three disposables which throw exceptions when disposed" .x(() => feature = typeof(StepWithThreeBadDisposables)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then the there should be at least two results" .x(() => Assert.InRange(results.Length, 2, int.MaxValue)); "And the first n-1 results should be passes" .x(() => Assert.All(results.Reverse().Skip(1), result => Assert.IsAssignableFrom<ITestPassed>(result))); "And the last result should be a failure" .x(() => Assert.IsAssignableFrom<ITestFailed>(results.Last())); "And the disposables should be disposed in reverse order" .x(() => Assert.Equal(new[] { "disposed3", "disposed2", "disposed1" }, typeof(ObjectDisposalFeature).GetTestEvents())); } [Scenario] [Example(typeof(StepsFollowedByAFailingStep))] [Example(typeof(StepFailsToComplete))] public void FailingSteps(Type feature, ITestResultMessage[] results) { $"Given {feature}" .x(() => { }); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one failure" .x(() => Assert.Single(results.OfType<ITestFailed>())); "And the disposables should be disposed in reverse order" .x(() => Assert.Equal(new[] { "disposed3", "disposed2", "disposed1" }, typeof(ObjectDisposalFeature).GetTestEvents())); } [Scenario] public void DisposablesAndTeardowns(Type feature, ITestResultMessage[] results) { "Given steps with disposables and teardowns" .x(() => feature = typeof(StepsWithDisposablesAndTeardowns)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "And there should be no failures" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "And the disposables and teardowns should be disposed/executed in reverse order" .x(() => Assert.Equal(new[] { "teardown4", "disposed3", "teardown2", "disposed1" }, typeof(ObjectDisposalFeature).GetTestEvents())); } [Scenario] public void NullDisposable() => "Given a null body" .x(c => ((IDisposable)null).Using(c)); private static class AStepWithThreeDisposables { [Scenario] public static void Scenario(Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given some disposables" .x(c => { disposable0 = new Disposable(1).Using(c); disposable1 = new Disposable(2).Using(c); disposable2 = new Disposable(3).Using(c); }); "When using the disposables" .x(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); } } private static class StepWithThreeBadDisposables { [Scenario] public static void Scenario(Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given some disposables" .x(c => { disposable0 = new BadDisposable(1).Using(c); disposable1 = new BadDisposable(2).Using(c); disposable2 = new BadDisposable(3).Using(c); }); "When using the disposables" .x(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); } } private static class ThreeStepsWithDisposables { [Scenario] public static void Scenario(Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given a disposable" .x(c => disposable0 = new Disposable(1).Using(c)); "And another disposable" .x(c => disposable1 = new Disposable(2).Using(c)); "And another disposable" .x(c => disposable2 = new Disposable(3).Using(c)); "When using the disposables" .x(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); } } private static class StepsFollowedByAFailingStep { [Scenario] public static void Scenario(Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given a disposable" .x(c => disposable0 = new Disposable(1).Using(c)); "And another disposable" .x(c => disposable1 = new Disposable(2).Using(c)); "And another disposable" .x(c => disposable2 = new Disposable(3).Using(c)); "When using the disposables" .x(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); "Then something happens" .x(() => Assert.Equal(0, 1)); } } private static class StepFailsToComplete { [Scenario] public static void Scenario() => "Given some disposables" .x(c => { new Disposable(1).Using(c); new Disposable(2).Using(c); new Disposable(3).Using(c); throw new InvalidOperationException(); }); } private static class AnAsyncStepWithThreeDisposables { [Scenario] public static void Scenario(Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given some disposables" .x(async c => { await Task.Yield(); disposable0 = new Disposable(1).Using(c); disposable1 = new Disposable(2).Using(c); disposable2 = new Disposable(3).Using(c); }); "When using the disposables" .x(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); } } private static class StepsWithDisposablesAndTeardowns { [Scenario] public static void Scenario() { "Given something" .x(c => new Disposable(1).Using(c)) .Teardown(() => typeof(ObjectDisposalFeature).SaveTestEvent("teardown2")); "And something else" .x(c => new Disposable(3).Using(c)) .Teardown(() => typeof(ObjectDisposalFeature).SaveTestEvent("teardown4")); } } private class Disposable : IDisposable { private readonly int number; private bool isDisposed; public Disposable(int number) => this.number = number; ~Disposable() { this.Dispose(false); } public void Use() { if (this.isDisposed) { throw new ObjectDisposedException(this.GetType().FullName); } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { var @event = string.Concat("disposed", this.number.ToString(CultureInfo.InvariantCulture)); typeof(ObjectDisposalFeature).SaveTestEvent(@event); this.isDisposed = true; } } } private sealed class BadDisposable : Disposable { public BadDisposable(int number) : base(number) { } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { throw new NotImplementedException(); } } } } }
using System; using System.Linq.Expressions; using NUnit.Framework; using StructureMap.Testing; namespace StructureMap.AutoMocking.Testing { [TestFixture] public abstract class AutoMockerTester { protected abstract AutoMocker<T> createAutoMocker<T>() where T : class; protected abstract void setExpectation<T, TResult>(T mock, Expression<Func<T, TResult>> functionCall, TResult expectedResult) where T : class; public class ConcreteThing { private readonly IMockedService _service; private readonly IMockedService2 _service2; public ConcreteThing(IMockedService service, IMockedService2 service2) { _service = service; _service2 = service2; } public IMockedService Service { get { return _service; } } public IMockedService2 Service2 { get { return _service2; } } } public class ConcreteClass { private readonly IMockedService _service; private readonly IMockedService2 _service2; private readonly IMockedService3 _service3; public ConcreteClass(IMockedService service, IMockedService2 service2, IMockedService3 service3) { _service = service; _service2 = service2; _service3 = service3; } public virtual string Name { get { return _service.Name; } } public IMockedService Service { get { return _service; } } public IMockedService2 Service2 { get { return _service2; } } public IMockedService3 Service3 { get { return _service3; } } public void CallService() { _service.Go(); } } public interface IMockedService { string Name { get; } void Go(); } public interface IMockedService2 { void Go(); } public interface IMockedService3 { void Go(); } public class StubService : IMockedService { private readonly string _name; public StubService() { } public StubService(string name) { _name = name; } #region IMockedService Members public string Name { get { return _name; } } public void Go() { throw new NotImplementedException(); } #endregion } public class ClassWithArray { private readonly IMockedService[] _services; public ClassWithArray(IMockedService[] services) { _services = services; } public IMockedService[] Services { get { return _services; } } } public interface IAnotherService { } [Test] public void CanInjectAnArrayOfMockServices1() { AutoMocker<ClassWithArray> mocker = createAutoMocker<ClassWithArray>(); IMockedService[] services = mocker.CreateMockArrayFor<IMockedService>(3); ClassWithArray theClass = mocker.ClassUnderTest; theClass.Services.Length.ShouldEqual(3); } [Test] public void CanInjectAnArrayOfMockServices3() { AutoMocker<ClassWithArray> mocker = createAutoMocker<ClassWithArray>(); IMockedService[] services = mocker.CreateMockArrayFor<IMockedService>(3); mocker.PartialMockTheClassUnderTest(); ClassWithArray theClass = mocker.ClassUnderTest; theClass.Services.Length.ShouldEqual(3); } [Test] public void GetTheSameConcreteClassTwiceFromCreate() { AutoMocker<ConcreteClass> autoMocker = createAutoMocker<ConcreteClass>(); ConcreteClass concreteClass = autoMocker.ClassUnderTest; Assert.AreSame(concreteClass, autoMocker.ClassUnderTest); Assert.AreSame(concreteClass, autoMocker.ClassUnderTest); Assert.AreSame(concreteClass, autoMocker.ClassUnderTest); } [Test] public void TheAutoMockerPushesInMocksAndAPreBuiltStubForAllOfTheConstructorArguments() { AutoMocker<ConcreteClass> autoMocker = createAutoMocker<ConcreteClass>(); var stub = new StubService(); autoMocker.Inject<IMockedService>(stub); var service2 = autoMocker.Get<IMockedService2>(); var service3 = autoMocker.Get<IMockedService3>(); ConcreteClass concreteClass = autoMocker.ClassUnderTest; Assert.AreSame(stub, concreteClass.Service); Assert.AreSame(service2, concreteClass.Service2); Assert.AreSame(service3, concreteClass.Service3); } [Test] public void TheAutoMockerPushesInMocksForAllOfTheConstructorArgumentsForAPartialMock() { AutoMocker<ConcreteClass> autoMocker = createAutoMocker<ConcreteClass>(); var service = autoMocker.Get<IMockedService>(); var service2 = autoMocker.Get<IMockedService2>(); var service3 = autoMocker.Get<IMockedService3>(); autoMocker.PartialMockTheClassUnderTest(); ConcreteClass concreteClass = autoMocker.ClassUnderTest; Assert.AreSame(service, concreteClass.Service); Assert.AreSame(service2, concreteClass.Service2); Assert.AreSame(service3, concreteClass.Service3); } [Test] public void UseConcreteClassFor() { AutoMocker<ConcreteClass> mocker = createAutoMocker<ConcreteClass>(); mocker.UseConcreteClassFor<ConcreteThing>(); var thing = mocker.Get<ConcreteThing>(); thing.ShouldBeOfType<ConcreteThing>(); Assert.AreSame(mocker.Get<IMockedService>(), thing.Service); Assert.AreSame(mocker.Get<IMockedService2>(), thing.Service2); } [Test] public void UseTheAutoMockerToStartUpTheConcreteClass() { AutoMocker<ConcreteClass> autoMocker = createAutoMocker<ConcreteClass>(); setExpectation(autoMocker.Get<IMockedService>(), x => x.Name, "Jeremy"); autoMocker.ClassUnderTest.Name.ShouldEqual("Jeremy"); } [Test] public void UseTheAutoMockerToStartUpTheConcreteClassAsAPartialMockAndSetTheNameMethodUp() { AutoMocker<ConcreteClass> autoMocker = createAutoMocker<ConcreteClass>(); autoMocker.PartialMockTheClassUnderTest(); ConcreteClass concreteClass = autoMocker.ClassUnderTest; setExpectation(concreteClass, x => x.Name, "Max"); concreteClass.Name.ShouldEqual("Max"); } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Siren.IO; using Siren.Protocol.Binary; namespace Siren.Protocol.Json { public class JsonReader : BaseProtocolReader { private JObject mJObject; private Stack<JToken> mJsonTokens = new Stack<JToken>(); private JToken mCurrenToken; private Stack<uint> mArrayInices = new Stack<uint>(); public override void Accept(ArraySegment<byte> data) { var str = Encoding.UTF8.GetString(data.Array, data.Offset, data.Count); mJObject = JObject.Parse(str); mCurrenToken = mJObject; mJsonTokens.Push(mCurrenToken); } public void Accept(string str) { mJObject = JObject.Parse(str); mCurrenToken = mJObject; mJsonTokens.Push(mCurrenToken); } public override bool IsEnd() { return false; } public override void OnVersion() { } public override void OnStructBegin() { } public override void OnStructEnd() { } public override void OnListBegin(out SirenFieldType dataType, out int count) { JToken currenToken = CurrentToken(); count = currenToken.Count(); mArrayInices.Push(0); dataType = SirenFieldType.Bool; } public override void OnListEnd() { mArrayInices.Pop(); } public override void OnDictionaryBegin(out SirenFieldType keyDataType, out SirenFieldType valueDataType, out int count) { JToken currenToken = CurrentToken(); count = currenToken.Count() / 2; mArrayInices.Push(0); keyDataType = SirenFieldType.Bool; valueDataType = SirenFieldType.Bool; } public override void OnDictionaryEnd() { mArrayInices.Pop(); } public override int OnPropertyBegin(string name, ushort id, SirenFieldType dataType, out ushort outId, out SirenFieldType outDataType) { outId = 0; outDataType = SirenFieldType.Struct; JToken outToken; JToken currenToken = CurrentToken(); outToken = currenToken[name]; if (outToken != null) { mJsonTokens.Push(outToken); return 0; } return -1; } public override void OnPropertyEnd() { mJsonTokens.Pop(); } public override void OnPropertySkip(SirenFieldType dataType) { mJsonTokens.Pop(); } public override object OnValue(Type type) { JToken currenToken = CurrentToken(); if (type == typeof(bool)) { return (bool)currenToken; } else if (type == typeof(char)) { return (char)currenToken; } else if (type == typeof(short)) { return (short)currenToken; } else if (type == typeof(int)) { return (int)currenToken; } else if (type == typeof(Int64)) { return (Int64)currenToken; } else if (type == typeof(byte)) { return (byte)currenToken; } else if (type == typeof(ushort)) { return (ushort)currenToken; } else if (type == typeof(uint)) { return (uint)currenToken; } else if (type == typeof(UInt64)) { return (UInt64)currenToken; } else if (type == typeof(float)) { return (float)currenToken; } else if (type == typeof(double)) { return (double)currenToken; } else { if (type.IsEnum) { return (uint)currenToken; } else { Console.WriteLine("Invalid value type:{0}", type); } } return null; } public override string OnString() { JToken currenToken = CurrentToken(); return (string)currenToken; } public override byte[] OnMemoryData() { JToken currenToken = CurrentToken(); var str = (string)currenToken; var data = Base91.Decode(str); return data; } public JToken CurrentToken() { JToken currenToken = mJsonTokens.Peek(); if (mArrayInices.Count <= 0) { return currenToken; } uint index = mArrayInices.Pop(); if (currenToken is JArray) { currenToken = (currenToken as JArray)[(int)index]; } else { JToken temp = currenToken.First; for (int i = 0; i < index; i++) { temp = temp.Next; } currenToken = temp; } ++index; mArrayInices.Push(index); return currenToken; } public override void OnError() { } public override T OnProperty<T>(string name, ushort id, bool withHeader = true) { ushort outId; SirenFieldType outDataType; int r = OnPropertyBegin(name, id, SirenFactory.GetPropertyType(typeof(T)), out outId, out outDataType); if (r == 0) { var obj = OnValue(typeof(T)); OnPropertyEnd(); return (T)obj; } return default(T); } } }
// Copyright (c) 2011-2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) #if __MonoCS__ using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using IBusDotNet; using Palaso.UI.WindowsForms.Keyboarding; using Palaso.UI.WindowsForms.Keyboarding.Interfaces; using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces; using Palaso.UI.WindowsForms.Keyboarding.Types; using Palaso.WritingSystems; namespace Palaso.UI.WindowsForms.Keyboarding.Linux { /// <summary> /// Class for handling ibus keyboards on Linux. Currently just a wrapper for KeyboardSwitcher. /// </summary> [CLSCompliant(false)] public class IbusKeyboardAdaptor: IKeyboardAdaptor { private IIbusCommunicator IBusCommunicator; private bool m_needIMELocation; /// <summary> /// Initializes a new instance of the /// <see cref="Palaso.UI.WindowsForms.Keyboard.Linux.IbusKeyboardAdaptor"/> class. /// </summary> public IbusKeyboardAdaptor(): this(new IbusCommunicator()) { } /// <summary> /// Used in unit tests /// </summary> public IbusKeyboardAdaptor(IIbusCommunicator ibusCommunicator) { IBusCommunicator = ibusCommunicator; if (!IBusCommunicator.Connected) return; if (KeyboardController.EventProvider != null) { KeyboardController.EventProvider.ControlAdded += OnControlRegistered; KeyboardController.EventProvider.ControlRemoving += OnControlRemoving; } } protected virtual void InitKeyboards() { foreach (var ibusKeyboard in GetIBusKeyboards()) { var keyboard = new IbusKeyboardDescription(this, ibusKeyboard); KeyboardController.Manager.RegisterKeyboard(keyboard); } } protected virtual IBusEngineDesc[] GetIBusKeyboards() { if (!IBusCommunicator.Connected) return new IBusEngineDesc[0]; var ibusWrapper = new InputBus(IBusCommunicator.Connection); return ibusWrapper.ListActiveEngines(); } internal IBusEngineDesc[] GetAllIBusKeyboards() { if (!IBusCommunicator.Connected) return new IBusEngineDesc[0]; var ibusWrapper = new InputBus(IBusCommunicator.Connection); return ibusWrapper.ListEngines(); } internal bool CanSetIbusKeyboard() { if (!IBusCommunicator.Connected) return false; IBusCommunicator.FocusIn(); if (GlobalCachedInputContext.InputContext == null) return false; return true; } internal bool IBusKeyboardAlreadySet(IbusKeyboardDescription keyboard) { // check our cached value if (GlobalCachedInputContext.Keyboard == keyboard) return true; if (keyboard == null || keyboard.IBusKeyboardEngine == null) { var context = GlobalCachedInputContext.InputContext; context.Reset(); GlobalCachedInputContext.Keyboard = null; context.Disable(); return true; } return false; } private bool SetIMEKeyboard(IbusKeyboardDescription keyboard) { try { if (!CanSetIbusKeyboard()) return false; if (IBusKeyboardAlreadySet(keyboard)) return true; // Set the associated XKB keyboard var parentLayout = keyboard.ParentLayout; if (parentLayout == "en") parentLayout = "us"; var xkbKeyboard = Keyboard.Controller.AllAvailableKeyboards.FirstOrDefault(kbd => kbd.Layout == parentLayout); if (xkbKeyboard != null) xkbKeyboard.Activate(); // Then set the IBus keyboard var context = GlobalCachedInputContext.InputContext; context.SetEngine(keyboard.IBusKeyboardEngine.LongName); GlobalCachedInputContext.Keyboard = keyboard; return true; } catch (Exception e) { Debug.WriteLine(string.Format("Changing keyboard failed, is kfml/ibus running? {0}", e)); return false; } } private void SetImePreeditWindowLocationAndSize(Control control) { var eventHandler = GetEventHandlerForControl(control); if (eventHandler != null) { var location = eventHandler.SelectionLocationAndHeight; IBusCommunicator.NotifySelectionLocationAndHeight(location.Left, location.Top, location.Height); } } /// <summary> /// Synchronize on a commit. /// </summary> /// <returns><c>true</c> if an open composition got cancelled, otherwise <c>false</c>. /// </returns> private bool ResetAndWaitForCommit(Control control) { IBusCommunicator.Reset(); // This should allow any generated commits to be handled by the message pump. // TODO: find a better way to synchronize Application.DoEvents(); var eventHandler = GetEventHandlerForControl(control); if (eventHandler != null) return eventHandler.CommitOrReset(); return false; } private static IIbusEventHandler GetEventHandlerForControl(Control control) { if (control == null) return null; object handler; if (!KeyboardController.EventProvider.EventHandlers.TryGetValue(control, out handler)) return null; return handler as IIbusEventHandler; } #region KeyboardController events private void OnControlRegistered(object sender, RegisterEventArgs e) { if (e.Control != null) { var eventHandler = e.EventHandler as IIbusEventHandler; if (eventHandler == null) { Debug.Assert(e.Control is TextBox, "Currently only TextBox controls are compatible with the default IBus event handler."); eventHandler = new IbusDefaultEventHandler((TextBox)e.Control); } KeyboardController.EventProvider.EventHandlers[e.Control] = eventHandler; IBusCommunicator.CommitText += eventHandler.OnCommitText; IBusCommunicator.UpdatePreeditText += eventHandler.OnUpdatePreeditText; IBusCommunicator.HidePreeditText += eventHandler.OnHidePreeditText; IBusCommunicator.KeyEvent += eventHandler.OnIbusKeyPress; IBusCommunicator.DeleteSurroundingText += eventHandler.OnDeleteSurroundingText; e.Control.GotFocus += HandleGotFocus; e.Control.LostFocus += HandleLostFocus; e.Control.MouseDown += HandleMouseDown; e.Control.PreviewKeyDown += HandlePreviewKeyDown; e.Control.KeyPress += HandleKeyPress; e.Control.KeyDown += HandleKeyDown; var scrollableControl = e.Control as ScrollableControl; if (scrollableControl != null) scrollableControl.Scroll += HandleScroll; } } private void OnControlRemoving(object sender, ControlEventArgs e) { if (e.Control != null) { e.Control.GotFocus -= HandleGotFocus; e.Control.LostFocus -= HandleLostFocus; e.Control.MouseDown -= HandleMouseDown; e.Control.PreviewKeyDown -= HandlePreviewKeyDown; e.Control.KeyPress -= HandleKeyPress; e.Control.KeyDown -= HandleKeyDown; var scrollableControl = e.Control as ScrollableControl; if (scrollableControl != null) scrollableControl.Scroll -= HandleScroll; var eventHandler = GetEventHandlerForControl(e.Control); if (eventHandler != null) { IBusCommunicator.CommitText -= eventHandler.OnCommitText; IBusCommunicator.UpdatePreeditText -= eventHandler.OnUpdatePreeditText; IBusCommunicator.HidePreeditText -= eventHandler.OnHidePreeditText; IBusCommunicator.KeyEvent -= eventHandler.OnIbusKeyPress; IBusCommunicator.DeleteSurroundingText -= eventHandler.OnDeleteSurroundingText; KeyboardController.EventProvider.EventHandlers.Remove(e.Control); } } } #endregion private bool PassKeyEventToIbus(Control control, Keys keyChar, Keys modifierKeys) { var keySym = X11KeyConverter.GetKeySym(keyChar); return PassKeyEventToIbus(control, keySym, modifierKeys); } private bool PassKeyEventToIbus(Control control, char keyChar, Keys modifierKeys) { if (keyChar == 0x7f) // we get this for Ctrl-Backspace keyChar = '\b'; return PassKeyEventToIbus(control, (int)keyChar, modifierKeys); } private bool PassKeyEventToIbus(Control control, int keySym, Keys modifierKeys) { if (!IBusCommunicator.Connected) return false; int scancode = X11KeyConverter.GetScanCode(keySym); if (scancode > -1) { if (IBusCommunicator.ProcessKeyEvent(keySym, scancode, modifierKeys)) { return true; } } // If ProcessKeyEvent doesn't consume the key, we need to kill any preedits and // sync before continuing processing the keypress. We return false so that the // control can process the character. ResetAndWaitForCommit(control); return false; } #region Event Handler for control private void HandleGotFocus(object sender, EventArgs e) { if (!IBusCommunicator.Connected) return; IBusCommunicator.FocusIn(); m_needIMELocation = true; } private void HandleLostFocus(object sender, EventArgs e) { if (!IBusCommunicator.Connected) return; IBusCommunicator.FocusOut(); var eventHandler = GetEventHandlerForControl(sender as Control); if (eventHandler == null) return; eventHandler.CommitOrReset(); } /// <summary> /// Inform input bus of Keydown events /// This is useful to get warning of key that should stop the preedit /// </summary> private void HandlePreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (!IBusCommunicator.Connected) return; var eventHandler = GetEventHandlerForControl(sender as Control); if (eventHandler == null) return; if (m_needIMELocation) { SetImePreeditWindowLocationAndSize(sender as Control); m_needIMELocation = false; } var key = e.KeyCode; switch (key) { case Keys.Escape: // These should end a preedit, so wait until that has happened // before allowing the key to be processed. ResetAndWaitForCommit(sender as Control); return; case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right: case Keys.Delete: case Keys.PageUp: case Keys.PageDown: case Keys.Home: case Keys.End: PassKeyEventToIbus(sender as Control, key, e.Modifiers); return; } // pass function keys onto ibus since they don't appear (on mono at least) as WM_SYSCHAR if (key >= Keys.F1 && key <= Keys.F24) PassKeyEventToIbus(sender as Control, key, e.Modifiers); } /// <summary> /// Handles a key down. While a preedit is active we don't want the control to handle /// any of the keys that IBus deals with. /// </summary> private void HandleKeyDown (object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right: case Keys.Delete: case Keys.PageUp: case Keys.PageDown: case Keys.Home: case Keys.End: var eventHandler = GetEventHandlerForControl(sender as Control); if (eventHandler != null) e.Handled = eventHandler.IsPreeditActive; break; } } /// <summary> /// Handles a key press. /// </summary> /// <remarks>When the user types a character the control receives the KeyPress event and /// this method gets called. We forward the key press to IBus. If IBus swallowed the key /// it will return true, so no further handling is done by the control, otherwise the /// control will process the key and update the selection. /// If IBus swallows the key event, it will either raise the UpdatePreeditText event, /// allowing the event handler to insert the composition as preedit (and update the /// selection), or it will raise the CommitText event so that the event handler can /// remove the preedit, replace it with the final composition string and update the /// selection. Some IBus keyboards might raise a ForwardKeyEvent (handled by /// <see cref="IIbusEventHandler.OnIbusKeyPress"/>) prior to calling CommitText to /// simulate a key press (e.g. backspace) so that the event handler can modify the /// existing text of the control. /// IBus might also open a pop-up window at the location we told it /// (<see cref="IIbusEventHandler.SelectionLocationAndHeight"/>) to display possible /// compositions. However, it will still call UpdatePreeditText.</remarks> private void HandleKeyPress(object sender, KeyPressEventArgs e) { e.Handled = PassKeyEventToIbus(sender as Control, e.KeyChar, Control.ModifierKeys); } private void HandleMouseDown(object sender, MouseEventArgs e) { if (!IBusCommunicator.Connected) return; ResetAndWaitForCommit(sender as Control); m_needIMELocation = true; } private void HandleScroll(object sender, ScrollEventArgs e) { if (!IBusCommunicator.Connected) return; SetImePreeditWindowLocationAndSize(sender as Control); } #endregion #region IKeyboardAdaptor implementation /// <summary> /// Initialize the installed keyboards /// </summary> public void Initialize() { InitKeyboards(); // Don't turn on any Ibus IME keyboard until requested explicitly. // If we do nothing, the first Ibus IME keyboard is automatically activated. IBusCommunicator.FocusIn(); if (GlobalCachedInputContext.InputContext != null && GetIBusKeyboards().Length > 0) { var context = GlobalCachedInputContext.InputContext; context.Reset(); GlobalCachedInputContext.Keyboard = null; context.SetEngine(""); context.Disable(); } IBusCommunicator.FocusOut(); } public void UpdateAvailableKeyboards() { InitKeyboards(); } /// <summary/> public void Close() { if (!IBusCommunicator.IsDisposed) { IBusCommunicator.Dispose(); } } public bool ActivateKeyboard(IKeyboardDefinition keyboard) { var ibusKeyboard = keyboard as IbusKeyboardDescription; return SetIMEKeyboard(ibusKeyboard); } /// <summary> /// Deactivates the specified keyboard. /// </summary> public void DeactivateKeyboard(IKeyboardDefinition keyboard) { SetIMEKeyboard(null); } /// <summary> /// List of keyboard layouts that either gave an exception or other error trying to /// get more information. We don't have enough information for these keyboard layouts /// to include them in the list of installed keyboards. /// </summary> public List<IKeyboardErrorDescription> ErrorKeyboards { get { return new List<IKeyboardErrorDescription>(); } } // Currently we expect this to only be useful on Windows. public IKeyboardDefinition GetKeyboardForInputLanguage(IInputLanguage inputLanguage) { throw new NotImplementedException(); } /// <summary> /// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...) /// </summary> public KeyboardType Type { get { return KeyboardType.OtherIm; } } /// <summary> /// Implementation is not required because this is not the primary (Type System) adapter. /// </summary> public IKeyboardDefinition DefaultKeyboard { get { throw new NotImplementedException(); } } /// <summary> /// Implementation is not required because this is not the primary (Type System) adapter. /// </summary> public IKeyboardDefinition ActiveKeyboard { get { throw new NotImplementedException(); } } /// <summary> /// Only the primary (Type=System) adapter is required to implement this method. This one makes keyboards /// during Initialize, but is not used to make an unavailable keyboard to match an LDML file. /// </summary> public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale) { throw new NotImplementedException(); } #endregion } } #endif
using MatterHackers.VectorMath; using System; //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2007 Lars Brubaker // larsbrubaker@gmail.com // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- namespace MatterHackers.Agg.UI { public class WindowWidget : GuiWidget { private int grabWidth = (int)Math.Round(5 * GuiWidget.DeviceScale); private GuiWidget windowBackground; public WindowWidget(RectangleDouble inBounds) : this(new GuiWidget(inBounds.Width, inBounds.Height) { HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Stretch, Position = new Vector2(inBounds.Left, inBounds.Bottom), Size = new Vector2(inBounds.Width, inBounds.Height) }) { } public WindowWidget(GuiWidget clientArea) { windowBackground = new FlowLayoutWidget(FlowDirection.TopToBottom) { HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Stretch, Margin = new BorderDouble(grabWidth), }; base.AddChild(windowBackground); TitleBar = new TitleBarWidget(this) { Size = new Vector2(0, 30 * GuiWidget.DeviceScale), HAnchor = HAnchor.Stretch, }; windowBackground.AddChild(TitleBar); MinimumSize = new Vector2(grabWidth * 8, grabWidth * 4 + TitleBar.Height * 2); WindowBorder = new BorderDouble(1); WindowBorderColor = Color.Cyan; Position = clientArea.Position + new Vector2(grabWidth, grabWidth); Size = clientArea.Size + new Vector2(grabWidth * 2, grabWidth * 2 + TitleBar.Height); AddGrabControls(); ClientArea = clientArea; windowBackground.AddChild(ClientArea); } public BorderDouble WindowBorder { get => windowBackground.Border; set => windowBackground.Border = value; } public Color WindowBorderColor { get => windowBackground.BorderColor; set => windowBackground.BorderColor = value; } public GuiWidget ClientArea { get; } public TitleBarWidget TitleBar { get; private set; } public override void OnDrawBackground(Graphics2D graphics2D) { // draw the shadow for (int i = 0; i < grabWidth; i++) { var color = new Color(Color.Black, 100 * i / grabWidth); // left line graphics2D.Line(i + .5, i + .5, i + .5, Height - i - .5, color); // right line graphics2D.Line(Width - i - .5, i + .5, Width - i - .5, Height - i - .5, color); // bottom line graphics2D.Line(i + .5, i + .5, Width - i - .5, i + .5, color); // top line graphics2D.Line(i + .5, Height - i - .5, Width - i - .5, Height - i - .5, color); } } private void AddGrabControls() { // this is for debugging var grabCornnerColor = Color.Transparent;// Color.Blue; var grabEdgeColor = Color.Transparent;//Color.Red; // left grab control base.AddChild(new GrabControl(Cursors.SizeWE) { BackgroundColor = grabEdgeColor, Margin = new BorderDouble(0, grabWidth), HAnchor = HAnchor.Left, VAnchor = VAnchor.Stretch, Size = new Vector2(grabWidth, 0), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; delta.Y = 0; var startSize = Size; Size = new Vector2(Size.X - delta.X, Size.Y); Position += startSize - Size; } }); // bottom grab control base.AddChild(new GrabControl(Cursors.SizeNS) { BackgroundColor = grabEdgeColor, Margin = new BorderDouble(grabWidth, 0), HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Bottom, Size = new Vector2(0, grabWidth), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; delta.X = 0; var startSize = Size; Size = new Vector2(Size.X, Size.Y - delta.Y); Position = Position + startSize - Size; } }); // left bottom grab control base.AddChild(new GrabControl(Cursors.SizeNESW) { BackgroundColor = grabCornnerColor, HAnchor = HAnchor.Left, VAnchor = VAnchor.Bottom, Size = new Vector2(grabWidth, grabWidth), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; var startSize = Size; Size -= delta; Position = Position + startSize - Size; } }); // left top grab control base.AddChild(new GrabControl(Cursors.SizeNWSE) { BackgroundColor = grabCornnerColor, HAnchor = HAnchor.Left, VAnchor = VAnchor.Top, Size = new Vector2(grabWidth, grabWidth), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; var startSize = Size; Size = new Vector2(Size.X - delta.X, Size.Y + delta.Y); Position += new Vector2(startSize.X - Size.X, 0); } }); // right grab control base.AddChild(new GrabControl(Cursors.SizeWE) { BackgroundColor = grabEdgeColor, Margin = new BorderDouble(0, grabWidth), VAnchor = VAnchor.Stretch, HAnchor = HAnchor.Right, Size = new Vector2(grabWidth, 0), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; Size = new Vector2(Size.X + delta.X, Size.Y); } }); // right top grab control base.AddChild(new GrabControl(Cursors.SizeNESW) { BackgroundColor = grabCornnerColor, HAnchor = HAnchor.Right, VAnchor = VAnchor.Top, Size = new Vector2(grabWidth, grabWidth), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; Size = new Vector2(Size.X + delta.X, Size.Y + delta.Y); } }); // top grab control base.AddChild(new GrabControl(Cursors.SizeNS) { BackgroundColor = grabEdgeColor, Margin = new BorderDouble(grabWidth, 0), HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Top, Size = new Vector2(0, grabWidth), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; Size = new Vector2(Size.X, Size.Y + delta.Y); } }); // right bottom base.AddChild(new GrabControl(Cursors.SizeNWSE) { BackgroundColor = grabCornnerColor, HAnchor = HAnchor.Right, VAnchor = VAnchor.Bottom, Size = new Vector2(grabWidth, grabWidth), AdjustParent = (s, e) => { var delta = e.Position - s.downPosition; var startSize = Size; Size = new Vector2(Size.X + delta.X, Size.Y - delta.Y); Position = new Vector2(Position.X, Position.Y + (startSize.Y - Size.Y)); } }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; using Xunit; namespace System.Xml.Tests { public partial class FactoryReaderTest : CGenericTestModule { private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator) { CModInfo.CommandLine = "/async"; RunTestCase(testCaseGenerator); } private static void RunTestCase(Func<CTestBase> testCaseGenerator) { var module = new FactoryReaderTest(); module.Init(null); module.AddChild(testCaseGenerator()); module.Execute(); Assert.Equal(0, module.FailCount); } private static void RunTest(Func<CTestBase> testCaseGenerator) { RunTestCase(testCaseGenerator); RunTestCaseAsync(testCaseGenerator); } [Fact] [OuterLoop] public static void ErrorConditionReader() { RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void XMLExceptionReader() { RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void LinePosReader() { RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void DepthReader() { RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void NamespaceReader() { RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void LookupNamespaceReader() { RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void HasValueReader() { RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void IsEmptyElementReader() { RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void XmlSpaceReader() { RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void XmlLangReader() { RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void SkipReader() { RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void BaseURIReader() { RunTest(() => new TCBaseURIReader() { Attribute = new TestCase() { Name = "BaseURI", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void InvalidXMLReader() { RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadOuterXmlReader() { RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void AttributeAccessReader() { RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ThisNameReader() { RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void MoveToAttributeReader() { RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void GetAttributeOrdinalReader() { RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void GetAttributeNameReader() { RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ThisOrdinalReader() { RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void MoveToAttributeOrdinalReader() { RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void MoveToFirstAttributeReader() { RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void MoveToNextAttributeReader() { RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void AttributeTestReader() { RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void AttributeXmlDeclarationReader() { RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void XmlnsReader() { RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void XmlnsPrefixReader() { RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadStateReader() { RunTest(() => new TCReadStateReader() { Attribute = new TestCase() { Name = "ReadState", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadInnerXmlReader() { RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void MoveToContentReader() { RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void IsStartElementReader() { RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadStartElementReader() { RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadEndElementReader() { RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ResolveEntityReader() { RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadAttributeValueReader() { RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadReader() { RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void MoveToElementReader() { RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void DisposeReader() { RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void BufferBoundariesReader() { RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileBeforeRead() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileAfterCloseInMiddle() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileAfterClose() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileAfterReadIsFalse() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } }); } [Fact] [OuterLoop] public static void ReadSubtreeReader() { RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadToDescendantReader() { RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadToNextSiblingReader() { RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadValueReader() { RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadContentAsBase64Reader() { RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadElementContentAsBase64Reader() { RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadContentAsBinHexReader() { RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadElementContentAsBinHexReader() { RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void ReadToFollowingReader() { RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "FactoryReader" } }); } [Fact] [OuterLoop] public static void Normalization() { RunTest(() => new TCNormalization() { Attribute = new TestCase() { Name = "FactoryReader Normalization", Desc = "FactoryReader" } }); } } }
using System; using NUnit.Framework; using Rothko.Model; using Rothko.Commands; using Rothko.Interfaces.Services; using Moq; using System.Collections.Generic; using System.Linq; using Rothko.Enumerators; namespace Rothko.Tests.Commands { [TestFixture] public class ChangeCursorPositionCommandTests { int _UnitX = 1, _UnitY = 1; int _CursorX = 2, _CursorY = 1; Mock<IPathfindingService> _PathfindingServiceMock; Mock<IUnitRangeService> _UnitRangeServiceMock; Map _Map; Player _Player1; Unit _Unit1; Unit _UnitCarrier; Unit _EnemyUnit1; UnitType _UnitTypeUnit1; List<Tile> _Tiles; RothkoBaseDatabase _RothkoBaseDatabase; ChangeCursorPositionCommand _Command; [SetUp] public void SetUp() { _Tiles = new List<Tile>() { new Tile() { X = _UnitX, Y = _UnitY }, new Tile() { X = _CursorX, Y = _CursorY } }; _UnitTypeUnit1 = new UnitType() { ID = 1, RangePoints = 1, ViewPoints = 3 }; _RothkoBaseDatabase = new RothkoBaseDatabase(); _RothkoBaseDatabase.UnitTypes.Add (_UnitTypeUnit1); _RothkoBaseDatabase.UnitTypeCarriers = new List<UnitTypeCarrier>() { new UnitTypeCarrier() { IDUnitTypeCarried = 1, IDUnitTypeCarrier = 2 } }; _PathfindingServiceMock = new Mock<IPathfindingService>(); _UnitRangeServiceMock = new Mock<IUnitRangeService>(); _UnitRangeServiceMock .Setup(s => s.GetEnemyUnitLocationsInAttackRange(It.IsAny<Unit>(), It.IsAny<List<Tile>>(), It.IsAny<List<Unit>>(), It.IsAny<int>(), It.IsAny<int>())) .Returns(new List<Tile>() { _Tiles.First(t => t.X == _CursorX && t.Y == _CursorY) }); _Player1 = new Player() { ID = 1, IDTeam = 1 }; _Unit1 = new Unit() { ID = 1, IDUnitType = 1, IDTeam = 1, HealthPoints = 10, X = _UnitX, Y = _UnitY }; _UnitCarrier = new Unit() { ID = 2, IDUnitType = 2, IDTeam = 1, HealthPoints = 10, X = _CursorX, Y = _CursorY, NumberOfUnitsBeingCarried = 0, NumberOfUnitsThatCanBeCarried = 4 }; _EnemyUnit1 = new Unit() { ID = 3, IDUnitType = 2, IDTeam = 2, HealthPoints = 10, X = _CursorX, Y = _CursorY }; _Map = new Map() { CursorX = 1, CursorY = 1 }; _Map.Tiles = _Tiles; _Map.Units.Add (_Unit1); _Map.Players.Add (_Player1); _Map.IDPlayerCurrent = 1; _Map.IDUnit_Selected = 1; } [Test] public void WhenExecutingCommandShouldChangeMapCursorLocations() { _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.AreEqual(_Map.CursorX, _CursorX); Assert.AreEqual(_Map.CursorY, _CursorY); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorPositionDifferentThanUnitPositionShouldCallPathFindingService() { _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingPath; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _PathfindingServiceMock.Verify(s => s.GetPath(_Unit1, _CursorX, _CursorY, _Map.Units, _Map.Tiles, _Map.CurrentPlayer.FogTiles, false, false)); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorPositionDifferentThanUnitPositionAndOnCurrentCursorPositionThereIsCarrierUnitWithTheCapabilityToCarryCurrentUnitShouldCallPathFindingServiceAllowingJuxtaPositionOfFriendlyUnits() { _Map.Units.Add (_UnitCarrier); _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingPath; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _PathfindingServiceMock.Verify(s => s.GetPath(_Unit1, _CursorX, _CursorY, _Map.Units, _Map.Tiles, _Map.CurrentPlayer.FogTiles, false, true)); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorPositionDifferentThanUnitPositionAndOnCurrentCursorPositionThereIsCarrierUnitWithTheCapabilityToCarryCurrentUnitButDeadShouldNotCallPathFindingServiceAllowingJuxtaPositionOfFriendlyUnits() { _UnitCarrier.HealthPoints = 0; _Map.Units.Add (_UnitCarrier); _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingPath; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _PathfindingServiceMock.Verify(s => s.GetPath(_Unit1, _CursorX, _CursorY, _Map.Units, _Map.Tiles, _Map.CurrentPlayer.FogTiles, false, false)); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorHasEnemyUnitShouldSetIDEnemyUnitAndPath() { List<Coordinate> coordinatesExpectedInMap; _Map.GameState = GameState.UnitDecidingPath; _Map.Units.Add (_EnemyUnit1); coordinatesExpectedInMap = new List<Coordinate>() { new Coordinate() { X = _CursorX, Y = _CursorY } }; _PathfindingServiceMock .Setup(s => s.GetPath(It.IsAny<Unit>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<List<Unit>>(), It.IsAny<List<Tile>>(), It.IsAny<List<FogTile>>(), It.IsAny<bool>(), It.IsAny<bool>())) .Returns(coordinatesExpectedInMap); _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.AreEqual(coordinatesExpectedInMap, _Map.CurrentUnitPath); Assert.AreEqual(_EnemyUnit1, _Map.SelectedUnitForAttack); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorHasEnemyUnitShouldCallRangeServiceWithLastCoordinate() { List<Coordinate> coordinatesExpectedInMap; _Map.GameState = GameState.UnitDecidingPath; _Map.Units.Add (_EnemyUnit1); coordinatesExpectedInMap = new List<Coordinate>() { new Coordinate() { X = 10, Y = 20 } }; _PathfindingServiceMock .Setup(s => s.GetPath(It.IsAny<Unit>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<List<Unit>>(), It.IsAny<List<Tile>>(), It.IsAny<List<FogTile>>(), It.IsAny<bool>(), It.IsAny<bool>())) .Returns(coordinatesExpectedInMap); _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _UnitRangeServiceMock.Verify(s => s.GetEnemyUnitLocationsInAttackRange(_Unit1, _Tiles, _Map.Units, 10, 20)); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorHasEnemyUnitButNoPathShouldCallRangeServiceWithCurrentUnitCoordinates() { List<Coordinate> coordinatesExpectedInMap; _Map.GameState = GameState.UnitDecidingPath; _Map.Units.Add (_EnemyUnit1); coordinatesExpectedInMap = new List<Coordinate>(); _PathfindingServiceMock .Setup(s => s.GetPath(It.IsAny<Unit>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<List<Unit>>(), It.IsAny<List<Tile>>(), It.IsAny<List<FogTile>>(), It.IsAny<bool>(), It.IsAny<bool>())) .Returns(coordinatesExpectedInMap); _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _UnitRangeServiceMock.Verify(s => s.GetEnemyUnitLocationsInAttackRange(_Unit1, _Tiles, _Map.Units, _Unit1.X, _Unit1.Y)); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorPositionDifferentThanUnitPositionShouldSetCurrentUnitPathOnMap() { List<Coordinate> coordinatesExpectedInMap; _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingPath; coordinatesExpectedInMap = new List<Coordinate>() { new Coordinate() { X = _CursorX, Y = _CursorY } }; _PathfindingServiceMock .Setup(s => s.GetPath(It.IsAny<Unit>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<List<Unit>>(), It.IsAny<List<Tile>>(), It.IsAny<List<FogTile>>(), It.IsAny<bool>(), It.IsAny<bool>())) .Returns(coordinatesExpectedInMap); _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.AreEqual(coordinatesExpectedInMap, _Map.CurrentUnitPath); } [Test] public void WhenGameStateUnitDecidingPathAndCurrentCursorPositionEqualToUnitPositionShouldNotCallPathFindingService() { _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingPath; _CursorX = _UnitX; _CursorY = _UnitY; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _PathfindingServiceMock.Verify(s => s.GetPath(It.IsAny<Unit>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<List<Unit>>(), It.IsAny<List<Tile>>(), It.IsAny<List<FogTile>>(), It.IsAny<bool>(), It.IsAny<bool>()), Times.Never ()); } [Test] public void WhenGameStateUnitDecidingAttackAndCurrentCursorPositionChangesShouldCallRangeService() { _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingAttack; _Map.Units.Add (_EnemyUnit1); _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); _UnitRangeServiceMock .Verify(s => s .GetEnemyUnitLocationsInAttackRange(_Unit1, _Tiles, _Map.Units, _Unit1.X, _Unit1.Y), Times.Once ()); } [Test] public void WhenGameStateUnitDecidingAttackAndCurrentCursorPositionChangesAndThereIsEnemyUnitOnLocationShouldSetItsIDOnMap() { _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingAttack; _Map.Units.Add (_EnemyUnit1); _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.AreEqual(_EnemyUnit1, _Map.SelectedUnitForAttack); Assert.AreEqual(_EnemyUnit1.ID, _Map.IDUnit_SelectedForAttack); } [Test] public void WhenGameStateUnitDecidingAttackAndCurrentCursorPositionChangesAndThereIsNoEnemyUnitOnLocationButIDUnitSelectedForAttackIsNotNullThenShouldBeSetToNull() { _Map.GameState = Rothko.Enumerators.GameState.UnitDecidingAttack; _Map.Units.Add (_EnemyUnit1); _Map.IDUnit_SelectedForAttack = _EnemyUnit1.ID; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, 3, 9); _Command.Execute(); Assert.AreEqual(null, _Map.SelectedUnitForAttack); Assert.AreEqual(null, _Map.IDUnit_SelectedForAttack); } [Test] public void WhenGameStateUnitDecidingUnloadPositionAndCurrentCursorPositionChangesAndIsOnPossibleUnloadPositionShouldSetMapsUnloadPositionCoordinates() { _Map.PossibleUnloadPositions = new List<Coordinate>() { new Coordinate() { X = _CursorX, Y = _CursorY } }; _Map.GameState = GameState.UnitDecidingUnloadPosition; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.IsNotNull(_Map.UnitUnloadPosition); Assert.IsTrue(_Map.UnitUnloadPosition.X == _CursorX && _Map.UnitUnloadPosition.Y == _CursorY); } [Test] public void WhenGameStateUnitDecidingUnloadPositionAndPossibleUnloadPositionsIsNullAndUnitUnloadPositionIsSetAndCurrentCursorPositionChangesAndIsNotOnPossibleUnloadPositionShouldSetMapsUnloadPositionToNull() { _Map.GameState = GameState.UnitDecidingUnloadPosition; _Map.UnitUnloadPosition = new Coordinate() { X = _CursorX - 1, Y = _CursorY }; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.IsNull(_Map.UnitUnloadPosition); } [Test] public void WhenGameStateUnitDecidingUnloadPositionAndPossibleUnloadPositionsIsNotNullAndUnitUnloadPositionIsSetAndCurrentCursorPositionChangesAndIsNotOnPossibleUnloadPositionShouldSetMapsUnloadPositionToNull() { _Map.PossibleUnloadPositions = new List<Coordinate>() { new Coordinate() { X = 999, Y = 999 } }; _Map.GameState = GameState.UnitDecidingUnloadPosition; _Map.UnitUnloadPosition = new Coordinate() { X = _CursorX - 1, Y = _CursorY }; _Command = new ChangeCursorPositionCommand(_Map, _RothkoBaseDatabase, _PathfindingServiceMock.Object, _UnitRangeServiceMock.Object, _CursorX, _CursorY); _Command.Execute(); Assert.IsNull(_Map.UnitUnloadPosition); } } }
using System; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Generators.C; using CppSharp.Generators.CLI; using CppSharp.Types; using Delegate = CppSharp.AST.Delegate; using Type = CppSharp.AST.Type; namespace CppSharp.Generators.Cpp { public class QuickJSMarshalNativeToManagedPrinter : MarshalPrinter<MarshalContext, CppTypePrinter> { public QuickJSMarshalNativeToManagedPrinter(MarshalContext marshalContext) : base(marshalContext) { } public string MemoryAllocOperator => (Context.Context.Options.GeneratorKind == GeneratorKind.CLI) ? "gcnew" : "new"; public override bool VisitType(Type type, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.MarshalToManaged(GeneratorKind.QuickJS, Context); return false; } return true; } public override bool VisitArrayType(ArrayType array, TypeQualifiers quals) { switch (array.SizeType) { case ArrayType.ArraySize.Constant: case ArrayType.ArraySize.Incomplete: case ArrayType.ArraySize.Variable: Context.Return.Write("nullptr"); break; default: throw new System.NotImplementedException(); } return true; } public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals) { Context.Return.Write(Context.ReturnVarName); return true; } public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (!VisitType(pointer, quals)) return false; var pointee = pointer.Pointee.Desugar(); PrimitiveType primitive; var param = Context.Parameter; if (param != null && (param.IsOut || param.IsInOut) && pointee.IsPrimitiveType(out primitive)) { Context.Return.Write(Context.ReturnVarName); return true; } if (pointee.IsPrimitiveType(out primitive)) { var returnVarName = Context.ReturnVarName; if (pointer.GetFinalQualifiedPointee().Qualifiers.IsConst != Context.ReturnType.Qualifiers.IsConst) { var nativeTypePrinter = new CppTypePrinter(Context.Context) { PrintTypeQualifiers = false }; var returnType = Context.ReturnType.Type.Desugar(); var constlessPointer = new PointerType() { IsDependent = pointer.IsDependent, Modifier = pointer.Modifier, QualifiedPointee = new QualifiedType(returnType.GetPointee()) }; var nativeConstlessTypeName = constlessPointer.Visit(nativeTypePrinter, new TypeQualifiers()); returnVarName = string.Format("const_cast<{0}>({1})", nativeConstlessTypeName, Context.ReturnVarName); } if (pointer.Pointee is TypedefType) { var desugaredPointer = new PointerType() { IsDependent = pointer.IsDependent, Modifier = pointer.Modifier, QualifiedPointee = new QualifiedType(pointee) }; var nativeTypeName = desugaredPointer.Visit(typePrinter, quals); Context.Return.Write("reinterpret_cast<{0}>({1})", nativeTypeName, returnVarName); } else Context.Return.Write(returnVarName); return true; } TypeMap typeMap = null; Context.Context.TypeMaps.FindTypeMap(pointee, out typeMap); Class @class; if (pointee.TryGetClass(out @class) && typeMap == null) { var instance = (pointer.IsReference) ? "&" + Context.ReturnVarName : Context.ReturnVarName; WriteClassInstance(@class, instance); return true; } return pointer.QualifiedPointee.Visit(this); } public override bool VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) { return false; } public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) { return VisitPrimitiveType(builtin.Type); } public override bool VisitEnumItemDecl(Enumeration.Item item) { var @enum = item.Namespace as Enumeration; return VisitPrimitiveType(@enum.BuiltinType.Type); } public bool VisitPrimitiveType(PrimitiveType primitive) { var retName = Generator.GeneratedIdentifier(Context.ReturnVarName); Context.Before.Write($"JSValue {retName} = "); switch (primitive) { case PrimitiveType.Void: return true; case PrimitiveType.Bool: Context.Before.WriteLine($"JS_NewBool(ctx, {Context.ArgName});"); break; case PrimitiveType.Char: case PrimitiveType.Char16: case PrimitiveType.Char32: case PrimitiveType.WideChar: case PrimitiveType.SChar: case PrimitiveType.UChar: case PrimitiveType.Short: case PrimitiveType.UShort: case PrimitiveType.Int: case PrimitiveType.Long: Context.Before.WriteLine($"JS_NewInt32(ctx, {Context.ArgName});"); break; case PrimitiveType.UInt: case PrimitiveType.ULong: Context.Before.WriteLine($"JS_NewUint32(ctx, {Context.ArgName});"); break; case PrimitiveType.LongLong: Context.Before.WriteLine($"JS_NewBigInt64(ctx, {Context.ArgName});"); break; case PrimitiveType.ULongLong: Context.Before.WriteLine($"JS_NewBigUint64(ctx, {Context.ArgName});"); break; case PrimitiveType.Float: case PrimitiveType.Double: Context.Before.WriteLine($"JS_NewFloat64(ctx, {Context.ArgName});"); break; case PrimitiveType.LongDouble: throw new NotImplementedException(); case PrimitiveType.Null: Context.Before.WriteLine($"JS_NULL;"); break; default: throw new NotImplementedException(); } Context.Return.Write(retName); return true; } public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { var decl = typedef.Declaration; TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = typedef; typeMap.MarshalToManaged(GeneratorKind.QuickJS, Context); return typeMap.IsValueType; } FunctionType function; if (decl.Type.IsPointerTo(out function)) { var typeName = typePrinter.VisitDeclaration(decl); var typeName2 = decl.Type.Visit(typePrinter); Context.Return.Write(typeName); } return decl.Type.Visit(this); } public override bool VisitTemplateSpecializationType(TemplateSpecializationType template, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = template; typeMap.MarshalToManaged(GeneratorKind.QuickJS, Context); return true; } return template.Template.Visit(this); } public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); var instance = string.Empty; if (Context.Context.Options.GeneratorKind == GeneratorKind.CLI) { if (!Context.ReturnType.Type.IsPointer()) instance += "&"; } instance += Context.ReturnVarName; var needsCopy = Context.MarshalKind != MarshalKind.NativeField; if (@class.IsRefType && needsCopy) { var name = Generator.GeneratedIdentifier(Context.ReturnVarName); Context.Before.WriteLine($"auto {name} = {MemoryAllocOperator} ::{{0}}({{1}});", @class.QualifiedOriginalName, Context.ReturnVarName); instance = name; } WriteClassInstance(@class, instance); return true; } public string QualifiedIdentifier(Declaration decl) { if (!string.IsNullOrEmpty(decl.TranslationUnit.Module.OutputNamespace)) return $"{decl.TranslationUnit.Module.OutputNamespace}::{decl.QualifiedName}"; return decl.QualifiedName; } public void WriteClassInstance(Class @class, string instance) { if (@class.CompleteDeclaration != null) { WriteClassInstance(@class.CompleteDeclaration as Class, instance); return; } if (!Context.ReturnType.Type.Desugar().IsPointer()) { Context.Return.Write($"{instance}"); return; } if (@class.IsRefType) Context.Return.Write($"({instance} == nullptr) ? nullptr : {MemoryAllocOperator} "); Context.Return.Write($"{QualifiedIdentifier(@class)}("); Context.Return.Write($"(::{@class.QualifiedOriginalName}*)"); Context.Return.Write($"{instance})"); } public override bool VisitFieldDecl(Field field) { return field.Type.Visit(this); } public override bool VisitFunctionDecl(Function function) { throw new NotImplementedException(); } public override bool VisitMethodDecl(Method method) { throw new NotImplementedException(); } public override bool VisitParameterDecl(Parameter parameter) { Context.Parameter = parameter; var ret = parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers); Context.Parameter = null; return ret; } public override bool VisitTypedefDecl(TypedefDecl typedef) { throw new NotImplementedException(); } public override bool VisitEnumDecl(Enumeration @enum) { var retName = Generator.GeneratedIdentifier(Context.ReturnVarName); Context.Before.WriteLine($"JSValue {retName} = JS_NewInt32(ctx, (int32_t) {Context.ReturnVarName});"); Context.Return.Write(retName); return true; } public override bool VisitVariableDecl(Variable variable) { return variable.Type.Visit(this, variable.QualifiedType.Qualifiers); } public override bool VisitClassTemplateDecl(ClassTemplate template) { return template.TemplatedClass.Visit(this); } public override bool VisitFunctionTemplateDecl(FunctionTemplate template) { return template.TemplatedFunction.Visit(this); } } public class QuickJSMarshalManagedToNativePrinter : MarshalPrinter<MarshalContext, CppTypePrinter> { public readonly TextGenerator VarPrefix; public readonly TextGenerator ArgumentPrefix; public QuickJSMarshalManagedToNativePrinter(MarshalContext ctx) : base(ctx) { VarPrefix = new TextGenerator(); ArgumentPrefix = new TextGenerator(); Context.MarshalToNative = this; } public override bool VisitType(Type type, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.MarshalToNative(GeneratorKind.QuickJS, Context); return false; } return true; } public override bool VisitTagType(TagType tag, TypeQualifiers quals) { if (!VisitType(tag, quals)) return false; return tag.Declaration.Visit(this); } public override bool VisitArrayType(ArrayType array, TypeQualifiers quals) { if (!VisitType(array, quals)) return false; switch (array.SizeType) { default: Context.Return.Write("nullptr"); break; } return true; } public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals) { var returnType = function.ReturnType; return returnType.Visit(this); } public bool VisitDelegateType(string type) { Context.Return.Write(Context.Parameter.Name); return true; } public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (!VisitType(pointer, quals)) return false; var pointee = pointer.Pointee.Desugar(); if (pointee is FunctionType) { typePrinter.PushContext(TypePrinterContextKind.Managed); var cppTypeName = pointer.Visit(typePrinter, quals); typePrinter.PopContext(); return VisitDelegateType(cppTypeName); } Enumeration @enum; if (pointee.TryGetEnum(out @enum)) { var isRef = Context.Parameter.Usage == ParameterUsage.Out || Context.Parameter.Usage == ParameterUsage.InOut; ArgumentPrefix.Write("&"); Context.Return.Write($"(::{@enum.QualifiedOriginalName}){0}{Context.Parameter.Name}", isRef ? string.Empty : "*"); return true; } Class @class; if (pointee.TryGetClass(out @class) && @class.IsValueType) { if (Context.Function == null) Context.Return.Write("&"); return pointer.QualifiedPointee.Visit(this); } var finalPointee = pointer.GetFinalPointee(); if (finalPointee.IsPrimitiveType()) { var cppTypeName = pointer.Visit(typePrinter, quals); Context.Return.Write($"({cppTypeName})"); Context.Return.Write(Context.Parameter.Name); return true; } return pointer.QualifiedPointee.Visit(this); } public override bool VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) { return false; } public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) { return VisitPrimitiveType(builtin.Type); } public bool VisitPrimitiveType(PrimitiveType primitive) { var type = typePrinter.VisitPrimitiveType(primitive); var argName = Context.Parameter.Name; Context.Before.WriteLine($"{type} {argName};"); switch (primitive) { case PrimitiveType.Void: return true; case PrimitiveType.Bool: Context.Before.WriteLine($"{argName} = JS_ToBool(ctx, argv[{Context.ParameterIndex}]);"); Context.Before.WriteLine($"if ({argName} == -1)"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.Char: case PrimitiveType.SChar: case PrimitiveType.UChar: Context.Before.WriteLine($"int32_t _{argName};"); Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Before.WriteLine($"{argName} = ({type})_{argName};"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.Short: case PrimitiveType.UShort: Context.Before.WriteLine($"int32_t _{argName};"); Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Before.WriteLine($"{argName} = ({type})_{argName};"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.Int: case PrimitiveType.Long: Context.Before.WriteLine($"if (JS_ToInt32(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.UInt: case PrimitiveType.ULong: Context.Before.WriteLine($"if (JS_ToUint32(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.LongLong: Context.Before.WriteLine($"int64_t _{argName};"); Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Before.WriteLine($"{argName} = ({type})_{argName};"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.ULongLong: Context.Before.WriteLine($"int64_t _{argName};"); Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Before.WriteLine($"{argName} = ({type})_{argName};"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.Float: Context.Before.WriteLine($"double _{argName};"); Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Before.WriteLine($"{argName} = ({type})_{argName};"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.Double: Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); Context.Before.WriteLineIndent("return JS_EXCEPTION;"); Context.Return.Write($"{argName}"); return true; case PrimitiveType.WideChar: default: throw new NotImplementedException(); } } public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { var decl = typedef.Declaration; TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) && typeMap.DoesMarshalling) { typeMap.MarshalToNative(GeneratorKind.QuickJS, Context); return typeMap.IsValueType; } FunctionType func; if (decl.Type.IsPointerTo(out func)) { typePrinter.PushContext(TypePrinterContextKind.Native); var declName = decl.Visit(typePrinter); typePrinter.PopContext(); // Use the original typedef name if available, otherwise just use the function pointer type string cppTypeName; if (!decl.IsSynthetized) { cppTypeName = "::" + typedef.Declaration.QualifiedOriginalName; } else { cppTypeName = decl.Type.Visit(typePrinter, quals); } VisitDelegateType(cppTypeName); return true; } PrimitiveType primitive; if (decl.Type.IsPrimitiveType(out primitive)) { Context.Return.Write($"(::{typedef.Declaration.QualifiedOriginalName})"); } return decl.Type.Visit(this); } public override bool VisitTemplateSpecializationType(TemplateSpecializationType template, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = template; typeMap.MarshalToNative(GeneratorKind.QuickJS, Context); return true; } return template.Template.Visit(this); } public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals) { Context.Return.Write(param.Parameter.Name); return true; } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); if (@class.IsValueType) { MarshalValueClass(@class); } else { MarshalRefClass(@class); } return true; } private void MarshalRefClass(Class @class) { var type = Context.Parameter.Type.Desugar(); TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.MarshalToNative(GeneratorKind.QuickJS, Context); return; } if (!type.SkipPointerRefs().IsPointer()) { Context.Return.Write("*"); if (Context.Parameter.Type.IsReference()) VarPrefix.Write("&"); } var method = Context.Function as Method; if (method != null && method.Conversion == MethodConversionKind.FunctionToInstanceMethod && Context.ParameterIndex == 0) { Context.Return.Write($"(::{@class.QualifiedOriginalName}*)"); Context.Return.Write(Helpers.InstanceIdentifier); return; } var paramType = Context.Parameter.Type.Desugar(); var isPointer = paramType.SkipPointerRefs().IsPointer(); var deref = isPointer ? "->" : "."; var instance = $"(::{@class.QualifiedOriginalName}*)" + $"{Context.Parameter.Name}{deref}{Helpers.InstanceIdentifier}"; if (isPointer) Context.Return.Write($"{Context.Parameter.Name} ? {instance} : nullptr"); else Context.Return.Write($"{instance}"); } private void MarshalValueClass(Class @class) { throw new System.NotImplementedException(); } public override bool VisitFieldDecl(Field field) { Context.Parameter = new Parameter { Name = Context.ArgName, QualifiedType = field.QualifiedType }; return field.Type.Visit(this); } public override bool VisitProperty(Property property) { Context.Parameter = new Parameter { Name = Context.ArgName, QualifiedType = property.QualifiedType }; return base.VisitProperty(property); } public override bool VisitFunctionDecl(Function function) { throw new NotImplementedException(); } public override bool VisitMethodDecl(Method method) { throw new NotImplementedException(); } public override bool VisitParameterDecl(Parameter parameter) { return parameter.Type.Visit(this); } public override bool VisitTypedefDecl(TypedefDecl typedef) { throw new NotImplementedException(); } public override bool VisitEnumDecl(Enumeration @enum) { VisitPrimitiveType(@enum.BuiltinType.Type); Context.Return.StringBuilder.Clear(); Context.Return.Write($"(::{@enum.QualifiedOriginalName}){Context.Parameter.Name}"); return true; } public override bool VisitVariableDecl(Variable variable) { throw new NotImplementedException(); } public override bool VisitClassTemplateDecl(ClassTemplate template) { return template.TemplatedClass.Visit(this); } public override bool VisitFunctionTemplateDecl(FunctionTemplate template) { return template.TemplatedFunction.Visit(this); } public override bool VisitMacroDefinition(MacroDefinition macro) { throw new NotImplementedException(); } public override bool VisitNamespace(Namespace @namespace) { throw new NotImplementedException(); } public override bool VisitEvent(Event @event) { throw new NotImplementedException(); } public bool VisitDelegate(Delegate @delegate) { throw new NotImplementedException(); } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite { /// <summary>Lets you stream a large attachment to a BlobStore asynchronously, e.g.</summary> /// <remarks>Lets you stream a large attachment to a BlobStore asynchronously, e.g. from a network download. /// </remarks> /// <exclude></exclude> public class BlobStoreWriter { /// <summary>The underlying blob store where it should be stored.</summary> /// <remarks>The underlying blob store where it should be stored.</remarks> private BlobStore store; /// <summary>The number of bytes in the blob.</summary> /// <remarks>The number of bytes in the blob.</remarks> private int length; /// <summary>After finishing, this is the key for looking up the blob through the CBL_BlobStore. /// </summary> /// <remarks>After finishing, this is the key for looking up the blob through the CBL_BlobStore. /// </remarks> private BlobKey blobKey; /// <summary>After finishing, store md5 digest result here</summary> private byte[] md5DigestResult; /// <summary>Message digest for sha1 that is updated as data is appended</summary> private MessageDigest sha1Digest; private MessageDigest md5Digest; private BufferedOutputStream outStream; private FilePath tempFile; public BlobStoreWriter(BlobStore store) { this.store = store; try { sha1Digest = MessageDigest.GetInstance("SHA-1"); sha1Digest.Reset(); md5Digest = MessageDigest.GetInstance("MD5"); md5Digest.Reset(); } catch (NoSuchAlgorithmException e) { throw new InvalidOperationException(e); } try { OpenTempFile(); } catch (FileNotFoundException e) { throw new InvalidOperationException(e); } } /// <exception cref="System.IO.FileNotFoundException"></exception> private void OpenTempFile() { string uuid = Misc.TDCreateUUID(); string filename = string.Format("%s.blobtmp", uuid); FilePath tempDir = store.TempDir(); tempFile = new FilePath(tempDir, filename); outStream = new BufferedOutputStream(new FileOutputStream(tempFile)); } /// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public virtual void AppendData(byte[] data) { try { outStream.Write(data); } catch (IOException e) { throw new RuntimeException("Unable to write to stream.", e); } length += data.Length; sha1Digest.Update(data); md5Digest.Update(data); } internal virtual void Read(InputStream inputStream) { byte[] buffer = new byte[1024]; int len; length = 0; try { while ((len = inputStream.Read(buffer)) != -1) { outStream.Write(buffer, 0, len); sha1Digest.Update(buffer, 0, len); md5Digest.Update(buffer, 0, len); length += len; } } catch (IOException e) { throw new RuntimeException("Unable to read from stream.", e); } finally { try { inputStream.Close(); } catch (IOException e) { Log.W(Log.TagBlobStore, "Exception closing input stream", e); } } } /// <summary>Call this after all the data has been added.</summary> /// <remarks>Call this after all the data has been added.</remarks> public virtual void Finish() { try { outStream.Close(); } catch (IOException e) { Log.W(Log.TagBlobStore, "Exception closing output stream", e); } blobKey = new BlobKey(sha1Digest.Digest()); md5DigestResult = md5Digest.Digest(); } /// <summary>Call this to cancel before finishing the data.</summary> /// <remarks>Call this to cancel before finishing the data.</remarks> public virtual void Cancel() { try { outStream.Close(); } catch (IOException e) { Log.W(Log.TagBlobStore, "Exception closing output stream", e); } tempFile.Delete(); } /// <summary>Installs a finished blob into the store.</summary> /// <remarks>Installs a finished blob into the store.</remarks> public virtual void Install() { if (tempFile == null) { return; } // already installed // Move temp file to correct location in blob store: string destPath = store.PathForKey(blobKey); FilePath destPathFile = new FilePath(destPath); bool result = tempFile.RenameTo(destPathFile); // If the move fails, assume it means a file with the same name already exists; in that // case it must have the identical contents, so we're still OK. if (result == false) { Cancel(); } tempFile = null; } public virtual string MD5DigestString() { string base64Md5Digest = Base64.EncodeBytes(md5DigestResult); return string.Format("md5-%s", base64Md5Digest); } public virtual string SHA1DigestString() { string base64Sha1Digest = Base64.EncodeBytes(blobKey.GetBytes()); return string.Format("sha1-%s", base64Sha1Digest); } public virtual int GetLength() { return length; } public virtual BlobKey GetBlobKey() { return blobKey; } public virtual string GetFilePath() { return tempFile.GetPath(); } } }
/* * CP28595.cs - Cyrillic (ISO) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-915.ucm". namespace I18N.Other { using System; using I18N.Common; public class CP28595 : ByteEncoding { public CP28595() : base(28595, ToChars, "Cyrillic (ISO)", "iso-8859-5", "iso-8859-5", "iso-8859-5", true, true, true, true, 1251) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u008D', '\u008E', '\u008F', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009A', '\u009B', '\u009C', '\u009D', '\u009E', '\u009F', '\u00A0', '\u0401', '\u0402', '\u0403', '\u0404', '\u0405', '\u0406', '\u0407', '\u0408', '\u0409', '\u040A', '\u040B', '\u040C', '\u00AD', '\u040E', '\u040F', '\u0410', '\u0411', '\u0412', '\u0413', '\u0414', '\u0415', '\u0416', '\u0417', '\u0418', '\u0419', '\u041A', '\u041B', '\u041C', '\u041D', '\u041E', '\u041F', '\u0420', '\u0421', '\u0422', '\u0423', '\u0424', '\u0425', '\u0426', '\u0427', '\u0428', '\u0429', '\u042A', '\u042B', '\u042C', '\u042D', '\u042E', '\u042F', '\u0430', '\u0431', '\u0432', '\u0433', '\u0434', '\u0435', '\u0436', '\u0437', '\u0438', '\u0439', '\u043A', '\u043B', '\u043C', '\u043D', '\u043E', '\u043F', '\u0440', '\u0441', '\u0442', '\u0443', '\u0444', '\u0445', '\u0446', '\u0447', '\u0448', '\u0449', '\u044A', '\u044B', '\u044C', '\u044D', '\u044E', '\u044F', '\u2116', '\u0451', '\u0452', '\u0453', '\u0454', '\u0455', '\u0456', '\u0457', '\u0458', '\u0459', '\u045A', '\u045B', '\u045C', '\u00A7', '\u045E', '\u045F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 161) switch(ch) { case 0x00AD: break; case 0x00A7: ch = 0xFD; break; case 0x0401: case 0x0402: case 0x0403: case 0x0404: case 0x0405: case 0x0406: case 0x0407: case 0x0408: case 0x0409: case 0x040A: case 0x040B: case 0x040C: ch -= 0x0360; break; case 0x040E: case 0x040F: case 0x0410: case 0x0411: case 0x0412: case 0x0413: case 0x0414: case 0x0415: case 0x0416: case 0x0417: case 0x0418: case 0x0419: case 0x041A: case 0x041B: case 0x041C: case 0x041D: case 0x041E: case 0x041F: case 0x0420: case 0x0421: case 0x0422: case 0x0423: case 0x0424: case 0x0425: case 0x0426: case 0x0427: case 0x0428: case 0x0429: case 0x042A: case 0x042B: case 0x042C: case 0x042D: case 0x042E: case 0x042F: case 0x0430: case 0x0431: case 0x0432: case 0x0433: case 0x0434: case 0x0435: case 0x0436: case 0x0437: case 0x0438: case 0x0439: case 0x043A: case 0x043B: case 0x043C: case 0x043D: case 0x043E: case 0x043F: case 0x0440: case 0x0441: case 0x0442: case 0x0443: case 0x0444: case 0x0445: case 0x0446: case 0x0447: case 0x0448: case 0x0449: case 0x044A: case 0x044B: case 0x044C: case 0x044D: case 0x044E: case 0x044F: ch -= 0x0360; break; case 0x0451: case 0x0452: case 0x0453: case 0x0454: case 0x0455: case 0x0456: case 0x0457: case 0x0458: case 0x0459: case 0x045A: case 0x045B: case 0x045C: ch -= 0x0360; break; case 0x045E: ch = 0xFE; break; case 0x045F: ch = 0xFF; break; case 0x2116: ch = 0xF0; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 161) switch(ch) { case 0x00AD: break; case 0x00A7: ch = 0xFD; break; case 0x0401: case 0x0402: case 0x0403: case 0x0404: case 0x0405: case 0x0406: case 0x0407: case 0x0408: case 0x0409: case 0x040A: case 0x040B: case 0x040C: ch -= 0x0360; break; case 0x040E: case 0x040F: case 0x0410: case 0x0411: case 0x0412: case 0x0413: case 0x0414: case 0x0415: case 0x0416: case 0x0417: case 0x0418: case 0x0419: case 0x041A: case 0x041B: case 0x041C: case 0x041D: case 0x041E: case 0x041F: case 0x0420: case 0x0421: case 0x0422: case 0x0423: case 0x0424: case 0x0425: case 0x0426: case 0x0427: case 0x0428: case 0x0429: case 0x042A: case 0x042B: case 0x042C: case 0x042D: case 0x042E: case 0x042F: case 0x0430: case 0x0431: case 0x0432: case 0x0433: case 0x0434: case 0x0435: case 0x0436: case 0x0437: case 0x0438: case 0x0439: case 0x043A: case 0x043B: case 0x043C: case 0x043D: case 0x043E: case 0x043F: case 0x0440: case 0x0441: case 0x0442: case 0x0443: case 0x0444: case 0x0445: case 0x0446: case 0x0447: case 0x0448: case 0x0449: case 0x044A: case 0x044B: case 0x044C: case 0x044D: case 0x044E: case 0x044F: ch -= 0x0360; break; case 0x0451: case 0x0452: case 0x0453: case 0x0454: case 0x0455: case 0x0456: case 0x0457: case 0x0458: case 0x0459: case 0x045A: case 0x045B: case 0x045C: ch -= 0x0360; break; case 0x045E: ch = 0xFE; break; case 0x045F: ch = 0xFF; break; case 0x2116: ch = 0xF0; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP28595 public class ENCiso_8859_5 : CP28595 { public ENCiso_8859_5() : base() {} }; // class ENCiso_8859_5 }; // namespace I18N.Other
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.InteropServices.ComTypes { public enum TYPEKIND { TKIND_ENUM = 0, TKIND_RECORD = TKIND_ENUM + 1, TKIND_MODULE = TKIND_RECORD + 1, TKIND_INTERFACE = TKIND_MODULE + 1, TKIND_DISPATCH = TKIND_INTERFACE + 1, TKIND_COCLASS = TKIND_DISPATCH + 1, TKIND_ALIAS = TKIND_COCLASS + 1, TKIND_UNION = TKIND_ALIAS + 1, TKIND_MAX = TKIND_UNION + 1 } [Flags] public enum TYPEFLAGS : short { TYPEFLAG_FAPPOBJECT = 0x1, TYPEFLAG_FCANCREATE = 0x2, TYPEFLAG_FLICENSED = 0x4, TYPEFLAG_FPREDECLID = 0x8, TYPEFLAG_FHIDDEN = 0x10, TYPEFLAG_FCONTROL = 0x20, TYPEFLAG_FDUAL = 0x40, TYPEFLAG_FNONEXTENSIBLE = 0x80, TYPEFLAG_FOLEAUTOMATION = 0x100, TYPEFLAG_FRESTRICTED = 0x200, TYPEFLAG_FAGGREGATABLE = 0x400, TYPEFLAG_FREPLACEABLE = 0x800, TYPEFLAG_FDISPATCHABLE = 0x1000, TYPEFLAG_FREVERSEBIND = 0x2000, TYPEFLAG_FPROXY = 0x4000 } [Flags] public enum IMPLTYPEFLAGS { IMPLTYPEFLAG_FDEFAULT = 0x1, IMPLTYPEFLAG_FSOURCE = 0x2, IMPLTYPEFLAG_FRESTRICTED = 0x4, IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8, } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPEATTR { // Constant used with the memid fields. public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF); // Actual fields of the TypeAttr struct. public Guid guid; public int lcid; public int dwReserved; public int memidConstructor; public int memidDestructor; public IntPtr lpstrSchema; public int cbSizeInstance; public TYPEKIND typekind; public short cFuncs; public short cVars; public short cImplTypes; public short cbSizeVft; public short cbAlignment; public TYPEFLAGS wTypeFlags; public short wMajorVerNum; public short wMinorVerNum; public TYPEDESC tdescAlias; public IDLDESC idldescType; } [StructLayout(LayoutKind.Sequential)] public struct FUNCDESC { public int memid; // MEMBERID memid; public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode; public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam; public FUNCKIND funckind; // FUNCKIND funckind; public INVOKEKIND invkind; // INVOKEKIND invkind; public CALLCONV callconv; // CALLCONV callconv; public short cParams; // short cParams; public short cParamsOpt; // short cParamsOpt; public short oVft; // short oVft; public short cScodes; // short cScodes; public ELEMDESC elemdescFunc; // ELEMDESC elemdescFunc; public short wFuncFlags; // WORD wFuncFlags; } [Flags] public enum IDLFLAG : short { IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE, IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN, IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT, IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID, IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct IDLDESC { public IntPtr dwReserved; public IDLFLAG wIDLFlags; } [Flags] public enum PARAMFLAG : short { PARAMFLAG_NONE = 0, PARAMFLAG_FIN = 0x1, PARAMFLAG_FOUT = 0x2, PARAMFLAG_FLCID = 0x4, PARAMFLAG_FRETVAL = 0x8, PARAMFLAG_FOPT = 0x10, PARAMFLAG_FHASDEFAULT = 0x20, PARAMFLAG_FHASCUSTDATA = 0x40 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct PARAMDESC { public IntPtr lpVarValue; public PARAMFLAG wParamFlags; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPEDESC { public IntPtr lpValue; public short vt; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct ELEMDESC { public TYPEDESC tdesc; [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] public IDLDESC idldesc; [FieldOffset(0)] public PARAMDESC paramdesc; } public DESCUNION desc; } public enum VARKIND : int { VAR_PERINSTANCE = 0x0, VAR_STATIC = 0x1, VAR_CONST = 0x2, VAR_DISPATCH = 0x3 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct VARDESC { public int memid; public string lpstrSchema; [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] public int oInst; [FieldOffset(0)] public IntPtr lpvarValue; } public DESCUNION desc; public ELEMDESC elemdescVar; public short wVarFlags; public VARKIND varkind; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DISPPARAMS { public IntPtr rgvarg; public IntPtr rgdispidNamedArgs; public int cArgs; public int cNamedArgs; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct EXCEPINFO { public short wCode; public short wReserved; [MarshalAs(UnmanagedType.BStr)] public string bstrSource; [MarshalAs(UnmanagedType.BStr)] public string bstrDescription; [MarshalAs(UnmanagedType.BStr)] public string bstrHelpFile; public int dwHelpContext; public IntPtr pvReserved; public IntPtr pfnDeferredFillIn; public int scode; } public enum FUNCKIND : int { FUNC_VIRTUAL = 0, FUNC_PUREVIRTUAL = 1, FUNC_NONVIRTUAL = 2, FUNC_STATIC = 3, FUNC_DISPATCH = 4 } [Flags] public enum INVOKEKIND : int { INVOKE_FUNC = 0x1, INVOKE_PROPERTYGET = 0x2, INVOKE_PROPERTYPUT = 0x4, INVOKE_PROPERTYPUTREF = 0x8 } public enum CALLCONV : int { CC_CDECL = 1, CC_MSCPASCAL = 2, CC_PASCAL = CC_MSCPASCAL, CC_MACPASCAL = 3, CC_STDCALL = 4, CC_RESERVED = 5, CC_SYSCALL = 6, CC_MPWCDECL = 7, CC_MPWPASCAL = 8, CC_MAX = 9 } [Flags] public enum FUNCFLAGS : short { FUNCFLAG_FRESTRICTED = 0x1, FUNCFLAG_FSOURCE = 0x2, FUNCFLAG_FBINDABLE = 0x4, FUNCFLAG_FREQUESTEDIT = 0x8, FUNCFLAG_FDISPLAYBIND = 0x10, FUNCFLAG_FDEFAULTBIND = 0x20, FUNCFLAG_FHIDDEN = 0x40, FUNCFLAG_FUSESGETLASTERROR = 0x80, FUNCFLAG_FDEFAULTCOLLELEM = 0x100, FUNCFLAG_FUIDEFAULT = 0x200, FUNCFLAG_FNONBROWSABLE = 0x400, FUNCFLAG_FREPLACEABLE = 0x800, FUNCFLAG_FIMMEDIATEBIND = 0x1000 } [Flags] public enum VARFLAGS : short { VARFLAG_FREADONLY = 0x1, VARFLAG_FSOURCE = 0x2, VARFLAG_FBINDABLE = 0x4, VARFLAG_FREQUESTEDIT = 0x8, VARFLAG_FDISPLAYBIND = 0x10, VARFLAG_FDEFAULTBIND = 0x20, VARFLAG_FHIDDEN = 0x40, VARFLAG_FRESTRICTED = 0x80, VARFLAG_FDEFAULTCOLLELEM = 0x100, VARFLAG_FUIDEFAULT = 0x200, VARFLAG_FNONBROWSABLE = 0x400, VARFLAG_FREPLACEABLE = 0x800, VARFLAG_FIMMEDIATEBIND = 0x1000 } [Guid("00020401-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeInfo { void GetTypeAttr(out IntPtr ppTypeAttr); void GetTypeComp(out ITypeComp ppTComp); void GetFuncDesc(int index, out IntPtr ppFuncDesc); void GetVarDesc(int index, out IntPtr ppVarDesc); void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] string[] rgBstrNames, int cMaxNames, out int pcNames); void GetRefTypeOfImplType(int index, out int href); void GetImplTypeFlags(int index, out IMPLTYPEFLAGS pImplTypeFlags); void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] string[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId); void Invoke([MarshalAs(UnmanagedType.IUnknown)] object pvInstance, int memid, short wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, out int puArgErr); void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile); void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal); void GetRefTypeInfo(int hRef, out ITypeInfo ppTI); void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object? pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out object ppvObj); void GetMops(int memid, out string? pBstrMops); void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex); [PreserveSig] void ReleaseTypeAttr(IntPtr pTypeAttr); [PreserveSig] void ReleaseFuncDesc(IntPtr pFuncDesc); [PreserveSig] void ReleaseVarDesc(IntPtr pVarDesc); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // <spec>http://webdata/xml/specs/XslCompiledTransform.xml</spec> //------------------------------------------------------------------------------ using System.CodeDom.Compiler; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Xml.XPath; using System.Xml.Xsl.Qil; using System.Xml.Xsl.Runtime; using System.Xml.Xsl.Xslt; using System.Runtime.Versioning; using System.Collections.Generic; using System.Linq; namespace System.Xml.Xsl { #if ! HIDE_XSL //---------------------------------------------------------------------------------------------------- // Clarification on null values in this API: // stylesheet, stylesheetUri - cannot be null // settings - if null, XsltSettings.Default will be used // stylesheetResolver - if null, XmlNullResolver will be used for includes/imports. // However, if the principal stylesheet is given by its URI, that // URI will be resolved using XmlUrlResolver (for compatibility // with XslTransform and XmlReader). // typeBuilder - cannot be null // scriptAssemblyPath - can be null only if scripts are disabled // compiledStylesheet - cannot be null // executeMethod, queryData - cannot be null // earlyBoundTypes - null means no script types // documentResolver - if null, XmlNullResolver will be used // input, inputUri - cannot be null // arguments - null means no arguments // results, resultsFile - cannot be null //---------------------------------------------------------------------------------------------------- public sealed class XslCompiledTransform { // Reader settings used when creating XmlReader from inputUri private static readonly XmlReaderSettings s_readerSettings = null; // Version for GeneratedCodeAttribute private readonly string Version = typeof(XslCompiledTransform).Assembly.GetName().Version.ToString(); static XslCompiledTransform() { s_readerSettings = new XmlReaderSettings(); } // Options of compilation private bool _enableDebug = false; // Results of compilation private CompilerErrorCollection _compilerErrorColl = null; private XmlWriterSettings _outputSettings = null; private QilExpression _qil = null; // Executable command for the compiled stylesheet private XmlILCommand _command = null; public XslCompiledTransform() { } public XslCompiledTransform(bool enableDebug) { _enableDebug = enableDebug; } /// <summary> /// This function is called on every recompilation to discard all previous results /// </summary> private void Reset() { _compilerErrorColl = null; _outputSettings = null; _qil = null; _command = null; } /// <summary> /// Writer settings specified in the stylesheet /// </summary> public XmlWriterSettings OutputSettings { get { return _outputSettings; } } //------------------------------------------------ // Load methods //------------------------------------------------ // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public void Load(XmlReader stylesheet) { Reset(); LoadInternal(stylesheet, XsltSettings.Default, CreateDefaultResolver()); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public void Load(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { Reset(); LoadInternal(stylesheet, settings, stylesheetResolver); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public void Load(IXPathNavigable stylesheet) { Reset(); LoadInternal(stylesheet, XsltSettings.Default, CreateDefaultResolver()); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { Reset(); LoadInternal(stylesheet, settings, stylesheetResolver); } public void Load(string stylesheetUri) { Reset(); if (stylesheetUri == null) { throw new ArgumentNullException(nameof(stylesheetUri)); } LoadInternal(stylesheetUri, XsltSettings.Default, CreateDefaultResolver()); } public void Load(string stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) { Reset(); if (stylesheetUri == null) { throw new ArgumentNullException(nameof(stylesheetUri)); } LoadInternal(stylesheetUri, settings, stylesheetResolver); } private CompilerErrorCollection LoadInternal(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { if (stylesheet == null) { throw new ArgumentNullException(nameof(stylesheet)); } if (settings == null) { settings = XsltSettings.Default; } CompileXsltToQil(stylesheet, settings, stylesheetResolver); CompilerError error = GetFirstError(); if (error != null) { throw new XslLoadException(error); } if (!settings.CheckOnly) { CompileQilToMsil(settings); } return _compilerErrorColl; } private void CompileXsltToQil(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { _compilerErrorColl = new Compiler(settings, _enableDebug, null).Compile(stylesheet, stylesheetResolver, out _qil); } /// <summary> /// Returns the first compiler error except warnings /// </summary> private CompilerError GetFirstError() { foreach (CompilerError error in _compilerErrorColl) { if (!error.IsWarning) { return error; } } return null; } private void CompileQilToMsil(XsltSettings settings) { _command = new XmlILGenerator().Generate(_qil, /*typeBuilder:*/null); _outputSettings = _command.StaticData.DefaultWriterSettings; _qil = null; } //------------------------------------------------ // Load compiled stylesheet from a Type //------------------------------------------------ public void Load(Type compiledStylesheet) { Reset(); if (compiledStylesheet == null) throw new ArgumentNullException(nameof(compiledStylesheet)); object[] customAttrs = compiledStylesheet.GetCustomAttributes(typeof(GeneratedCodeAttribute), /*inherit:*/false); GeneratedCodeAttribute generatedCodeAttr = customAttrs.Length > 0 ? (GeneratedCodeAttribute)customAttrs[0] : null; // If GeneratedCodeAttribute is not there, it is not a compiled stylesheet class if (generatedCodeAttr != null && generatedCodeAttr.Tool == typeof(XslCompiledTransform).FullName) { if (new Version(Version).CompareTo(new Version(generatedCodeAttr.Version)) < 0) { throw new ArgumentException(SR.Format(SR.Xslt_IncompatibleCompiledStylesheetVersion, generatedCodeAttr.Version, Version), nameof(compiledStylesheet)); } FieldInfo fldData = compiledStylesheet.GetField(XmlQueryStaticData.DataFieldName, BindingFlags.Static | BindingFlags.NonPublic); FieldInfo fldTypes = compiledStylesheet.GetField(XmlQueryStaticData.TypesFieldName, BindingFlags.Static | BindingFlags.NonPublic); // If private fields are not there, it is not a compiled stylesheet class if (fldData != null && fldTypes != null) { // Retrieve query static data from the type byte[] queryData = fldData.GetValue(/*this:*/null) as byte[]; if (queryData != null) { MethodInfo executeMethod = compiledStylesheet.GetMethod("Execute", BindingFlags.Static | BindingFlags.NonPublic); Type[] earlyBoundTypes = (Type[])fldTypes.GetValue(/*this:*/null); // Load the stylesheet Load(executeMethod, queryData, earlyBoundTypes); return; } } } // Throw an exception if the command was not loaded if (_command == null) throw new ArgumentException(SR.Format(SR.Xslt_NotCompiledStylesheet, compiledStylesheet.FullName), nameof(compiledStylesheet)); } public void Load(MethodInfo executeMethod, byte[] queryData, Type[] earlyBoundTypes) { Reset(); if (executeMethod == null) throw new ArgumentNullException(nameof(executeMethod)); if (queryData == null) throw new ArgumentNullException(nameof(queryData)); DynamicMethod dm = executeMethod as DynamicMethod; Delegate delExec = (dm != null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : executeMethod.CreateDelegate(typeof(ExecuteDelegate)); _command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes)); _outputSettings = _command.StaticData.DefaultWriterSettings; } //------------------------------------------------ // Transform methods which take an IXPathNavigable //------------------------------------------------ public void Transform(IXPathNavigable input, XmlWriter results) { CheckArguments(input, results); Transform(input, (XsltArgumentList)null, results, CreateDefaultResolver()); } public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results) { CheckArguments(input, results); Transform(input, arguments, results, CreateDefaultResolver()); } public void Transform(IXPathNavigable input, XsltArgumentList arguments, TextWriter results) { CheckArguments(input, results); using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) { Transform(input, arguments, writer, CreateDefaultResolver()); writer.Close(); } } public void Transform(IXPathNavigable input, XsltArgumentList arguments, Stream results) { CheckArguments(input, results); using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) { Transform(input, arguments, writer, CreateDefaultResolver()); writer.Close(); } } //------------------------------------------------ // Transform methods which take an XmlReader //------------------------------------------------ public void Transform(XmlReader input, XmlWriter results) { CheckArguments(input, results); Transform(input, (XsltArgumentList)null, results, CreateDefaultResolver()); } public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results) { CheckArguments(input, results); Transform(input, arguments, results, CreateDefaultResolver()); } public void Transform(XmlReader input, XsltArgumentList arguments, TextWriter results) { CheckArguments(input, results); using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) { Transform(input, arguments, writer, CreateDefaultResolver()); writer.Close(); } } public void Transform(XmlReader input, XsltArgumentList arguments, Stream results) { CheckArguments(input, results); using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) { Transform(input, arguments, writer, CreateDefaultResolver()); writer.Close(); } } //------------------------------------------------ // Transform methods which take a uri // SxS Note: Annotations should propagate to the caller to have him either check that // the passed URIs are SxS safe or decide that they don't have to be SxS safe and // suppress the message. //------------------------------------------------ [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")] public void Transform(string inputUri, XmlWriter results) { CheckArguments(inputUri, results); using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings)) { Transform(reader, (XsltArgumentList)null, results, CreateDefaultResolver()); } } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")] public void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results) { CheckArguments(inputUri, results); using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings)) { Transform(reader, arguments, results, CreateDefaultResolver()); } } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")] public void Transform(string inputUri, XsltArgumentList arguments, TextWriter results) { CheckArguments(inputUri, results); using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings)) using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) { Transform(reader, arguments, writer, CreateDefaultResolver()); writer.Close(); } } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")] public void Transform(string inputUri, XsltArgumentList arguments, Stream results) { CheckArguments(inputUri, results); using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings)) using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) { Transform(reader, arguments, writer, CreateDefaultResolver()); writer.Close(); } } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")] public void Transform(string inputUri, string resultsFile) { if (inputUri == null) throw new ArgumentNullException(nameof(inputUri)); if (resultsFile == null) throw new ArgumentNullException(nameof(resultsFile)); // SQLBUDT 276415: Prevent wiping out the content of the input file if the output file is the same using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings)) using (XmlWriter writer = XmlWriter.Create(resultsFile, OutputSettings)) { Transform(reader, (XsltArgumentList)null, writer, CreateDefaultResolver()); writer.Close(); } } //------------------------------------------------ // Main Transform overloads //------------------------------------------------ // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) { CheckArguments(input, results); CheckCommand(); _command.Execute((object)input, documentResolver, arguments, results); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) { CheckArguments(input, results); CheckCommand(); _command.Execute((object)input.CreateNavigator(), documentResolver, arguments, results); } //------------------------------------------------ // Helper methods //------------------------------------------------ private static void CheckArguments(object input, object results) { if (input == null) throw new ArgumentNullException(nameof(input)); if (results == null) throw new ArgumentNullException(nameof(results)); } private static void CheckArguments(string inputUri, object results) { if (inputUri == null) throw new ArgumentNullException(nameof(inputUri)); if (results == null) throw new ArgumentNullException(nameof(results)); } private void CheckCommand() { if (_command == null) { throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded); } } private static XmlResolver CreateDefaultResolver() { if (LocalAppContextSwitches.AllowDefaultResolver) { return new XmlUrlResolver(); } else { return XmlNullResolver.Singleton; } } //------------------------------------------------ // Test suites entry points //------------------------------------------------ private QilExpression TestCompile(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { Reset(); CompileXsltToQil(stylesheet, settings, stylesheetResolver); return _qil; } private void TestGenerate(XsltSettings settings) { Debug.Assert(_qil != null, "You must compile to Qil first"); CompileQilToMsil(settings); } private void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) { _command.Execute(inputUri, documentResolver, arguments, results); } internal static void PrintQil(object qil, XmlWriter xw, bool printComments, bool printTypes, bool printLineInfo) { QilExpression qilExpr = (QilExpression)qil; QilXmlWriter.Options options = QilXmlWriter.Options.None; QilValidationVisitor.Validate(qilExpr); if (printComments) options |= QilXmlWriter.Options.Annotations; if (printTypes) options |= QilXmlWriter.Options.TypeInfo; if (printLineInfo) options |= QilXmlWriter.Options.LineInfo; QilXmlWriter qw = new QilXmlWriter(xw, options); qw.ToXml(qilExpr); xw.Flush(); } } #endif // ! HIDE_XSL }
// // Source.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Banshee.Base; using Banshee.Collection; using Banshee.Configuration; using Banshee.ServiceStack; namespace Banshee.Sources { public abstract class Source : ISource { private Source parent; private PropertyStore properties = new PropertyStore (); protected SourceMessage status_message; private List<SourceMessage> messages = new List<SourceMessage> (); private List<Source> child_sources = new List<Source> (); private ReadOnlyCollection<Source> read_only_children; private SourceSortType child_sort; private bool sort_children = true; private SchemaEntry<string> child_sort_schema; private SchemaEntry<bool> separate_by_type_schema; public event EventHandler Updated; public event EventHandler UserNotifyUpdated; public event EventHandler MessageNotify; public event SourceEventHandler ChildSourceAdded; public event SourceEventHandler ChildSourceRemoved; public delegate void OpenPropertiesDelegate (); protected Source (string generic_name, string name, int order) : this (generic_name, name, order, order.ToString ()) { } protected Source (string generic_name, string name, int order, string type_unique_id) : this () { GenericName = generic_name; Name = name; Order = order; TypeUniqueId = type_unique_id; SourceInitialize (); } protected Source () { child_sort = DefaultChildSort; } // This method is chained to subclasses intialize methods, // allowing at any state for delayed intialization by using the empty ctor. protected virtual void Initialize () { SourceInitialize (); } private void SourceInitialize () { // If this source is not defined in Banshee.Services, set its // ResourceAssembly to the assembly where it is defined. Assembly asm = Assembly.GetAssembly (this.GetType ());//Assembly.GetCallingAssembly (); if (asm != Assembly.GetExecutingAssembly ()) { Properties.Set<Assembly> ("ResourceAssembly", asm); } properties.PropertyChanged += OnPropertyChanged; read_only_children = new ReadOnlyCollection<Source> (child_sources); if (ApplicationContext.Debugging && ApplicationContext.CommandLine.Contains ("test-source-messages")) { TestMessages (); } LoadSortSchema (); } protected void OnSetupComplete () { /*ITrackModelSource tm_source = this as ITrackModelSource; if (tm_source != null) { tm_source.TrackModel.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (tm_source.TrackModel); // TODO if/when browsable models can be added/removed on the fly, this would need to change to reflect that foreach (IListModel model in tm_source.FilterModels) { Banshee.Collection.ExportableModel exportable = model as Banshee.Collection.ExportableModel; if (exportable != null) { exportable.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (exportable); } } }*/ } protected void Remove () { if (prefs_page != null) { prefs_page.Dispose (); } if (ServiceManager.SourceManager.ContainsSource (this)) { if (this.Parent != null) { this.Parent.RemoveChildSource (this); } else { ServiceManager.SourceManager.RemoveSource (this); } } } protected void PauseSorting () { sort_children = false; } protected void ResumeSorting () { sort_children = true; } #region Public Methods public virtual void Activate () { } public virtual void Deactivate () { } public virtual void Rename (string newName) { properties.SetString ("Name", newName); } public virtual bool AcceptsInputFromSource (Source source) { return false; } public virtual bool AcceptsUserInputFromSource (Source source) { return AcceptsInputFromSource (source); } public virtual void MergeSourceInput (Source source, SourceMergeType mergeType) { Log.ErrorFormat ("MergeSourceInput not implemented by {0}", this); } public virtual SourceMergeType SupportedMergeTypes { get { return SourceMergeType.None; } } public virtual bool SetParentSource (Source parent) { this.parent = parent; return true; } public virtual bool ContainsChildSource (Source child) { lock (Children) { return child_sources.Contains (child); } } public virtual void AddChildSource (Source child) { lock (Children) { if (!child_sources.Contains (child)) { if (child.SetParentSource (this)) { child_sources.Add (child); OnChildSourceAdded (child); } } } } public virtual void RemoveChildSource (Source child) { lock (Children) { if (child.Children.Count > 0) { child.ClearChildSources (); } child_sources.Remove (child); OnChildSourceRemoved (child); } } public virtual void ClearChildSources () { lock (Children) { while (child_sources.Count > 0) { RemoveChildSource (child_sources[child_sources.Count - 1]); } } } private class SizeComparer : IComparer<Source> { public int Compare (Source a, Source b) { return a.Count.CompareTo (b.Count); } } public virtual void SortChildSources (SourceSortType sort_type) { child_sort = sort_type; child_sort_schema.Set (child_sort.Id); SortChildSources (); } public virtual void SortChildSources () { lock (this) { if (!sort_children) { return; } sort_children = false; } if (child_sort != null && child_sort.SortType != SortType.None) { lock (Children) { child_sort.Sort (child_sources, SeparateChildrenByType); int i = 0; foreach (Source child in child_sources) { // Leave children with negative orders alone, so they can be manually // placed at the top if (child.Order >= 0) { child.Order = i++; } } } } sort_children = true; } private void LoadSortSchema () { if (ChildSortTypes.Length == 0) { return; } if (unique_id == null && type_unique_id == null) { Hyena.Log.WarningFormat ("Trying to LoadSortSchema, but source's id not set! {0}", UniqueId); return; } child_sort_schema = CreateSchema<string> ("child_sort_id", DefaultChildSort.Id, "", ""); string child_sort_id = child_sort_schema.Get (); foreach (SourceSortType sort_type in ChildSortTypes) { if (sort_type.Id == child_sort_id) { child_sort = sort_type; break; } } separate_by_type_schema = CreateSchema<bool> ("separate_by_type", false, "", ""); SortChildSources (); } public T GetProperty<T> (string name, bool inherited) { return inherited ? GetInheritedProperty<T> (name) : Properties.Get<T> (name); } public T GetInheritedProperty<T> (string name) { return Properties.Contains (name) ? Properties.Get<T> (name) : Parent != null ? Parent.GetInheritedProperty<T> (name) : default (T); } #endregion #region Protected Methods public virtual void SetStatus (string message, bool error) { SetStatus (message, !error, !error, error ? "dialog-error" : null); } public virtual void SetStatus (string message, bool can_close, bool is_spinning, string icon_name) { lock (this) { if (status_message == null) { status_message = new SourceMessage (this); PushMessage (status_message); } string status_name = String.Format ("<i>{0}</i>", GLib.Markup.EscapeText (Name)); status_message.FreezeNotify (); status_message.Text = String.Format (GLib.Markup.EscapeText (message), status_name); status_message.CanClose = can_close; status_message.IsSpinning = is_spinning; status_message.SetIconName (icon_name); status_message.IsHidden = false; status_message.ClearActions (); } status_message.ThawNotify (); } public virtual void HideStatus () { lock (this) { if (status_message != null) { RemoveMessage (status_message); status_message = null; } } } public void PushMessage (SourceMessage message) { lock (this) { messages.Insert (0, message); message.Updated += HandleMessageUpdated; } OnMessageNotify (); } protected SourceMessage PopMessage () { try { lock (this) { if (messages.Count > 0) { SourceMessage message = messages[0]; message.Updated -= HandleMessageUpdated; messages.RemoveAt (0); return message; } return null; } } finally { OnMessageNotify (); } } protected void ClearMessages () { lock (this) { if (messages.Count > 0) { foreach (SourceMessage message in messages) { message.Updated -= HandleMessageUpdated; } messages.Clear (); OnMessageNotify (); } status_message = null; } } private void TestMessages () { int count = 0; SourceMessage message_3 = null; Application.RunTimeout (5000, delegate { if (count++ > 5) { if (count == 7) { RemoveMessage (message_3); } PopMessage (); return true; } else if (count > 10) { return false; } SourceMessage message = new SourceMessage (this); message.FreezeNotify (); message.Text = String.Format ("Testing message {0}", count); message.IsSpinning = count % 2 == 0; message.CanClose = count % 2 == 1; if (count % 3 == 0) { for (int i = 2; i < count; i++) { message.AddAction (new MessageAction (String.Format ("Button {0}", i))); } } message.ThawNotify (); PushMessage (message); if (count == 3) { message_3 = message; } return true; }); } public void RemoveMessage (SourceMessage message) { lock (this) { if (messages.Remove (message)) { message.Updated -= HandleMessageUpdated; OnMessageNotify (); } } } private void HandleMessageUpdated (object o, EventArgs args) { if (CurrentMessage == o && CurrentMessage.IsHidden) { PopMessage (); } OnMessageNotify (); } protected virtual void OnMessageNotify () { EventHandler handler = MessageNotify; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceAdded (Source source) { SortChildSources (); source.Updated += OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceAdded; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnChildSourceRemoved (Source source) { source.Updated -= OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceRemoved; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnUpdated () { EventHandler handler = Updated; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceUpdated (object o, EventArgs args) { SortChildSources (); } public void NotifyUser () { OnUserNotifyUpdated (); } protected void OnUserNotifyUpdated () { if (this != ServiceManager.SourceManager.ActiveSource) { EventHandler handler = UserNotifyUpdated; if (handler != null) { handler (this, EventArgs.Empty); } } } #endregion #region Private Methods private void OnPropertyChanged (object o, PropertyChangeEventArgs args) { OnUpdated (); } #endregion #region Public Properties public ReadOnlyCollection<Source> Children { get { return read_only_children; } } string [] ISource.Children { get { return null; } } public Source Parent { get { return parent; } } public virtual string TypeName { get { return GetType ().Name; } } private string unique_id; public string UniqueId { get { if (unique_id == null && type_unique_id == null) { Log.ErrorFormat ("Creating Source.UniqueId for {0} (type {1}), but TypeUniqueId is null; trace is {2}", this.Name, GetType ().Name, System.Environment.StackTrace); } return unique_id ?? (unique_id = String.Format ("{0}-{1}", this.GetType ().Name, TypeUniqueId)); } } private string type_unique_id; protected string TypeUniqueId { get { return type_unique_id; } set { type_unique_id = value; } } public virtual bool CanRename { get { return false; } } public virtual bool HasProperties { get { return false; } } public virtual bool HasViewableTrackProperties { get { return false; } } public virtual bool HasEditableTrackProperties { get { return false; } } public virtual string Name { get { return properties.Get<string> ("Name"); } set { properties.SetString ("Name", value); } } public virtual string GenericName { get { return properties.Get<string> ("GenericName"); } set { properties.SetString ("GenericName", value); } } public int Order { get { return properties.GetInteger ("Order"); } set { properties.SetInteger ("Order", value); } } public SourceMessage CurrentMessage { get { lock (this) { return messages.Count > 0 ? messages[0] : null; } } } public virtual bool ImplementsCustomSearch { get { return false; } } public virtual bool CanSearch { get { return false; } } public virtual string FilterQuery { get { return properties.Get<string> ("FilterQuery"); } set { properties.SetString ("FilterQuery", value); } } public TrackFilterType FilterType { get { return (TrackFilterType)properties.GetInteger ("FilterType"); } set { properties.SetInteger ("FilterType", (int)value); } } public virtual bool Expanded { get { return properties.GetBoolean ("Expanded"); } set { properties.SetBoolean ("Expanded", value); } } public virtual bool? AutoExpand { get { return true; } } public virtual PropertyStore Properties { get { return properties; } } public virtual bool CanActivate { get { return true; } } public virtual int Count { get { return 0; } } public virtual int EnabledCount { get { return Count; } } private string parent_conf_id; public string ParentConfigurationId { get { if (parent_conf_id == null) { parent_conf_id = (Parent ?? this).UniqueId.Replace ('.', '_'); } return parent_conf_id; } } private string conf_id; public string ConfigurationId { get { return conf_id ?? (conf_id = UniqueId.Replace ('.', '_')); } } public virtual int FilteredCount { get { return Count; } } public virtual string TrackModelPath { get { return null; } } public static readonly SourceSortType SortNameAscending = new SourceSortType ( "NameAsc", Catalog.GetString ("Name"), SortType.Ascending, null); // null comparer b/c we already fall back to sorting by name public static readonly SourceSortType SortSizeAscending = new SourceSortType ( "SizeAsc", Catalog.GetString ("Size Ascending"), SortType.Ascending, new SizeComparer ()); public static readonly SourceSortType SortSizeDescending = new SourceSortType ( "SizeDesc", Catalog.GetString ("Size Descending"), SortType.Descending, new SizeComparer ()); private static SourceSortType[] sort_types = new SourceSortType[] {}; public virtual SourceSortType[] ChildSortTypes { get { return sort_types; } } public SourceSortType ActiveChildSort { get { return child_sort; } } public virtual SourceSortType DefaultChildSort { get { return null; } } public bool SeparateChildrenByType { get { return separate_by_type_schema.Get (); } set { separate_by_type_schema.Set (value); SortChildSources (); } } #endregion #region Status Message Stuff private static DurationStatusFormatters duration_status_formatters = new DurationStatusFormatters (); public static DurationStatusFormatters DurationStatusFormatters { get { return duration_status_formatters; } } protected virtual int StatusFormatsCount { get { return duration_status_formatters.Count; } } public virtual int CurrentStatusFormat { get { return ConfigurationClient.Get<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", 0); } set { ConfigurationClient.Set<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", value); } } public SchemaEntry<T> CreateSchema<T> (string name) { return CreateSchema<T> (name, default(T), null, null); } public SchemaEntry<T> CreateSchema<T> (string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}", ParentConfigurationId), name, defaultValue, shortDescription, longDescription); } public SchemaEntry<T> CreateSchema<T> (string ns, string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}.{1}", ParentConfigurationId, ns), name, defaultValue, shortDescription, longDescription); } public virtual string PreferencesPageId { get { return null; } } private Banshee.Preferences.SourcePage prefs_page; public Banshee.Preferences.Page PreferencesPage { get { return prefs_page ?? (prefs_page = new Banshee.Preferences.SourcePage (this)); } } public void CycleStatusFormat () { int new_status_format = CurrentStatusFormat + 1; if (new_status_format >= StatusFormatsCount) { new_status_format = 0; } CurrentStatusFormat = new_status_format; } private const string STATUS_BAR_SEPARATOR = " \u2013 "; public virtual string GetStatusText () { StringBuilder builder = new StringBuilder (); int count = FilteredCount; if (count == 0) { return String.Empty; } var count_str = String.Format ("{0:N0}", count); builder.AppendFormat (GetPluralItemCountString (count), count_str); if (this is IDurationAggregator && StatusFormatsCount > 0) { var duration = ((IDurationAggregator)this).Duration; if (duration > TimeSpan.Zero) { builder.Append (STATUS_BAR_SEPARATOR); duration_status_formatters[CurrentStatusFormat] (builder, ((IDurationAggregator)this).Duration); } } if (this is IFileSizeAggregator) { long bytes = (this as IFileSizeAggregator).FileSize; if (bytes > 0) { builder.Append (STATUS_BAR_SEPARATOR); builder.AppendFormat (new FileSizeQueryValue (bytes).ToUserQuery ()); } } return builder.ToString (); } public virtual string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} item", "{0} items", count); } #endregion public override string ToString () { return Name; } /*string IService.ServiceName { get { return String.Format ("{0}{1}", DBusServiceManager.MakeDBusSafeString (Name), "Source"); } }*/ // FIXME: Replace ISource with IDBusExportable when it's enabled again ISource ISource.Parent { get { if (Parent != null) { return ((Source)this).Parent; } else { return null /*ServiceManager.SourceManager*/; } } } } }