context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; namespace Orleans.Providers { /// <summary> /// Providers configuration and loading error semantics: /// 1) We will only load the providers that were specified in the config. /// If a provider is not specified in the config, we will not attempt to load it. /// Specificaly, it means both storage and streaming providers are loaded only if configured. /// 2) If a provider is specified in the config, but was not loaded (no type found, or constructor failed, or Init failed), the silo will fail to start. /// /// Loading providers workflow and error handling implementation: /// 1) Load ProviderCategoryConfiguration. /// a) If CategoryConfiguration not found - it is not an error, continue. /// 2) Go over all assemblies and load all found providers and instantiate them via ProviderTypeManager. /// a) If a certain found provider type failed to get instantiated, it is not an error, continue. /// 3) Validate all providers were loaded: go over all provider config and check that we could indeed load and instantiate all of them. /// a) If failed to load or instantiate at least one configured provider, fail the silo start. /// 4) InitProviders: call Init on all loaded providers. /// a) Failure to init a provider wil result in silo failing to start. /// </summary> /// <typeparam name="TProvider"></typeparam> internal class ProviderLoader<TProvider> where TProvider : IProvider { private readonly Dictionary<string, TProvider> providers; private IDictionary<string, IProviderConfiguration> providerConfigs; private readonly Logger logger; public ProviderLoader() { logger = LogManager.GetLogger("ProviderLoader/" + typeof(TProvider).Name, LoggerType.Runtime); providers = new Dictionary<string, TProvider>(); } public void LoadProviders(IDictionary<string, IProviderConfiguration> configs, IProviderManager providerManager) { providerConfigs = configs ?? new Dictionary<string, IProviderConfiguration>(); foreach (IProviderConfiguration providerConfig in providerConfigs.Values) ((ProviderConfiguration)providerConfig).SetProviderManager(providerManager); // Load providers ProviderTypeLoader.AddProviderTypeManager(t => typeof(TProvider).IsAssignableFrom(t), RegisterProviderType); ValidateProviders(); } private void ValidateProviders() { foreach (IProviderConfiguration providerConfig in providerConfigs.Values) { TProvider provider; ProviderConfiguration fullConfig = (ProviderConfiguration) providerConfig; if (providers.TryGetValue(providerConfig.Name, out provider)) { logger.Verbose(ErrorCode.Provider_ProviderLoadedOk, "Provider of type {0} name {1} located ok.", fullConfig.Type, fullConfig.Name); continue; } string msg = string.Format("Provider of type {0} name {1} was not loaded." + "Please check that you deployed the assembly in which the provider class is defined to the execution folder.", fullConfig.Type, fullConfig.Name); logger.Error(ErrorCode.Provider_ConfiguredProviderNotLoaded, msg); throw new OrleansException(msg); } } public async Task InitProviders(IProviderRuntime providerRuntime) { Dictionary<string, TProvider> copy; lock (providers) { copy = providers.ToDictionary(p => p.Key, p => p.Value); } foreach (var provider in copy) { string name = provider.Key; try { await provider.Value.Init(provider.Key, providerRuntime, providerConfigs[name]); } catch (Exception exc) { logger.Error(ErrorCode.Provider_ErrorFromInit, string.Format("Exception initializing provider Name={0} Type={1}", name, provider), exc); throw; } } } // used only for testing internal void AddProvider(string name, TProvider provider, IProviderConfiguration config) { lock (providers) { providers.Add(name, provider); } } internal int GetNumLoadedProviders() { lock (providers) { return providers.Count; } } public TProvider GetProvider(string name, bool caseInsensitive = false) { TProvider provider; if (!TryGetProvider(name, out provider, caseInsensitive)) { throw new KeyNotFoundException(string.Format("Cannot find provider of type {0} with Name={1}", typeof(TProvider).FullName, name)); } return provider; } public bool TryGetProvider(string name, out TProvider provider, bool caseInsensitive = false) { lock (providers) { if (providers.TryGetValue(name, out provider)) return provider != null; if (!caseInsensitive) return provider != null; // Try all lower case if (!providers.TryGetValue(name.ToLowerInvariant(), out provider)) { // Try all upper case providers.TryGetValue(name.ToUpperInvariant(), out provider); } } return provider != null; } public IList<TProvider> GetProviders() { lock (providers) { return providers.Values.ToList(); } } public TProvider GetDefaultProvider(string defaultProviderName) { lock (providers) { TProvider provider; // Use provider named "Default" if present if (!providers.TryGetValue(defaultProviderName, out provider)) { // Otherwise, if there is only a single provider listed, use that if (providers.Count == 1) provider = providers.First().Value; } if (provider != null) return provider; string errMsg = "Cannot find default provider for " + typeof(TProvider); logger.Error(ErrorCode.Provider_NoDefaultProvider, errMsg); throw new InvalidOperationException(errMsg); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void RegisterProviderType(Type t) { // First, figure out the provider type name var typeName = TypeUtils.GetFullName(t); // Now see if we have any config entries for that type // If there's no config entry, then we don't load the type Type[] constructorBindingTypes = new[] { typeof(string), typeof(XmlElement) }; foreach (var entry in providerConfigs.Values) { var fullConfig = (ProviderConfiguration) entry; if (fullConfig.Type != typeName) continue; // Found one! Now look for an appropriate constructor; try TProvider(string, Dictionary<string,string>) first var constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorBindingTypes, null); var parms = new object[] { typeName, entry.Properties }; if (constructor == null) { // See if there's a default constructor to use, if there's no two-parameter constructor constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); parms = new object[0]; } if (constructor == null) continue; TProvider instance; try { instance = (TProvider)constructor.Invoke(parms); } catch (Exception ex) { logger.Warn(ErrorCode.Provider_InstanceConstructionError1, "Error constructing an instance of a " + typeName + " provider using type " + t.Name + " for provider with name " + fullConfig.Name, ex); return; } lock (providers) { providers[fullConfig.Name] = instance; } logger.Info(ErrorCode.Provider_Loaded, "Loaded provider of type {0} Name={1}", typeName, fullConfig.Name); } } } }
namespace Ioke.Lang { using System; using System.Collections.Generic; using System.IO; using Ioke.Lang.Parser; using Ioke.Lang.Parser.Functional; using Ioke.Lang.Util; public class IokeMain { private const string HELP = "Usage: ioke [switches] -- [programfile] [arguments]\n" + " -Cdirectory execute with directory as CWD\n" + " -d debug, set debug flag\n" + " -e script execute the script. if provided, no program file is necessary.\n" + " there can be many of these provided on the same command line.\n" + " -h, --help help, this message\n" + " -Idir add directory to 'System loadPath'. May be used more than once\n" + " --copyright print the copyright\n" + " --version print current version\n"; public static void Main(string[] args) { string current = System.Reflection.Assembly.GetExecutingAssembly().Location; string iokeHome = new FileInfo(current).Directory.Parent.FullName; string iokeLib = Path.Combine(iokeHome, "lib"); Runtime r = new Runtime(new FunctionalOperatorShufflerFactory()); r.Init(); IokeObject context = r.Ground; Message mx = new Message(r, ".", null, true); mx.Line = 0; mx.Position = 0; IokeObject message = r.CreateMessage(mx); string cwd = null; var scripts = new SaneList<string>(); var loadDirs = new SaneList<string>(); bool debug = false; try { int start = 0; bool done = false; bool readStdin = false; bool printedSomething = false; for(;!done && start<args.Length;start++) { string arg = args[start]; if(arg.Length > 0) { if(arg[0] != '-') { done = true; break; } else { if(arg.Equals("--")) { done = true; } else if(arg.Equals("-d")) { debug = true; r.Debug = true; } else if(arg.StartsWith("-e")) { if(arg.Length == 2) { scripts.Add(args[++start]); } else { scripts.Add(arg.Substring(2)); } } else if(arg.StartsWith("-I")) { if(arg.Length == 2) { loadDirs.Add(args[++start]); } else { loadDirs.Add(arg.Substring(2)); } } else if(arg.Equals("-h") || arg.Equals("--help")) { Console.Error.Write(HELP); return; } else if(arg.Equals("--version")) { Console.Error.WriteLine(getVersion()); printedSomething = true; } else if(arg.Equals("--copyright")) { Console.Error.Write(COPYRIGHT); printedSomething = true; } else if(arg.Equals("-")) { readStdin = true; } else if(arg[1] == 'C') { if(arg.Length == 2) { cwd = args[++start]; } else { cwd = arg.Substring(2); } } else { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(r.Condition, message, context, "Error", "CommandLine", "DontUnderstandOption"), null).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", context); condition.SetCell("option", r.NewText(arg)); r.ErrorCondition(condition); } } } } if(cwd != null) { r.CurrentWorkingDirectory = cwd; } ((IokeSystem)IokeObject.dataOf(r.System)).CurrentProgram = "-e"; string lib = Environment.GetEnvironmentVariable("ioke.lib"); if(lib == null) { lib = iokeLib; } ((IokeSystem)IokeObject.dataOf(r.System)).AddLoadPath(lib + "/ioke"); ((IokeSystem)IokeObject.dataOf(r.System)).AddLoadPath("lib/ioke"); foreach(string ss in loadDirs) { ((IokeSystem)IokeObject.dataOf(r.System)).AddLoadPath(ss); } foreach(string script in scripts) { r.EvaluateStream("-e", new StringReader(script), message, context); } if(readStdin) { ((IokeSystem)IokeObject.dataOf(r.System)).CurrentProgram = "<stdin>"; r.EvaluateStream("<stdin>", Console.In, message, context); } if(args.Length > start) { if(args.Length > (start+1)) { for(int i=start+1,j=args.Length; i<j; i++) { r.AddArgument(args[i]); } } string file = args[start]; if(file.StartsWith("\"")) { file = file.Substring(1, file.Length-1); } if(file.Length > 1 && file[file.Length-1] == '"') { file = file.Substring(0, file.Length-1); } ((IokeSystem)IokeObject.dataOf(r.System)).CurrentProgram = file; r.EvaluateFile(file, message, context); } else { if(!readStdin && scripts.Count == 0 && !printedSomething) { r.EvaluateString("use(\"builtin/iik\"). IIk mainLoop", message, context); } } r.TearDown(); } catch(ControlFlow.Exit e) { int exitVal = e.ExitValue; try { r.TearDown(); } catch(ControlFlow.Exit e2) { exitVal = e2.ExitValue; } Environment.Exit(exitVal); } catch(ControlFlow e) { string name = e.GetType().FullName; System.Console.Error.WriteLine("unexpected control flow: " + name.Substring(name.LastIndexOf(".") + 1).ToLower()); if(debug) { System.Console.Error.WriteLine(e); } Environment.Exit(1); } } public static string getVersion() { try { using(Stream s = typeof(IokeSystem).Assembly.GetManifestResourceStream("Ioke.Lang.version.properties")) { using(StreamReader sr = new StreamReader(s, System.Text.Encoding.UTF8)) { var result = new Dictionary<string, string>(); while(!sr.EndOfStream) { string ss = sr.ReadLine(); if(ss.IndexOf('=') != -1) { string[] parts = ss.Split('='); result[parts[0].Trim()] = parts[1].Trim(); } } string version = result["ioke.build.versionString"]; string date = result["ioke.build.date"]; string commit = result["ioke.build.commit"]; return version + " [" + date + " -- " + commit + "]"; } } } catch(System.Exception) { } return ""; } private const string COPYRIGHT = "Copyright (c) 2009 Ola Bini, [email protected]\n"+ "\n"+ "Permission is hereby granted, free of charge, to any person obtaining a copy\n"+ "of this software and associated documentation files (the \"Software\"), to deal\n"+ "in the Software without restriction, including without limitation the rights\n"+ "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"+ "copies of the Software, and to permit persons to whom the Software is\n"+ "furnished to do so, subject to the following conditions:\n"+ "\n"+ "The above copyright notice and this permission notice shall be included in\n"+ "all copies or substantial portions of the Software.\n"+ "\n"+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"+ "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"+ "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"+ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"+ "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"+ "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"+ "THE SOFTWARE.\n"; } }
using System; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; using System.Drawing; using TribalWars.Villages.Buildings; using TribalWars.Villages.Resources; using TribalWars.Villages.Units; using TribalWars.Worlds; namespace TribalWars.Browsers.Reporting { /// <summary> /// Represents a Tribal Wars attack report /// </summary> public class Report : IComparable<Report>, IEquatable<Report>, IXmlSerializable { #region Fields // players internal ReportVillage _defender; internal ReportVillage _attacker; // report date internal DateTime? _dateReport; internal DateTime _dateCopied; // General stuff internal string _luck; internal string _morale; internal string _winner; internal float _loyaltyBegin; internal int _loyaltyEnd; // resources internal int _resourceHaulGot; // stole this much resources internal int _resourceHaulMax; // max resources your troops could captures internal Resource _resourcesHaul; // Actual haul internal Resource _resourcesLeft; // Left in the village (if scouts went along) // identifies the report internal ReportTypes _reportType; internal ReportStatusses _reportStatus; internal ReportFlags _reportFlag; // output options internal ReportOutputOptions _reportOptions; // Troops internal Dictionary<UnitTypes, ReportUnit> _attack = new Dictionary<UnitTypes, ReportUnit>(); internal Dictionary<UnitTypes, ReportUnit> _defense = new Dictionary<UnitTypes, ReportUnit>(); internal Dictionary<BuildingTypes, ReportBuilding> _buildings; internal int _calculatedPoints; #endregion #region Properties /// <summary> /// Gets the defending village /// </summary> public ReportVillage Defender { get { return _defender; } } /// <summary> /// Gets the attacking village /// </summary> public ReportVillage Attacker { get { return _attacker; } } /// <summary> /// Gets the report date or the copy date if the latter is unknown /// </summary> public DateTime Date { get { if (_dateReport.HasValue) return _dateReport.Value; return _dateCopied; } } /// <summary> /// Gets the report date /// </summary> public DateTime? ReportDate { get { return _dateReport; } } /// <summary> /// Gets the luck factor /// </summary> public string Luck { get { return _luck; } } /// <summary> /// Gets the morale /// </summary> public string Morale { get { return _morale; } } /// <summary> /// Gets the winner (attacker/defender) /// </summary> public string Winner { get { return _winner; } } /// <summary> /// Gets the loyalty before the attack /// </summary> public float LoyaltyBegin { get { return _loyaltyBegin; } } /// <summary> /// Gets the loyalty after the attack /// </summary> public int LoyaltyEnd { get { return _loyaltyEnd; } } /// <summary> /// Gets the total haul /// </summary> public int ResourceHaulGot { get { return _resourceHaulGot; } } /// <summary> /// Gets the maximum haul /// </summary> /// <remarks>If Got is different from Max the village is emptied</remarks> public int ResourceHaulMax { get { return _resourceHaulMax; } } /// <summary> /// Gets the haul details /// </summary> public Resource ResourcesHaul { get { return _resourcesHaul; } } /// <summary> /// The amount of resources left in the village /// </summary> /// <remarks>When a scout was sent with the attack</remarks> public Resource ResourcesLeft { get { return _resourcesLeft; } } /// <summary> /// Gets the report type /// </summary> public ReportTypes ReportType { get { return _reportType; } } /// <summary> /// Gets the winner of the attack /// </summary> public ReportStatusses ReportStatus { get { return _reportStatus; } } /// <summary> /// Get additional info on the attack /// </summary> public ReportFlags ReportFlag { get { return _reportFlag; } } /// <summary> /// Gets the output options /// </summary> public ReportOutputOptions ReportOptions { get { return _reportOptions; } } /// <summary> /// Gets the attack army /// </summary> public Dictionary<UnitTypes, ReportUnit> Attack { get { return _attack; } } /// <summary> /// Gets the defending army /// </summary> public Dictionary<UnitTypes, ReportUnit> Defense { get { return _defense; } } /// <summary> /// Gets the scouted buildings /// </summary> public Dictionary<BuildingTypes, ReportBuilding> Buildings { get { return _buildings; } } /// <summary> /// Gets the calculated points based on scouted buildings /// </summary> public int CalculatedPoints { get { return _calculatedPoints; } } #endregion #region Constructors public Report() { _dateCopied = World.Default.Settings.ServerTime; _resourcesHaul = new Resource(); _resourcesLeft = new Resource(); _defense = new Dictionary<UnitTypes, ReportUnit>(); _buildings = new Dictionary<BuildingTypes, ReportBuilding>(); } #endregion #region Public Methods /// <summary> /// Sets the report date /// </summary> public void SetReportDate(DateTime date) { _dateReport = date; } /// <summary> /// Calculates the total amount of troops in the village /// </summary> /// <param name="units">The units dictionary</param> /// <param name="type">Calculate for what state of the battle</param> public static int GetTotalPeople(Dictionary<UnitTypes, ReportUnit> units, TotalPeople type) { int total = 0; foreach (ReportUnit unit in units.Values) { switch (type) { case TotalPeople.Start: total += unit.AmountStart * unit.Unit.Cost.People; break; case TotalPeople.Out: total += unit.AmountOut * unit.Unit.Cost.People; break; case TotalPeople.Lost: total += unit.AmountLost * unit.Unit.Cost.People; break; case TotalPeople.EndPlusOut: total += unit.AmountEndPlusOut * unit.Unit.Cost.People; break; case TotalPeople.End: total += unit.AmountEnd * unit.Unit.Cost.People; break; } } return total; } /// <summary> /// Gets the population in the buildings /// </summary> public int GetTotalPeopleInBuildings() { int farmBuildings = 0; foreach (ReportBuilding build in Buildings.Values) { farmBuildings += build.GetTotalPeople(); } return farmBuildings; } /// <summary> /// Gets the total resource space /// </summary> /// <remarks>This is the (warehouse - hiding place) * 3</remarks> public int GetTotalResourceRoom() { if (Buildings != null) { ReportBuilding warehouse = null, hide = null; if (Buildings.ContainsKey(BuildingTypes.Warehouse)) warehouse = Buildings[BuildingTypes.Warehouse]; if (Buildings.ContainsKey(BuildingTypes.HidingPlace)) hide = Buildings[BuildingTypes.HidingPlace]; if (warehouse != null) { int room = warehouse.GetTotalProduction(); if (hide != null) room -= hide.GetTotalProduction(); return room * 3; } } return 0; } #endregion #region Printers /// <summary> /// Generates standard BBCode output /// </summary> public string BBCode() { return ReportBbCodeOutput.Generate(this); } #endregion #region Painters protected int ImageXOffset = 20; protected int ImageYOffset = 20; protected int ImageYTextOffset = 5; protected int ResourceYOffset = 10; protected static Pen _borderPen = new Pen(Color.Black, 2); /// <summary> /// Draws the report to a canvas /// </summary> public virtual void Paint(Graphics g) { ReportPainter.Paint(g, this); } #endregion #region Static Methods /// <summary> /// Returns an image corresponding with the outcome of the battle /// </summary> public static Image GetCircleImage(Report report) { switch (report.ReportStatus) { case ReportStatusses.Failure: return Images.ReportRed; case ReportStatusses.Success: if (report.ReportType == ReportTypes.Scout) { return Images.ReportBlue; } else { return Images.ReportGreen; } case ReportStatusses.HalfSuccess: return Images.ReportYellow; } return null; } /// <summary> /// Returns an image corresponding with the nature of the battle /// </summary> public static Image GetInfoImage(Report report) { switch (report.ReportType) { case ReportTypes.Attack: return BuildingImages.Barracks; case ReportTypes.Fake: return Images.Fake; case ReportTypes.Farm: return BuildingImages.Farm; case ReportTypes.Noble: return UnitImages.Noble; case ReportTypes.Scout: return UnitImages.Scout; } return null; } #endregion #region IComparable<Report> Members public int CompareTo(Report other) { TimeSpan span = other.Date - Date; if (span.TotalSeconds > 0) return -1; else return 1; } public override int GetHashCode() { return Date.GetHashCode(); } public override bool Equals(object obj) { return Equals(obj as Report); } public bool Equals(Report other) { if (other == null) return false; if (other.Date != Date || other.Defender.Village != Defender.Village || other.Attacker.Village != Attacker.Village) return false; foreach (ReportUnit unit in _attack.Values) { if (!other._attack.ContainsKey(unit.Unit.Type) || !unit.Equals(other._attack[unit.Unit.Type])) return false; } foreach (ReportUnit unit in _defense.Values) { if (!other._defense.ContainsKey(unit.Unit.Type) || !unit.Equals(other._defense[unit.Unit.Type])) return false; } return true; } #endregion #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public virtual void ReadXml(XmlReader r) { r.MoveToContent(); string reportDate = r.GetAttribute(0); DateTime reportDateTest; if (DateTime.TryParse(reportDate, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out reportDateTest)) _dateReport = reportDateTest; _dateCopied = Convert.ToDateTime(r.GetAttribute(1), System.Globalization.CultureInfo.InvariantCulture); r.Read(); _reportType = (ReportTypes)Convert.ToInt32(r.ReadElementString("Type")); _reportStatus = (ReportStatusses)Convert.ToInt32(r.ReadElementString("Status")); _reportFlag = (ReportFlags)Convert.ToInt32(r.ReadElementString("Flags")); r.MoveToContent(); _loyaltyBegin = Convert.ToInt32(r.GetAttribute(0)); _loyaltyEnd = Convert.ToInt32(r.GetAttribute(1)); r.Read(); r.MoveToContent(); _attacker = new ReportVillage(); _attacker.ReadXml(r); //r.ReadEndElement(); //r.MoveToContent(); _defender = new ReportVillage(); _defender.ReadXml(r); //r.Read(); //r.MoveToContent(); //r.ReadStartElement(); //r.MoveToContent(); _resourcesHaul = new Resource(); r.Read(); _resourcesHaul.ReadXml(r); //r.ReadEndElement(); _resourceHaulMax = Convert.ToInt32(r.ReadElementString("Max")); r.Read(); r.Read(); _resourcesLeft = new Resource(); _resourcesLeft.ReadXml(r); r.Read(); DateTime? tempDate; _attack = ReportUnit.LoadXmlList(r, out tempDate); _defense = ReportUnit.LoadXmlList(r, out tempDate); _buildings = ReportBuilding.LoadXmlList(r, out tempDate); r.ReadEndElement(); r.Read(); } public virtual void WriteXml(XmlWriter w) { w.WriteStartElement("Report"); if (_dateReport.HasValue) w.WriteAttributeString("Report", _dateReport.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); else w.WriteAttributeString("Report", ""); w.WriteAttributeString("Copied", _dateCopied.ToString(System.Globalization.CultureInfo.InvariantCulture)); w.WriteElementString("Type", ((int)_reportType).ToString()); w.WriteElementString("Status", ((int)_reportStatus).ToString()); w.WriteElementString("Flags", ((int)_reportFlag).ToString()); w.WriteStartElement("Loyalty"); w.WriteAttributeString("Begin", _loyaltyBegin.ToString()); w.WriteAttributeString("End", _loyaltyEnd.ToString()); w.WriteEndElement(); Attacker.WriteXml(w); Defender.WriteXml(w); w.WriteStartElement("Haul"); _resourcesHaul.WriteXml(w); w.WriteElementString("Max", _resourceHaulMax.ToString()); w.WriteEndElement(); w.WriteStartElement("Scouted"); _resourcesLeft.WriteXml(w); w.WriteEndElement(); ReportUnit.WriteXmlList(w, "Attack", Attack, true, null); ReportUnit.WriteXmlList(w, "Defense", Defense, true, null); ReportBuilding.WriteXmlList(w, Buildings, null); w.WriteEndElement(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ServiceStack.DesignPatterns.Model; namespace ServiceStack.Examples.ServiceModel.Types { [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class CustomerOrders { public CustomerOrders() { this.Orders = new List<Order>(); } [DataMember] public Customer Customer { get; set; } [DataMember] public List<Order> Orders { get; set; } public override bool Equals(object obj) { var other = obj as CustomerOrders; if (other == null) return false; var i = 0; return this.Customer.Equals(other.Customer) && this.Orders.All(x => x.Equals(other.Orders[i++])); } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class Customer : IHasStringId { public Customer() { } public Customer(string customerId, string companyName, string contactName, string contactTitle, string address, string city, string region, string postalCode, string country, string phoneNo, string faxNo, byte[] picture) { Id = customerId; CompanyName = companyName; ContactName = contactName; ContactTitle = contactTitle; Address = address; City = city; Region = region; PostalCode = postalCode; Country = country; Phone = phoneNo; Fax = faxNo; Picture = picture; } [DataMember] public string Id { get; set; } [DataMember] public string CompanyName { get; set; } [DataMember] public string ContactName { get; set; } [DataMember] public string ContactTitle { get; set; } [DataMember] public string Address { get; set; } [DataMember] public string City { get; set; } [DataMember] public string Region { get; set; } [DataMember] public string PostalCode { get; set; } [DataMember] public string Country { get; set; } [DataMember] public string Phone { get; set; } [DataMember] public string Fax { get; set; } //[TextField] //[DataMember] public byte[] Picture { get; set; } public override bool Equals(object obj) { var other = obj as Customer; if (other == null) return false; return this.Address == other.Address && this.City == other.City && this.CompanyName == other.CompanyName && this.ContactName == other.ContactName && this.ContactTitle == other.ContactTitle && this.Country == other.Country && this.Fax == other.Fax && this.Id == other.Id && this.Phone == other.Phone && this.Picture == other.Picture && this.PostalCode == other.PostalCode && this.Region == other.Region; } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class Order { public Order() { this.OrderDetails = new List<OrderDetail>(); } [DataMember] public OrderHeader OrderHeader { get; set; } [DataMember] public List<OrderDetail> OrderDetails { get; set; } public override bool Equals(object obj) { var other = obj as Order; if (other == null) return false; var i = 0; return this.OrderHeader.Equals(other.OrderHeader) && this.OrderDetails.All(x => x.Equals(other.OrderDetails[i++])); } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class OrderHeader : IHasIntId { public OrderHeader() { } public OrderHeader( int orderId, string customerId, int employeeId, DateTime? orderDate, DateTime? requiredDate, DateTime? shippedDate, int shipVia, decimal freight, string shipName, string address, string city, string region, string postalCode, string country) { Id = orderId; CustomerId = customerId; EmployeeId = employeeId; OrderDate = orderDate; RequiredDate = requiredDate; ShippedDate = shippedDate; ShipVia = shipVia; Freight = freight; ShipName = shipName; ShipAddress = address; ShipCity = city; ShipRegion = region; ShipPostalCode = postalCode; ShipCountry = country; } [DataMember] public int Id { get; set; } [DataMember] public string CustomerId { get; set; } [DataMember] public int EmployeeId { get; set; } [DataMember] public DateTime? OrderDate { get; set; } [DataMember] public DateTime? RequiredDate { get; set; } [DataMember] public DateTime? ShippedDate { get; set; } [DataMember] public int? ShipVia { get; set; } [DataMember] public decimal Freight { get; set; } [DataMember] public string ShipName { get; set; } [DataMember] public string ShipAddress { get; set; } [DataMember] public string ShipCity { get; set; } [DataMember] public string ShipRegion { get; set; } [DataMember] public string ShipPostalCode { get; set; } [DataMember] public string ShipCountry { get; set; } public override bool Equals(object obj) { var other = obj as OrderHeader; if (other == null) return false; return this.Id == other.Id && this.CustomerId == other.CustomerId && this.EmployeeId == other.EmployeeId && this.OrderDate == other.OrderDate && this.RequiredDate == other.RequiredDate && this.ShippedDate == other.ShippedDate && this.ShipVia == other.ShipVia && this.Freight == other.Freight && this.ShipName == other.ShipName && this.ShipAddress == other.ShipAddress && this.ShipCity == other.ShipCity && this.ShipRegion == other.ShipRegion && this.ShipPostalCode == other.ShipPostalCode && this.ShipCountry == other.ShipCountry; } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class OrderDetail : IHasStringId { public OrderDetail() { } public OrderDetail( int orderId, int productId, decimal unitPrice, short quantity, double discount) { OrderId = orderId; ProductId = productId; UnitPrice = unitPrice; Quantity = quantity; Discount = discount; } public string Id { get { return this.OrderId + "/" + this.ProductId; } } [DataMember] public int OrderId { get; set; } [DataMember] public int ProductId { get; set; } [DataMember] public decimal UnitPrice { get; set; } [DataMember] public short Quantity { get; set; } [DataMember] public double Discount { get; set; } public override bool Equals(object obj) { var other = obj as OrderDetail; if (other == null) return false; return this.Id == other.Id && this.OrderId == other.OrderId && this.ProductId == other.ProductId && this.UnitPrice == other.UnitPrice && this.Quantity == other.Quantity && this.Discount == other.Discount; } } }
/** * This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). * It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) */ using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using System; using System.Collections; using System.Collections.Generic; using UnityEngine.EventSystems; using System.Linq; namespace Fungus { public class MenuDialog : MonoBehaviour { // Currently active Menu Dialog used to display Menu options public static MenuDialog activeMenuDialog; [Tooltip("Automatically select the first interactable button when the menu is shown.")] public bool autoSelectFirstButton = false; [NonSerialized] public Button[] cachedButtons; [NonSerialized] public Slider cachedSlider; public static MenuDialog GetMenuDialog() { if (activeMenuDialog == null) { // Use first Menu Dialog found in the scene (if any) MenuDialog md = GameObject.FindObjectOfType<MenuDialog>(); if (md != null) { activeMenuDialog = md; } if (activeMenuDialog == null) { // Auto spawn a menu dialog object from the prefab GameObject prefab = Resources.Load<GameObject>("MenuDialog"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.SetActive(false); go.name = "MenuDialog"; activeMenuDialog = go.GetComponent<MenuDialog>(); } } } return activeMenuDialog; } public virtual void Awake() { Button[] optionButtons = GetComponentsInChildren<Button>(); cachedButtons = optionButtons; Slider timeoutSlider = GetComponentInChildren<Slider>(); cachedSlider = timeoutSlider; if (Application.isPlaying) { // Don't auto disable buttons in the editor Clear(); } } public virtual void OnEnable() { // The canvas may fail to update if the menu dialog is enabled in the first game frame. // To fix this we just need to force a canvas update when the object is enabled. Canvas.ForceUpdateCanvases(); } public virtual void Clear() { StopAllCoroutines(); Button[] optionButtons = GetComponentsInChildren<Button>(); foreach (UnityEngine.UI.Button button in optionButtons) { button.onClick.RemoveAllListeners(); } foreach (UnityEngine.UI.Button button in optionButtons) { if (button != null) { button.gameObject.SetActive(false); } } Slider timeoutSlider = GetComponentInChildren<Slider>(); if (timeoutSlider != null) { timeoutSlider.gameObject.SetActive(false); } } public virtual bool AddOption(string text, bool interactable, Block targetBlock) { bool addedOption = false; foreach (Button button in cachedButtons) { if (!button.gameObject.activeSelf) { button.gameObject.SetActive(true); button.interactable = interactable; if (interactable && autoSelectFirstButton && !cachedButtons.Select((x) => x.gameObject).Contains(EventSystem.current.currentSelectedGameObject)) { EventSystem.current.SetSelectedGameObject(button.gameObject); } Text textComponent = button.GetComponentInChildren<Text>(); if (textComponent != null) { textComponent.text = text; } Block block = targetBlock; button.onClick.AddListener(delegate { EventSystem.current.SetSelectedGameObject(null); StopAllCoroutines(); // Stop timeout Clear(); HideSayDialog(); if (block != null) { #if UNITY_EDITOR // Select the new target block in the Flowchart window Flowchart flowchart = block.GetFlowchart(); flowchart.selectedBlock = block; #endif gameObject.SetActive(false); block.StartExecution(); } }); addedOption = true; break; } } return addedOption; } public int DisplayedOptionsCount { get { int count = 0; foreach (Button button in cachedButtons) { if (button.gameObject.activeSelf) { count++; } } return count; } } public virtual void HideSayDialog() { SayDialog sayDialog = SayDialog.GetSayDialog(); if (sayDialog != null) { sayDialog.FadeOut(); } } public virtual void ShowTimer(float duration, Block targetBlock) { if (cachedSlider != null) { cachedSlider.gameObject.SetActive(true); gameObject.SetActive(true); StopAllCoroutines(); StartCoroutine(WaitForTimeout(duration, targetBlock)); } } protected virtual IEnumerator WaitForTimeout(float timeoutDuration, Block targetBlock) { float elapsedTime = 0; Slider timeoutSlider = GetComponentInChildren<Slider>(); while (elapsedTime < timeoutDuration) { if (timeoutSlider != null) { float t = 1f - elapsedTime / timeoutDuration; timeoutSlider.value = t; } elapsedTime += Time.deltaTime; yield return null; } Clear(); gameObject.SetActive(false); HideSayDialog(); if (targetBlock != null) { targetBlock.StartExecution(); } } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.Collections; using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// A set of Assert methods operationg on one or more collections /// </summary> public class CollectionAssert { #region Equals and ReferenceEquals /// <summary> /// The Equals method throws an AssertionException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new AssertionException("Assert.Equals should not be used for Assertions"); } /// <summary> /// override the default ReferenceEquals to throw an AssertionException. This /// implementation makes sure there is no mistake in calling this function /// as part of Assert. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new AssertionException("Assert.ReferenceEquals should not be used for Assertions"); } #endregion #region AllItemsAreInstancesOfType /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType) { AllItemsAreInstancesOfType(collection, expectedType, string.Empty, null); } /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> /// <param name="message">The message that will be displayed on failure</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType, string message) { AllItemsAreInstancesOfType(collection, expectedType, message, null); } /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType, string message, params object[] args) { Assert.That(collection, new AllItemsConstraint(new InstanceOfTypeConstraint(expectedType)), message, args); } #endregion #region AllItemsAreNotNull /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> public static void AllItemsAreNotNull (IEnumerable collection) { AllItemsAreNotNull(collection, string.Empty, null); } /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void AllItemsAreNotNull (IEnumerable collection, string message) { AllItemsAreNotNull(collection, message, null); } /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreNotNull (IEnumerable collection, string message, params object[] args) { Assert.That(collection, new AllItemsConstraint(new NotConstraint(new EqualConstraint(null))), message, args); } #endregion #region AllItemsAreUnique /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> public static void AllItemsAreUnique (IEnumerable collection) { AllItemsAreUnique(collection, string.Empty, null); } /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void AllItemsAreUnique (IEnumerable collection, string message) { AllItemsAreUnique(collection, message, null); } /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreUnique (IEnumerable collection, string message, params object[] args) { Assert.That(collection, new UniqueItemsConstraint(), message, args); } #endregion #region AreEqual /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreEqual (IEnumerable expected, IEnumerable actual) { //AreEqual(expected, actual, null, string.Empty, null); Assert.That(actual, new EqualConstraint(expected)); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreEqual(expected, actual, comparer, string.Empty, null); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, string message) { //AreEqual(expected, actual, null, message, null); Assert.That(actual, new EqualConstraint(expected), message); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message) { AreEqual(expected, actual, comparer, message, null); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { //AreEqual(expected, actual, null, message, args); Assert.That(actual, new EqualConstraint(expected), message, args); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, new EqualConstraint(expected).Using(comparer), message, args); } #endregion #region AreEquivalent /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual) { AreEquivalent(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual, string message) { AreEquivalent(expected, actual, message, null); } /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, new CollectionEquivalentConstraint(expected), message, args); } #endregion #region AreNotEqual /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual) { Assert.That(actual, new NotConstraint(new EqualConstraint(expected))); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreNotEqual(expected, actual, comparer, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, string message) { Assert.That(actual, new NotConstraint(new EqualConstraint(expected)), message); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message) { AreNotEqual(expected, actual, comparer, message, null); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { //AreNotEqual(expected, actual, null, message, args); //Assert.AreNotEqual( expected, actual, message, args ); Assert.That(actual, new NotConstraint(new EqualConstraint(expected)), message, args); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, new NotConstraint(new EqualConstraint(expected).Using(comparer)), message, args); } #endregion #region AreNotEquivalent /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual) { AreNotEquivalent(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual, string message) { AreNotEquivalent(expected, actual, message, null); } /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, new NotConstraint(new CollectionEquivalentConstraint(expected)), message, args); } #endregion #region Contains /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> public static void Contains (IEnumerable collection, Object actual) { Contains(collection, actual, string.Empty, null); } /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> /// <param name="message">The message that will be displayed on failure</param> public static void Contains (IEnumerable collection, Object actual, string message) { Contains(collection, actual, message, null); } /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Contains (IEnumerable collection, Object actual, string message, params object[] args) { Assert.That(collection, new CollectionContainsConstraint(actual), message, args); } #endregion #region DoesNotContain /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> public static void DoesNotContain (IEnumerable collection, Object actual) { DoesNotContain(collection, actual, string.Empty, null); } /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> /// <param name="message">The message that will be displayed on failure</param> public static void DoesNotContain (IEnumerable collection, Object actual, string message) { DoesNotContain(collection, actual, message, null); } /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void DoesNotContain (IEnumerable collection, Object actual, string message, params object[] args) { Assert.That(collection, new NotConstraint( new CollectionContainsConstraint( actual ) ), message, args); } #endregion #region IsNotSubsetOf /// <summary> /// Asserts that superset is not a subject of subset. /// </summary> /// <param name="subset">The IEnumerable superset to be considered</param> /// <param name="superset">The IEnumerable subset to be considered</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset) { IsNotSubsetOf(subset, superset, string.Empty, null); } /// <summary> /// Asserts that superset is not a subject of subset. /// </summary> /// <param name="subset">The IEnumerable superset to be considered</param> /// <param name="superset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset, string message) { IsNotSubsetOf(subset, superset, message, null); } /// <summary> /// Asserts that superset is not a subject of subset. /// </summary> /// <param name="subset">The IEnumerable superset to be considered</param> /// <param name="superset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset, string message, params object[] args) { Assert.That(subset, new NotConstraint(new CollectionSubsetConstraint(superset)), message, args); } #endregion #region IsSubsetOf /// <summary> /// Asserts that superset is a subset of subset. /// </summary> /// <param name="subset">The IEnumerable superset to be considered</param> /// <param name="superset">The IEnumerable subset to be considered</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset) { IsSubsetOf(subset, superset, string.Empty, null); } /// <summary> /// Asserts that superset is a subset of subset. /// </summary> /// <param name="subset">The IEnumerable superset to be considered</param> /// <param name="superset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset, string message) { IsSubsetOf(subset, superset, message, null); } /// <summary> /// Asserts that superset is a subset of subset. /// </summary> /// <param name="subset">The IEnumerable superset to be considered</param> /// <param name="superset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset, string message, params object[] args) { Assert.That(subset, new CollectionSubsetConstraint(superset), message, args); } #endregion #region IsEmpty /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new EmptyConstraint(), message, args); } /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> public static void IsEmpty(IEnumerable collection, string message) { IsEmpty(collection, message, null); } /// <summary> /// Assert that an array,list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsEmpty(IEnumerable collection) { IsEmpty(collection, string.Empty, null); } #endregion #region IsNotEmpty /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new NotConstraint(new EmptyConstraint()), message, args); } /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> public static void IsNotEmpty(IEnumerable collection, string message) { IsNotEmpty(collection, message, null); } /// <summary> /// Assert that an array,list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsNotEmpty(IEnumerable collection) { IsNotEmpty(collection, string.Empty, null); } #endregion #region IsOrdered /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsOrdered(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new CollectionOrderedConstraint(), message, args); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> public static void IsOrdered(IEnumerable collection, string message) { IsOrdered(collection, message, null); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsOrdered(IEnumerable collection) { IsOrdered(collection, string.Empty, null); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsOrdered(IEnumerable collection, IComparer comparer, string message, params object[] args) { Assert.That(collection, new CollectionOrderedConstraint().Using(comparer), message, args); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> /// <param name="message">The message to be displayed on failure</param> public static void IsOrdered(IEnumerable collection, IComparer comparer, string message) { IsOrdered(collection, comparer, message, null); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> public static void IsOrdered(IEnumerable collection, IComparer comparer) { IsOrdered(collection, comparer, string.Empty, null); } #endregion } }
using Entitas; using NSpec; using System.Collections.Generic; using System.Linq; class describe_EntityIndex : nspec { void when_primary_index() { context["single key"] = () => { PrimaryEntityIndex<TestEntity, string> index = null; IContext<TestEntity> ctx = null; IGroup<TestEntity> group = null; before = () => { ctx = new MyTestContext(); group = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA)); index = new PrimaryEntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { var nameAge = c as NameAgeComponent; return nameAge != null ? nameAge.name : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name; }); }; context["when entity for key doesn't exist"] = () => { it["returns null when getting entity for unknown key"] = () => { index.GetEntity("unknownKey").should_be_null(); }; }; context["when entity for key exists"] = () => { const string name = "Max"; TestEntity entity = null; before = () => { var nameAgeComponent = new NameAgeComponent(); nameAgeComponent.name = name; entity = ctx.CreateEntity(); entity.AddComponent(CID.ComponentA, nameAgeComponent); }; it["gets entity for key"] = () => { index.GetEntity(name).should_be_same(entity); }; it["retains entity"] = () => { entity.retainCount.should_be(3); // Context, Group, EntityIndex }; it["has existing entity"] = () => { var newIndex = new PrimaryEntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { var nameAge = c as NameAgeComponent; return nameAge != null ? nameAge.name : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name; }); newIndex.GetEntity(name).should_be_same(entity); }; it["releases and removes entity from index when component gets removed"] = () => { entity.RemoveComponent(CID.ComponentA); index.GetEntity(name).should_be_null(); entity.retainCount.should_be(1); // Context }; it["throws when adding an entity for the same key"] = expect<EntityIndexException>(() => { var nameAgeComponent = new NameAgeComponent(); nameAgeComponent.name = name; entity = ctx.CreateEntity(); entity.AddComponent(CID.ComponentA, nameAgeComponent); }); it["can ToString"] = () => { index.ToString().should_be("PrimaryEntityIndex(TestIndex)"); }; context["when deactivated"] = () => { before = () => { index.Deactivate(); }; it["clears index and releases entity"] = () => { index.GetEntity(name).should_be_null(); entity.retainCount.should_be(2); // Context, Group }; it["doesn't add entities anymore"] = () => { var nameAgeComponent = new NameAgeComponent(); nameAgeComponent.name = name; ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent); index.GetEntity(name).should_be_null(); }; context["when activated"] = () => { before = () => { index.Activate(); }; it["has existing entity"] = () => { index.GetEntity(name).should_be_same(entity); }; it["adds new entities"] = () => { var nameAgeComponent = new NameAgeComponent(); nameAgeComponent.name = "Jack"; entity = ctx.CreateEntity(); entity.AddComponent(CID.ComponentA, nameAgeComponent); index.GetEntity("Jack").should_be_same(entity); }; }; }; }; }; context["multiple keys"] = () => { PrimaryEntityIndex<TestEntity, string> index = null; IContext<TestEntity> ctx = null; IGroup<TestEntity> group = null; before = () => { ctx = new MyTestContext(); group = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA)); index = new PrimaryEntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { var nameAge = c as NameAgeComponent; return nameAge != null ? new [] { nameAge.name + "1", nameAge.name + "2" } : new [] { ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name + "1", ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name + "2" }; }); }; context["when entity for key exists"] = () => { const string name = "Max"; TestEntity entity = null; before = () => { var nameAgeComponent = new NameAgeComponent(); nameAgeComponent.name = name; entity = ctx.CreateEntity(); entity.AddComponent(CID.ComponentA, nameAgeComponent); }; it["retains entity"] = () => { entity.retainCount.should_be(3); var safeAerc = entity.aerc as SafeAERC; if (safeAerc != null) { safeAerc.owners.should_contain(index); } }; it["gets entity for key"] = () => { index.GetEntity(name + "1").should_be_same(entity); index.GetEntity(name + "2").should_be_same(entity); }; it["releases and removes entity from index when component gets removed"] = () => { entity.RemoveComponent(CID.ComponentA); index.GetEntity(name + "1").should_be_null(); index.GetEntity(name + "2").should_be_null(); entity.retainCount.should_be(1); var safeAerc = entity.aerc as SafeAERC; if (safeAerc != null) { safeAerc.owners.should_not_contain(index); } }; it["has existing entity"] = () => { index.Deactivate(); index.Activate(); index.GetEntity(name + "1").should_be_same(entity); index.GetEntity(name + "2").should_be_same(entity); }; }; }; } void when_index() { context["single key"] = () => { EntityIndex<TestEntity, string> index = null; IContext<TestEntity> ctx = null; IGroup<TestEntity> group = null; before = () => { ctx = new MyTestContext(); group = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA)); index = new EntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { var nameAge = c as NameAgeComponent; return nameAge != null ? nameAge.name : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name; }); }; context["when entity for key doesn't exist"] = () => { it["has no entities"] = () => { index.GetEntities("unknownKey").should_be_empty(); }; }; context["when entity for key exists"] = () => { const string name = "Max"; NameAgeComponent nameAgeComponent = null; TestEntity entity1 = null; TestEntity entity2 = null; before = () => { nameAgeComponent = new NameAgeComponent(); nameAgeComponent.name = name; entity1 = ctx.CreateEntity(); entity1.AddComponent(CID.ComponentA, nameAgeComponent); entity2 = ctx.CreateEntity(); entity2.AddComponent(CID.ComponentA, nameAgeComponent); }; it["gets entities for key"] = () => { var entities = index.GetEntities(name); entities.Count.should_be(2); entities.should_contain(entity1); entities.should_contain(entity2); }; it["retains entity"] = () => { entity1.retainCount.should_be(3); // Context, Group, EntityIndex entity2.retainCount.should_be(3); // Context, Group, EntityIndex }; it["has existing entities"] = () => { var newIndex = new EntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { var nameAge = c as NameAgeComponent; return nameAge != null ? nameAge.name : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name; }); newIndex.GetEntities(name).Count.should_be(2); }; it["releases and removes entity from index when component gets removed"] = () => { entity1.RemoveComponent(CID.ComponentA); index.GetEntities(name).Count.should_be(1); entity1.retainCount.should_be(1); // Context }; it["can ToString"] = () => { index.ToString().should_be("EntityIndex(TestIndex)"); }; context["when deactivated"] = () => { before = () => { index.Deactivate(); }; it["clears index and releases entity"] = () => { index.GetEntities(name).should_be_empty(); entity1.retainCount.should_be(2); // Context, Group entity2.retainCount.should_be(2); // Context, Group }; it["doesn't add entities anymore"] = () => { ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent); index.GetEntities(name).should_be_empty(); }; context["when activated"] = () => { before = () => { index.Activate(); }; it["has existing entities"] = () => { var entities = index.GetEntities(name); entities.Count.should_be(2); entities.should_contain(entity1); entities.should_contain(entity2); }; it["adds new entities"] = () => { var entity3 = ctx.CreateEntity(); entity3.AddComponent(CID.ComponentA, nameAgeComponent); var entities = index.GetEntities(name); entities.Count.should_be(3); entities.should_contain(entity1); entities.should_contain(entity2); entities.should_contain(entity3); }; }; }; }; }; context["multiple keys"] = () => { EntityIndex<TestEntity, string> index = null; IContext<TestEntity> ctx = null; IGroup<TestEntity> group = null; TestEntity entity1 = null; TestEntity entity2 = null; before = () => { ctx = new MyTestContext(); group = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA)); index = new EntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { return e == entity1 ? new [] { "1", "2" } : new [] { "2", "3" }; }); }; context["when entity for key exists"] = () => { before = () => { entity1 = ctx.CreateEntity(); entity1.AddComponentA(); entity2 = ctx.CreateEntity(); entity2.AddComponentA(); }; it["retains entity"] = () => { entity1.retainCount.should_be(3); entity2.retainCount.should_be(3); var safeAerc1 = entity1.aerc as SafeAERC; if (safeAerc1 != null) { safeAerc1.owners.should_contain(index); } var safeAerc2 = entity1.aerc as SafeAERC; if (safeAerc2 != null) { safeAerc2.owners.should_contain(index); } }; it["has entity"] = () => { index.GetEntities("1").Count.should_be(1); index.GetEntities("2").Count.should_be(2); index.GetEntities("3").Count.should_be(1); }; it["gets entity for key"] = () => { index.GetEntities("1").First().should_be_same(entity1); index.GetEntities("2").should_contain(entity1); index.GetEntities("2").should_contain(entity2); index.GetEntities("3").First().should_be_same(entity2); }; it["releases and removes entity from index when component gets removed"] = () => { entity1.RemoveComponent(CID.ComponentA); index.GetEntities("1").Count.should_be(0); index.GetEntities("2").Count.should_be(1); index.GetEntities("3").Count.should_be(1); entity1.retainCount.should_be(1); entity2.retainCount.should_be(3); var safeAerc1 = entity1.aerc as SafeAERC; if (safeAerc1 != null) { safeAerc1.owners.should_not_contain(index); } var safeAerc2 = entity2.aerc as SafeAERC; if (safeAerc2 != null) { safeAerc2.owners.should_contain(index); } }; it["has existing entities"] = () => { index.Deactivate(); index.Activate(); index.GetEntities("1").First().should_be_same(entity1); index.GetEntities("2").should_contain(entity1); index.GetEntities("2").should_contain(entity2); index.GetEntities("3").First().should_be_same(entity2); }; }; }; } void when_index_multiple_components() { #pragma warning disable EntityIndex<TestEntity, string> index = null; IContext<TestEntity> ctx = null; IGroup<TestEntity> group = null; before = () => { ctx = new MyTestContext(); }; it["gets last component that triggered adding entity to group"] = () => { IComponent receivedComponent = null; group = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA, CID.ComponentB)); index = new EntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { receivedComponent = c; return ((NameAgeComponent)c).name; }); var nameAgeComponent1 = new NameAgeComponent(); nameAgeComponent1.name = "Max"; var nameAgeComponent2 = new NameAgeComponent(); nameAgeComponent2.name = "Jack"; var entity = ctx.CreateEntity(); entity.AddComponent(CID.ComponentA, nameAgeComponent1); entity.AddComponent(CID.ComponentB, nameAgeComponent2); receivedComponent.should_be_same(nameAgeComponent2); }; it["works with NoneOf"] = () => { var receivedComponents = new List<IComponent>(); var nameAgeComponent1 = new NameAgeComponent(); nameAgeComponent1.name = "Max"; var nameAgeComponent2 = new NameAgeComponent(); nameAgeComponent2.name = "Jack"; group = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA).NoneOf(CID.ComponentB)); index = new EntityIndex<TestEntity, string>("TestIndex", group, (e, c) => { receivedComponents.Add(c); if (c == nameAgeComponent1) { return ((NameAgeComponent)c).name; } return ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name; }); var entity = ctx.CreateEntity(); entity.AddComponent(CID.ComponentA, nameAgeComponent1); entity.AddComponent(CID.ComponentB, nameAgeComponent2); receivedComponents.Count.should_be(2); receivedComponents[0].should_be(nameAgeComponent1); receivedComponents[1].should_be(nameAgeComponent2); }; } }
//#define SA_DEBUG_MODE using UnityEngine; using System.Collections; public class TBM_Game_Example : AndroidNativeExampleBase { public GameObject avatar; public GameObject hi; public SA_Label playerLabel; public SA_Label gameState; public SA_Label parisipants; public DefaultPreviewButton connectButton; public DefaultPreviewButton helloButton; public DefaultPreviewButton leaveRoomButton; public DefaultPreviewButton showRoomButton; public DefaultPreviewButton[] ConnectionDependedntButtons; public SA_PartisipantUI[] patrisipants; //private Texture defaulttexture; void Start() { playerLabel.text = "Player Disconnected"; //defaulttexture = avatar.GetComponent<Renderer>().material.mainTexture; GooglePlayConnection.ActionPlayerConnected += OnPlayerConnected; GooglePlayConnection.ActionPlayerDisconnected += OnPlayerDisconnected; GooglePlayConnection.ActionConnectionResultReceived += OnConnectionResult; if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) { //checking if player already connected OnPlayerConnected (); } InitTBM(); } public void Init() { GooglePlayTBM.ActionMatchUpdated += ActionMatchUpdated; } #if UNITY_ANDROID private GP_TBM_Match mMatch = null; //... // Call this method when a player has completed his turn and wants to // go onto the next player, which may be himself. public void playTurn() { string nextParticipantId = string.Empty; // Get the next participant in the game-defined way, possibly round-robin. //nextParticipantId = getNextParticipantId(); // Get the updated state. In this example, we simply use a // a pre-defined string. In your game, there may be more complicated state. string mTurnData = "My turn data sample"; // At this point, you might want to show a waiting dialog so that // the current player does not try to submit turn actions twice. AndroidNativeUtility.ShowPreloader("Loading..", "Sending the tunr data"); // Invoke the next turn. We are converting our data to a byte array. System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] byteArray = encoding.GetBytes(mTurnData); GooglePlayTBM.Instance.TakeTrun(mMatch.Id, byteArray, nextParticipantId); } #endif void ActionMatchUpdated (GP_TBM_UpdateMatchResult result) { // Match Date updated } public void InitTBM() { int variant = 1; GooglePlayTBM.Instance.SetVariant (variant); int ROLE_WIZARD = 0x4; // 100 in binary GooglePlayTBM.Instance.SetExclusiveBitMask (ROLE_WIZARD); GooglePlayTBM.Instance.RegisterMatchUpdateListener(); } public void ShowInboxUI() { GooglePlayTBM.Instance.ShowInbox(); } public void FinishMathc() { } public void findMatch() { GooglePlayTBM.ActionMatchCreationCanceled += ActionMatchCreationCanceled; GooglePlayTBM.ActionMatchInitiated += ActionMatchInitiated; int minPlayers = 2; int maxPlayers = 2; bool allowAutomatch = true; GooglePlayTBM.Instance.StartSelectOpponentsView (minPlayers, maxPlayers, allowAutomatch); } void ActionMatchCreationCanceled (AndroidActivityResult result) { // Match Creation was cnaceled by user } void ActionMatchInitiated (GP_TBM_MatchInitiatedResult result) { if(!result.IsSucceeded) { AndroidMessage.Create("Match Initi Failed", "Status code: " + result.Response); return; } GP_TBM_Match Match = result.Match; // If this player is not the first player in this match, continue. if (Match.Data != null) { //showTurnUI(match); return; } // Otherwise, this is the first player. Initialize the game state. //initGame(match); // Let the player take the first turn //showTurnUI(match); } public void LoadAllMatchersInfo() { GooglePlayTBM.Instance.LoadAllMatchesInfo (GP_TBM_MatchesSortOrder.SORT_ORDER_MOST_RECENT_FIRST); } public void LoadActiveMatchesInfo() { GooglePlayTBM.Instance.LoadMatchesInfo (GP_TBM_MatchesSortOrder.SORT_ORDER_MOST_RECENT_FIRST, GP_TBM_MatchTurnStatus.MATCH_TURN_STATUS_MY_TURN, GP_TBM_MatchTurnStatus.MATCH_TURN_STATUS_THEIR_TURN); } private void ConncetButtonPress() { Debug.Log("GooglePlayManager State -> " + GooglePlayConnection.State.ToString()); if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) { SA_StatusBar.text = "Disconnecting from Play Service..."; GooglePlayConnection.Instance.Disconnect (); } else { SA_StatusBar.text = "Connecting to Play Service..."; GooglePlayConnection.Instance.Connect (); } } private void DrawParticipants() { } void FixedUpdate() { DrawParticipants(); string title = "Connect"; if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) { title = "Disconnect"; foreach(DefaultPreviewButton btn in ConnectionDependedntButtons) { btn.EnabledButton(); } } else { foreach(DefaultPreviewButton btn in ConnectionDependedntButtons) { btn.DisabledButton(); } if(GooglePlayConnection.State == GPConnectionState.STATE_DISCONNECTED || GooglePlayConnection.State == GPConnectionState.STATE_UNCONFIGURED) { title = "Connect"; } else { title = "Connecting.."; } } connectButton.text = title; } private void OnPlayerDisconnected() { SA_StatusBar.text = "Player Disconnected"; playerLabel.text = "Player Disconnected"; } private void OnPlayerConnected() { SA_StatusBar.text = "Player Connected"; playerLabel.text = GooglePlayManager.Instance.player.name; } private void OnConnectionResult(GooglePlayConnectionResult result) { SA_StatusBar.text = "ConnectionResul: " + result.code.ToString(); Debug.Log(result.code.ToString()); } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using CodePlex2GitHub; namespace CodePlex2GitHub { [DbContext(typeof(CodePlexDbContext))] partial class CodePlexDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc2-20143") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("CodePlex2GitHub.Model.FileAttachment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("FileName"); b.HasKey("Id"); b.ToTable("FileAttachment"); }); modelBuilder.Entity("CodePlex2GitHub.Model.FileAttachmentContent", b => { b.Property<int>("FileAttachmentId"); b.Property<byte[]>("Content"); b.HasKey("FileAttachmentId"); b.HasIndex("FileAttachmentId"); b.ToTable("FileAttachmentContent"); }); modelBuilder.Entity("CodePlex2GitHub.Model.Release", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<int?>("DevelopmentStatus") .HasColumnName("DevelopmentStatusId"); b.Property<string>("Name"); b.Property<int>("ProjectID"); b.Property<DateTime?>("ReleaseDate"); b.HasKey("Id"); b.ToTable("Release"); }); modelBuilder.Entity("CodePlex2GitHub.Model.Thread", b => { b.Property<int>("ThreadId") .ValueGeneratedOnAdd(); b.Property<int>("ProjectID"); b.Property<string>("Tag"); b.Property<string>("Title"); b.HasKey("ThreadId"); b.ToTable("Thread"); }); modelBuilder.Entity("CodePlex2GitHub.Model.ThreadPost", b => { b.Property<int>("PostId") .ValueGeneratedOnAdd(); b.Property<string>("MarkedAsAnswerBy"); b.Property<DateTime?>("MarkedAsAnswerDate"); b.Property<string>("PostedBy"); b.Property<DateTime>("PostedDate"); b.Property<string>("Text"); b.Property<int?>("ThreadThreadId"); b.HasKey("PostId"); b.HasIndex("ThreadThreadId"); b.ToTable("ThreadPost"); }); modelBuilder.Entity("CodePlex2GitHub.Model.User", b => { b.Property<int>("UserId") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("UserId"); b.ToTable("User"); }); modelBuilder.Entity("CodePlex2GitHub.Model.WorkItem", b => { b.Property<int>("WorkItemId") .ValueGeneratedOnAdd(); b.Property<int?>("AssignedToUserId"); b.Property<int?>("ClosedByUserId"); b.Property<string>("ClosedComment"); b.Property<DateTime?>("ClosedDate"); b.Property<string>("Component") .IsRequired(); b.Property<string>("Custom"); b.Property<string>("Description") .IsRequired(); b.Property<int?>("LastUpdatedByUserId"); b.Property<DateTime>("LastUpdatedDate"); b.Property<string>("PlannedForRelease"); b.Property<int>("ProjectID"); b.Property<string>("ReasonClosed"); b.Property<int?>("ReportedByUserId"); b.Property<DateTime>("ReportedDate"); b.Property<int>("Severity"); b.Property<string>("Status"); b.Property<string>("Summary") .IsRequired(); b.Property<string>("Type"); b.Property<int>("VoteCount"); b.HasKey("WorkItemId"); b.HasIndex("AssignedToUserId"); b.HasIndex("ClosedByUserId"); b.HasIndex("LastUpdatedByUserId"); b.HasIndex("ReportedByUserId"); b.ToTable("WorkItems"); }); modelBuilder.Entity("CodePlex2GitHub.Model.WorkItemAttachment", b => { b.Property<int>("WorkItemId"); b.Property<int?>("FileAttachmentId"); b.Property<int>("ProjectID"); b.HasKey("WorkItemId", "FileAttachmentId"); b.HasIndex("FileAttachmentId"); b.HasIndex("WorkItemId"); b.ToTable("WorkItemAttachments"); }); modelBuilder.Entity("CodePlex2GitHub.Model.WorkItemComment", b => { b.Property<int>("CommentId") .ValueGeneratedOnAdd(); b.Property<string>("Comment"); b.Property<DateTime>("Date"); b.Property<int>("ProjectID"); b.Property<int>("UserId"); b.Property<int>("WorkItemId"); b.HasKey("CommentId"); b.HasIndex("UserId"); b.HasIndex("WorkItemId"); b.ToTable("WorkItemComments"); }); modelBuilder.Entity("CodePlex2GitHub.Model.FileAttachmentContent", b => { b.HasOne("CodePlex2GitHub.Model.FileAttachment") .WithOne() .HasForeignKey("CodePlex2GitHub.Model.FileAttachmentContent", "FileAttachmentId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("CodePlex2GitHub.Model.ThreadPost", b => { b.HasOne("CodePlex2GitHub.Model.Thread") .WithMany() .HasForeignKey("ThreadThreadId"); }); modelBuilder.Entity("CodePlex2GitHub.Model.WorkItem", b => { b.HasOne("CodePlex2GitHub.Model.User") .WithMany() .HasForeignKey("AssignedToUserId"); b.HasOne("CodePlex2GitHub.Model.User") .WithMany() .HasForeignKey("ClosedByUserId"); b.HasOne("CodePlex2GitHub.Model.User") .WithMany() .HasForeignKey("LastUpdatedByUserId"); b.HasOne("CodePlex2GitHub.Model.User") .WithMany() .HasForeignKey("ReportedByUserId"); }); modelBuilder.Entity("CodePlex2GitHub.Model.WorkItemAttachment", b => { b.HasOne("CodePlex2GitHub.Model.FileAttachment") .WithMany() .HasForeignKey("FileAttachmentId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("CodePlex2GitHub.Model.WorkItem") .WithMany() .HasForeignKey("WorkItemId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("CodePlex2GitHub.Model.WorkItemComment", b => { b.HasOne("CodePlex2GitHub.Model.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("CodePlex2GitHub.Model.WorkItem") .WithMany() .HasForeignKey("WorkItemId") .OnDelete(DeleteBehavior.Cascade); }); } } }
namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Crypto.Utilities { internal sealed class Pack { private Pack() { } internal static void UInt16_To_BE(ushort n, byte[] bs) { bs[0] = (byte)(n >> 8); bs[1] = (byte)(n); } internal static void UInt16_To_BE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n >> 8); bs[off + 1] = (byte)(n); } internal static ushort BE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] << 8 | (uint)bs[1]; return (ushort)n; } internal static ushort BE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] << 8 | (uint)bs[off + 1]; return (ushort)n; } internal static byte[] UInt32_To_BE(uint n) { byte[] bs = new byte[4]; UInt32_To_BE(n, bs, 0); return bs; } internal static void UInt32_To_BE(uint n, byte[] bs) { bs[0] = (byte)(n >> 24); bs[1] = (byte)(n >> 16); bs[2] = (byte)(n >> 8); bs[3] = (byte)(n); } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { bs[off] = (byte)(n >> 24); bs[off + 1] = (byte)(n >> 16); bs[off + 2] = (byte)(n >> 8); bs[off + 3] = (byte)(n); } internal static byte[] UInt32_To_BE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_BE(ns, bs, 0); return bs; } internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off) { for(int i = 0; i < ns.Length; ++i) { UInt32_To_BE(ns[i], bs, off); off += 4; } } internal static uint BE_To_UInt32(byte[] bs) { return (uint)bs[0] << 24 | (uint)bs[1] << 16 | (uint)bs[2] << 8 | (uint)bs[3]; } internal static uint BE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] << 24 | (uint)bs[off + 1] << 16 | (uint)bs[off + 2] << 8 | (uint)bs[off + 3]; } internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns) { for(int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt32(bs, off); off += 4; } } internal static byte[] UInt64_To_BE(ulong n) { byte[] bs = new byte[8]; UInt64_To_BE(n, bs, 0); return bs; } internal static void UInt64_To_BE(ulong n, byte[] bs) { UInt32_To_BE((uint)(n >> 32), bs); UInt32_To_BE((uint)(n), bs, 4); } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { UInt32_To_BE((uint)(n >> 32), bs, off); UInt32_To_BE((uint)(n), bs, off + 4); } internal static byte[] UInt64_To_BE(ulong[] ns) { byte[] bs = new byte[8 * ns.Length]; UInt64_To_BE(ns, bs, 0); return bs; } internal static void UInt64_To_BE(ulong[] ns, byte[] bs, int off) { for(int i = 0; i < ns.Length; ++i) { UInt64_To_BE(ns[i], bs, off); off += 8; } } internal static ulong BE_To_UInt64(byte[] bs) { uint hi = BE_To_UInt32(bs); uint lo = BE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong BE_To_UInt64(byte[] bs, int off) { uint hi = BE_To_UInt32(bs, off); uint lo = BE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } internal static void BE_To_UInt64(byte[] bs, int off, ulong[] ns) { for(int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt64(bs, off); off += 8; } } internal static void UInt16_To_LE(ushort n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); } internal static void UInt16_To_LE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); } internal static ushort LE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] | (uint)bs[1] << 8; return (ushort)n; } internal static ushort LE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] | (uint)bs[off + 1] << 8; return (ushort)n; } internal static byte[] UInt32_To_LE(uint n) { byte[] bs = new byte[4]; UInt32_To_LE(n, bs, 0); return bs; } internal static void UInt32_To_LE(uint n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); bs[2] = (byte)(n >> 16); bs[3] = (byte)(n >> 24); } internal static void UInt32_To_LE(uint n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); bs[off + 2] = (byte)(n >> 16); bs[off + 3] = (byte)(n >> 24); } internal static byte[] UInt32_To_LE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_LE(ns, bs, 0); return bs; } internal static void UInt32_To_LE(uint[] ns, byte[] bs, int off) { for(int i = 0; i < ns.Length; ++i) { UInt32_To_LE(ns[i], bs, off); off += 4; } } internal static uint LE_To_UInt32(byte[] bs) { return (uint)bs[0] | (uint)bs[1] << 8 | (uint)bs[2] << 16 | (uint)bs[3] << 24; } internal static uint LE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] | (uint)bs[off + 1] << 8 | (uint)bs[off + 2] << 16 | (uint)bs[off + 3] << 24; } internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns) { for(int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } } internal static void LE_To_UInt32(byte[] bs, int bOff, uint[] ns, int nOff, int count) { for(int i = 0; i < count; ++i) { ns[nOff + i] = LE_To_UInt32(bs, bOff); bOff += 4; } } internal static uint[] LE_To_UInt32(byte[] bs, int off, int count) { uint[] ns = new uint[count]; for(int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } return ns; } internal static byte[] UInt64_To_LE(ulong n) { byte[] bs = new byte[8]; UInt64_To_LE(n, bs, 0); return bs; } internal static void UInt64_To_LE(ulong n, byte[] bs) { UInt32_To_LE((uint)(n), bs); UInt32_To_LE((uint)(n >> 32), bs, 4); } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { UInt32_To_LE((uint)(n), bs, off); UInt32_To_LE((uint)(n >> 32), bs, off + 4); } internal static ulong LE_To_UInt64(byte[] bs) { uint lo = LE_To_UInt32(bs); uint hi = LE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong LE_To_UInt64(byte[] bs, int off) { uint lo = LE_To_UInt32(bs, off); uint hi = LE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.EC2; using Amazon.EC2.Model; namespace AWSSDK_DotNet35.UnitTests.TestTools { [TestClass] public class EC2ConstructorCustomizationsTests { [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void AssociateAddressRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.AssociateAddressRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void AssociateDhcpOptionsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.AssociateDhcpOptionsRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void AttachVolumeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.AttachVolumeRequest), new System.Type[] { typeof(string), typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void AttachVpnGatewayRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.AttachVpnGatewayRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void AuthorizeSecurityGroupIngressRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.AuthorizeSecurityGroupIngressRequest), new System.Type[] { typeof(string), typeof(List<IpPermission>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void BundleInstanceRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.BundleInstanceRequest), new System.Type[] { typeof(string), typeof(Storage), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CancelBundleTaskRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CancelBundleTaskRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CancelSpotInstanceRequestsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CancelSpotInstanceRequestsRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ConfirmProductInstanceRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ConfirmProductInstanceRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateCustomerGatewayRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateCustomerGatewayRequest), new System.Type[] { typeof(GatewayType), typeof(string), typeof(int), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateDhcpOptionsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateDhcpOptionsRequest), new System.Type[] { typeof(List<DhcpConfiguration>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateImageRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateImageRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateKeyPairRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateKeyPairRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreatePlacementGroupRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreatePlacementGroupRequest), new System.Type[] { typeof(string), typeof(PlacementStrategy), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateSecurityGroupRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateSecurityGroupRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateSnapshotRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateSnapshotRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateSpotDatafeedSubscriptionRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateSpotDatafeedSubscriptionRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateSubnetRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateSubnetRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateTagsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateTagsRequest), new System.Type[] { typeof(List<string>), typeof(List<Tag>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateVolumeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateVolumeRequest), new System.Type[] { typeof(string), typeof(int), }); EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateVolumeRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateVpcRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateVpcRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateVpnConnectionRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateVpnConnectionRequest), new System.Type[] { typeof(string), typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void CreateVpnGatewayRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.CreateVpnGatewayRequest), new System.Type[] { typeof(GatewayType), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteCustomerGatewayRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteCustomerGatewayRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteDhcpOptionsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteDhcpOptionsRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteKeyPairRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteKeyPairRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeletePlacementGroupRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeletePlacementGroupRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteSecurityGroupRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteSecurityGroupRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteSnapshotRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteSnapshotRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteSubnetRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteSubnetRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteTagsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteTagsRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteVolumeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteVolumeRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteVpcRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteVpcRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteVpnConnectionRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteVpnConnectionRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeleteVpnGatewayRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeleteVpnGatewayRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DeregisterImageRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DeregisterImageRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DescribeImageAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DescribeImageAttributeRequest), new System.Type[] { typeof(string), typeof(ImageAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DescribeInstanceAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DescribeInstanceAttributeRequest), new System.Type[] { typeof(string), typeof(InstanceAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DescribeSnapshotAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DescribeSnapshotAttributeRequest), new System.Type[] { typeof(string), typeof(SnapshotAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DescribeTagsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DescribeTagsRequest), new System.Type[] { typeof(List<Filter>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DescribeVolumesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DescribeVolumesRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DetachVolumeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DetachVolumeRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DetachVpnGatewayRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DetachVpnGatewayRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void DisassociateAddressRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.DisassociateAddressRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void GetConsoleOutputRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.GetConsoleOutputRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void GetPasswordDataRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.GetPasswordDataRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ImportKeyPairRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ImportKeyPairRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ModifyImageAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ModifyImageAttributeRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ModifyInstanceAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ModifyInstanceAttributeRequest), new System.Type[] { typeof(string), typeof(InstanceAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ModifySnapshotAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ModifySnapshotAttributeRequest), new System.Type[] { typeof(string), typeof(SnapshotAttributeName), typeof(OperationType), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void MonitorInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.MonitorInstancesRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void PurchaseReservedInstancesOfferingRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.PurchaseReservedInstancesOfferingRequest), new System.Type[] { typeof(string), typeof(int), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void RebootInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.RebootInstancesRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void RegisterImageRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.RegisterImageRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ReleaseAddressRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ReleaseAddressRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void RequestSpotInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.RequestSpotInstancesRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ResetImageAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ResetImageAttributeRequest), new System.Type[] { typeof(string), typeof(ResetImageAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ResetInstanceAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ResetInstanceAttributeRequest), new System.Type[] { typeof(string), typeof(InstanceAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void ResetSnapshotAttributeRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.ResetSnapshotAttributeRequest), new System.Type[] { typeof(string), typeof(SnapshotAttributeName), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void RevokeSecurityGroupIngressRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.RevokeSecurityGroupIngressRequest), new System.Type[] { typeof(string), typeof(List<IpPermission>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void RunInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.RunInstancesRequest), new System.Type[] { typeof(string), typeof(int), typeof(int), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void StartInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.StartInstancesRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void StopInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.StopInstancesRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void TerminateInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.TerminateInstancesRequest), new System.Type[] { typeof(List<string>), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("EC2")] public void UnmonitorInstancesRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.EC2.Model.UnmonitorInstancesRequest), new System.Type[] { typeof(List<string>), }); } void EnsureConstructorExists(System.Type type, System.Type[] constructorParams) { Assert.IsNotNull(type.GetConstructor(constructorParams)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace IotCentral.Tests.ScenarioTests { using System; using System.Collections.Generic; using System.Linq; using IotCentral.Tests.Helpers; using Microsoft.Azure.Management.IotCentral; using Microsoft.Azure.Management.IotCentral.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using Xunit; using Microsoft.Rest; using Microsoft.Rest.Azure; public class IotCentralLifeCycleTests : IotCentralTestBase { [Fact] public void TestIotCentralCreateLifeCycle() { using (MockContext context = MockContext.Start(this.GetType())) { Initialize(context); // Create Resource Group var resourceGroup = CreateResourceGroup(IotCentralTestUtilities.DefaultResourceGroupName); // Create App var app = CreateIotCentral(resourceGroup, IotCentralTestUtilities.DefaultLocation, IotCentralTestUtilities.DefaultResourceName, IotCentralTestUtilities.DefaultSubdomain); // Validate resourceName and subdomain are taken this.CheckAppNameAndSubdomainTaken(app.Name, app.Subdomain); Assert.NotNull(app); Assert.Equal(AppSku.ST1, app.Sku.Name); Assert.Equal(IotCentralTestUtilities.DefaultResourceName, app.Name); Assert.Equal(IotCentralTestUtilities.DefaultSubdomain, app.Subdomain); // Add and Get Tags IDictionary<string, string> tags = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; var appPatch = new AppPatch() { Tags = tags, DisplayName = IotCentralTestUtilities.DefaultResourceName, Subdomain = IotCentralTestUtilities.DefaultSubdomain }; app = this.iotCentralClient.Apps.Update(IotCentralTestUtilities.DefaultResourceGroupName, IotCentralTestUtilities.DefaultResourceName, appPatch); Assert.NotNull(app); Assert.True(app.Tags.Count().Equals(2)); Assert.Equal("value2", app.Tags["key2"]); // Get all Iot Central apps in a resource group var iotAppsByResourceGroup = this.iotCentralClient.Apps.ListByResourceGroup(IotCentralTestUtilities.DefaultResourceGroupName.ToLowerInvariant()).ToList(); // Get all Iot Apps in a subscription var iotAppsBySubscription = this.iotCentralClient.Apps.ListBySubscription().ToList(); // Get all of the available IoT Apps REST API operations var operationList = this.iotCentralClient.Operations.List().ToList(); // Get IoT Central Apps REST API read operation var readOperation = operationList.Where(e => e.Name.Equals("Microsoft.IoTCentral/IotApps/Read", StringComparison.OrdinalIgnoreCase)).ToList(); Assert.True(iotAppsByResourceGroup.Count > 0); Assert.True(iotAppsBySubscription.Count > 0); Assert.True(operationList.Count > 0); Assert.True(readOperation.Count.Equals(1)); } } [Fact] public void TestIotCentralUpdateLifeCycle() { using (MockContext context = MockContext.Start(this.GetType())) { this.Initialize(context); // Create Resource Group var resourceGroup = CreateResourceGroup(IotCentralTestUtilities.DefaultUpdateResourceGroupName); // Create App var app = CreateIotCentral(resourceGroup, IotCentralTestUtilities.DefaultLocation, IotCentralTestUtilities.DefaultUpdateResourceName, IotCentralTestUtilities.DefaultUpdateSubdomain); // Validate resourceName and subdomain are taken this.CheckAppNameAndSubdomainTaken(app.Name, app.Subdomain); // Update App var newSubDomain = "test-updated-sub-domain"; var newDisplayName = "test-updated-display-name"; // Add and Get Tags IDictionary<string, string> tags = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; AppPatch appPatch = new AppPatch() { Tags = tags, DisplayName = newDisplayName, Subdomain = newSubDomain }; app = UpdateIotCentral(resourceGroup, appPatch, IotCentralTestUtilities.DefaultUpdateResourceName); // List apps app = iotCentralClient.Apps.ListByResourceGroup(IotCentralTestUtilities.DefaultUpdateResourceGroupName) .FirstOrDefault(e => e.Name.Equals(IotCentralTestUtilities.DefaultUpdateResourceName, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(app); Assert.Equal(newDisplayName, app.DisplayName); Assert.True(app.Tags.Count().Equals(2)); Assert.Equal("value2", app.Tags["key2"]); } } [Fact] public void TestAppWhenNullAppSkuInfo() { var exceptionThrown = false; try { App app = new App() { Location = IotCentralTestUtilities.DefaultLocation, Sku = new AppSkuInfo(), Subdomain = IotCentralTestUtilities.DefaultUpdateSubdomain, DisplayName = IotCentralTestUtilities.DefaultUpdateResourceName }; app.Validate(); } catch (Exception ex) { exceptionThrown = true; Assert.Equal(typeof(ValidationException), ex.GetType()); } Assert.True(exceptionThrown); } [Fact] public void TestAppSkuInfoWhenNullInput() { var exceptionThrown = false; try { AppSkuInfo appSku = new AppSkuInfo(); appSku.Validate(); } catch (Exception ex) { exceptionThrown = true; Assert.Equal(typeof(ValidationException), ex.GetType()); } Assert.True(exceptionThrown); } [Fact] public void TestOperationInputsWhenNullInput() { var exceptionThrown = false; try { OperationInputs operationInput = new OperationInputs(); operationInput.Validate(); } catch (Exception ex) { exceptionThrown = true; Assert.Equal(typeof(ValidationException), ex.GetType()); } Assert.True(exceptionThrown); } [Fact] public void TestResourceWhenNullLocation() { var exceptionThrown = false; try { Resource resource = new Resource(); resource.Validate(); } catch (Exception ex) { exceptionThrown = true; Assert.Equal(typeof(ValidationException), ex.GetType()); } Assert.True(exceptionThrown); } private void CheckAppNameAndSubdomainTaken(string resourceName, string subdomain) { OperationInputs resourceNameInputs = new OperationInputs(resourceName, "IoTApps"); OperationInputs subdomainInputs = new OperationInputs(subdomain, "IoTApps"); // check if names are available var resourceNameResult = iotCentralClient.Apps.CheckNameAvailability(resourceNameInputs); var subdomainResult = iotCentralClient.Apps.CheckSubdomainAvailability(subdomainInputs); Assert.False(resourceNameResult.NameAvailable); Assert.False(subdomainResult.NameAvailable); } } }
// 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. #if FEATURE_CODEPAGES_FILE // requires BaseCodePageEncooding namespace System.Text { using System; using System.Diagnostics.Contracts; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; // SBCSCodePageEncoding [Serializable] internal class SBCSCodePageEncoding : BaseCodePageEncoding, ISerializable { // Pointers to our memory section parts [NonSerialized] [SecurityCritical] unsafe char* mapBytesToUnicode = null; // char 256 [NonSerialized] [SecurityCritical] unsafe byte* mapUnicodeToBytes = null; // byte 65536 [NonSerialized] [SecurityCritical] unsafe int* mapCodePageCached = null; // to remember which CP is cached const char UNKNOWN_CHAR=(char)0xFFFD; // byteUnknown is used for default fallback only [NonSerialized] byte byteUnknown; [NonSerialized] char charUnknown; [System.Security.SecurityCritical] // auto-generated public SBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } [System.Security.SecurityCritical] // auto-generated internal SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } // Constructor called by serialization. // Note: We use the base GetObjectData however [System.Security.SecurityCritical] // auto-generated internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // Actually this can't ever get called, CodePageEncoding is our proxy Contract.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor"); throw new ArgumentNullException("this"); } // We have a managed code page entry, so load our tables // SBCS data section looks like: // // char[256] - what each byte maps to in unicode. No support for surrogates. 0 is undefined code point // (except 0 for byte 0 is expected to be a real 0) // // byte/char* - Data for best fit (unicode->bytes), again no best fit for Unicode // 1st WORD is Unicode // of 1st character position // Next bytes are best fit byte for that position. Position is incremented after each byte // byte < 0x20 means skip the next n positions. (Where n is the byte #) // byte == 1 means that next word is another unicode code point # // byte == 0 is unknown. (doesn't override initial WCHAR[256] table! [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { // Should be loading OUR code page Contract.Assert(pCodePage->CodePage == this.dataTableCodePage, "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page if (pCodePage->ByteCount != 1) throw new NotSupportedException( Environment.GetResourceString("NotSupported_NoCodepageData", CodePage)); // Remember our unknown bytes & chars byteUnknown = (byte)pCodePage->ByteReplace; charUnknown = pCodePage->UnicodeReplace; // Get our mapped section 65536 bytes for unicode->bytes, 256 * 2 bytes for bytes->unicode // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment) byte *pMemorySection = GetSharedMemory(65536*1 + 256*2 + 4 + iExtraBytes); mapBytesToUnicode = (char*)pMemorySection; mapUnicodeToBytes = (byte*)(pMemorySection + 256 * 2); mapCodePageCached = (int*)(pMemorySection + 256 * 2 + 65536 * 1 + iExtraBytes); // If its cached (& filled in) we don't have to do anything else if (*mapCodePageCached != 0) { Contract.Assert(*mapCodePageCached == this.dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page to be same as data table code page. Cached : " + *mapCodePageCached + " Expected:" + this.dataTableCodePage); if (*mapCodePageCached != this.dataTableCodePage) throw new OutOfMemoryException( Environment.GetResourceString("Arg_OutOfMemoryException")); // If its cached (& filled in) we don't have to do anything else return; } // Need to read our data file and fill in our section. // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide) // so be careful here. Only stick legal values in here, don't stick temporary values. // Read our data file and set mapBytesToUnicode and mapUnicodeToBytes appropriately // First table is just all 256 mappings char* pTemp = (char*)&(pCodePage->FirstDataWord); for (int b = 0; b < 256; b++) { // Don't want to force 0's to map Unicode wrong. 0 byte == 0 unicode already taken care of if (pTemp[b] != 0 || b == 0) { mapBytesToUnicode[b] = pTemp[b]; if (pTemp[b] != UNKNOWN_CHAR) mapUnicodeToBytes[pTemp[b]] = (byte)b; } else { mapBytesToUnicode[b] = UNKNOWN_CHAR; } } // We're done with our mapped section, set our flag so others don't have to rebuild table. *mapCodePageCached = this.dataTableCodePage; } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Read in our best fit table [System.Security.SecurityCritical] // auto-generated protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. lock(InternalSyncObject) { // If we got a best fit array already, then don't do this if (arrayUnicodeBestFit == null) { // // Read in Best Fit table. // // First check the SBCS->Unicode best fit table, which starts right after the // 256 word data table. This table looks like word, word where 1st word is byte and 2nd // word is replacement for that word. It ends when byte == 0. byte* pData = (byte*)&(pCodePage->FirstDataWord); pData += 512; // Need new best fit array char[] arrayTemp = new char[256]; for (int i = 0; i < 256; i++) arrayTemp[i] = mapBytesToUnicode[i]; // See if our words are zero ushort byteTemp; while ((byteTemp = *((ushort*)pData)) != 0) { Contract.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}", byteTemp, CodePage, (int)arrayTemp[byteTemp])); pData += 2; arrayTemp[byteTemp] = *((char*)pData); pData += 2; } // Remember our new array arrayBytesBestFit = arrayTemp; // It was on 0, it needs to be on next byte pData+=2; byte* pUnicodeToSBCS = pData; // Now count our characters from our Unicode->SBCS best fit table, // which is right after our 256 byte data table int iBestFitCount = 0; // Now do the UnicodeToBytes Best Fit mapping (this is the one we normally think of when we say "best fit") // pData should be pointing at the first data point for Bytes->Unicode table int unicodePosition = *((ushort*)pData); pData += 2; while (unicodePosition < 0x10000) { // Get the next byte byte input = *pData; pData++; // build our table: if (input == 1) { // Use next 2 bytes as our byte position unicodePosition = *((ushort*)pData); pData+=2; } else if (input < 0x20 && input > 0 && input != 0x1e) { // Advance input characters unicodePosition += input; } else { // Use this character if it isn't zero if (input > 0) iBestFitCount++; // skip this unicode position in any case unicodePosition++; } } // Make an array for our best fit data arrayTemp = new char[iBestFitCount*2]; // Now actually read in the data // reset pData should be pointing at the first data point for Bytes->Unicode table pData = pUnicodeToSBCS; unicodePosition = *((ushort*)pData); pData += 2; iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte byte input = *pData; pData++; // build our table: if (input == 1) { // Use next 2 bytes as our byte position unicodePosition = *((ushort*)pData); pData+=2; } else if (input < 0x20 && input > 0 && input != 0x1e) { // Advance input characters unicodePosition += input; } else { // Check for escape for glyph range if (input == 0x1e) { // Its an escape, so just read next byte directly input = *pData; pData++; } // 0 means just skip me if (input > 0) { // Use this character arrayTemp[iBestFitCount++] = (char)unicodePosition; // Have to map it to Unicode because best fit will need unicode value of best fit char. arrayTemp[iBestFitCount++] = mapBytesToUnicode[input]; // This won't work if it won't round trip. Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}", (int)mapBytesToUnicode[input], (int)input, CodePage)); } unicodePosition++; } } // Remember it arrayUnicodeBestFit = arrayTemp; } } } // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); // Need to test fallback EncoderReplacementFallback fallback = null; // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start"); } else { // If we aren't using default fallback then we may have a complicated count. fallback = this.EncoderFallback as EncoderReplacementFallback; } if ((fallback != null && fallback.MaxCharCount == 1)/* || bIsBestFit*/) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) count++; return (count); } // It had a funky fallback, so its more complicated // Need buffer maybe later EncoderFallbackBuffer fallbackBuffer = null; // prepare our end int byteCount = 0; char* charEnd = chars + count; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char byte bTemp = mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Create & init fallback buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; // chars has moved so we need to remember figure it out so Exception fallback // index will be correct fallbackBuffer.InternalInitialize(charEnd - count, charEnd, encoder, false); } // Get Fallback fallbackBuffer.InternalFallback(ch, ref chars); continue; } // We'll use this one byteCount++; } Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end"); return (int)byteCount; } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); // Need to test fallback EncoderReplacementFallback fallback = null; // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && // encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { // If we aren't using default fallback then we may have a complicated count. fallback = this.EncoderFallback as EncoderReplacementFallback; } // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Make sure our fallback character is valid first byte bReplacement = mapUnicodeToBytes[fallback.DefaultString[0]]; // Check for replacements in range, otherwise fall back to slow version. if (bReplacement != 0) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = bReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // Simple way while (chars < charEnd) { char ch2 = *chars; chars++; byte bTemp = mapUnicodeToBytes[ch2]; // Check for fallback if (bTemp == 0 && ch2 != (char)0) *bytes = bReplacement; else *bytes = bTemp; bytes++; } // Clear encoder if (encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars-charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // For fallback we may need a fallback buffer, we know we aren't default fallback EncoderFallbackBuffer fallbackBuffer = null; // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback(charLeftOver, ref chars); if (fallbackBuffer.Remaining > byteEnd - bytes) { // Throw it, if we don't have enough for this we never will ThrowBytesOverflow(encoder, true); } } // Now we may have fallback char[] already from the encoder fallback above // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char byte bTemp = mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { // Get Fallback if ( fallbackBuffer == null ) { // Create & init fallback buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; // chars has moved so we need to remember figure it out so Exception fallback // index will be correct fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Make sure we have enough room. Each fallback char will be 1 output char // (or recursion exception will be thrown) fallbackBuffer.InternalFallback(ch, ref chars); if (fallbackBuffer.Remaining > byteEnd - bytes) { // Didn't use this char, reset it Contract.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)"); chars--; fallbackBuffer.InternalReset(); // Throw it & drop this data ThrowBytesOverflow(encoder, chars == charStart); break; } continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { Contract.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)"); chars--; // don't use last char } ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } // Go ahead and add it *bytes = bTemp; bytes++; } // encoder stuff if we have one if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } // Expect Empty fallback buffer for SBCS Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); // See if we have best fit bool bUseBestFit = false; // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback fallback = null; if (decoder == null) { fallback = this.DecoderFallback as DecoderReplacementFallback; bUseBestFit = this.DecoderFallback.IsMicrosoftBestFitFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback; Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Might need one of these later DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; char c; c = mapBytesToUnicode[*bytes]; bytes++; // If unknown we have to do fallback count if (c == UNKNOWN_CHAR) { // Must have a fallback buffer if (fallbackBuffer == null) { // Need to adjust count so we get real start if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = *(bytes - 1); charCount--; // We'd already reserved one for *(bytes-1) charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end"); // Converted sequence is same length as input return charCount; } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); // See if we have best fit bool bUseBestFit = false; // Do it fast way if using ? replacement or best fit fallbacks byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback fallback = null; if (decoder == null) { fallback = this.DecoderFallback as DecoderReplacementFallback; bUseBestFit = this.DecoderFallback.IsMicrosoftBestFitFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback; Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) { // Try it the fast way char replacementChar; if (fallback == null) replacementChar = '?'; // Best fit alwasy has ? for fallback for SBCS else replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { char c; if (bUseBestFit) { if (arrayBytesBestFit == null) { ReadBestFitTable(); } c = arrayBytesBestFit[*bytes]; } else c = mapBytesToUnicode[*bytes]; bytes++; if (c == UNKNOWN_CHAR) // This is an invalid byte in the ASCII encoding. *chars = replacementChar; else *chars = c; chars++; } // bytes & chars used are the same if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; char c = mapBytesToUnicode[*bytes]; bytes++; // See if it was unknown if (c == UNKNOWN_CHAR) { // Make sure we have a fallback buffer if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer Contract.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)"); byteBuffer[0] = *(bytes - 1); // Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits. if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get this byte bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Contract.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)"); bytes--; // unused byte ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } *(chars) = c; chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } [System.Runtime.InteropServices.ComVisible(false)] public override bool IsAlwaysNormalized(NormalizationForm form) { // Most of these code pages could be decomposed or have compatibility mappings for KC, KD, & D // additionally the allow unassigned forms and IDNA wouldn't work either, so C is our choice. if (form == NormalizationForm.FormC) { // Form C is only true for some code pages. They have to have all 256 code points assigned // and not map to unassigned or combinable code points. switch (CodePage) { // Return true for some code pages. case 1252: // (Latin I - ANSI) case 1250: // (Eastern Europe - ANSI) case 1251: // (Cyrillic - ANSI) case 1254: // (Turkish - ANSI) case 1256: // (Arabic - ANSI) case 28591: // (ISO 8859-1 Latin I) case 437: // (United States - OEM) case 737: // (Greek (aka 437G) - OEM) case 775: // (Baltic - OEM) case 850: // (Multilingual (Latin I) - OEM) case 852: // (Slovak (Latin II) - OEM) case 855: // (Cyrillic - OEM) case 858: // (Multilingual (Latin I) - OEM + Euro) case 860: // (Portuguese - OEM) case 861: // (Icelandic - OEM) case 862: // (Hebrew - OEM) case 863: // (Canadian French - OEM) case 865: // (Nordic - OEM) case 866: // (Russian - OEM) case 869: // (Modern Greek - OEM) case 10007: // (Cyrillic - MAC) case 10017: // (Ukraine - MAC) case 10029: // (Latin II - MAC) case 28592: // (ISO 8859-2 Eastern Europe) case 28594: // (ISO 8859-4 Baltic) case 28595: // (ISO 8859-5 Cyrillic) case 28599: // (ISO 8859-9 Latin Alphabet No.5) case 28603: // (ISO/IEC 8859-13:1998 (Lithuanian)) case 28605: // (ISO 8859-15 Latin 9 (IBM923=IBM819+Euro)) case 037: // (IBM EBCDIC U.S./Canada) case 500: // (IBM EBCDIC International) case 870: // (IBM EBCDIC Latin-2 Multilingual/ROECE) case 1026: // (IBM EBCDIC Latin-5 Turkey) case 1047: // (IBM Latin-1/Open System) case 1140: // (IBM EBCDIC U.S./Canada (037+Euro)) case 1141: // (IBM EBCDIC Germany (20273(IBM273)+Euro)) case 1142: // (IBM EBCDIC Denmark/Norway (20277(IBM277+Euro)) case 1143: // (IBM EBCDIC Finland/Sweden (20278(IBM278)+Euro)) case 1144: // (IBM EBCDIC Italy (20280(IBM280)+Euro)) case 1145: // (IBM EBCDIC Latin America/Spain (20284(IBM284)+Euro)) case 1146: // (IBM EBCDIC United Kingdom (20285(IBM285)+Euro)) case 1147: // (IBM EBCDIC France (20297(IBM297+Euro)) case 1148: // (IBM EBCDIC International (500+Euro)) case 1149: // (IBM EBCDIC Icelandic (20871(IBM871+Euro)) case 20273: // (IBM EBCDIC Germany) case 20277: // (IBM EBCDIC Denmark/Norway) case 20278: // (IBM EBCDIC Finland/Sweden) case 20280: // (IBM EBCDIC Italy) case 20284: // (IBM EBCDIC Latin America/Spain) case 20285: // (IBM EBCDIC United Kingdom) case 20297: // (IBM EBCDIC France) case 20871: // (IBM EBCDIC Icelandic) case 20880: // (IBM EBCDIC Cyrillic) case 20924: // (IBM Latin-1/Open System (IBM924=IBM1047+Euro)) case 21025: // (IBM EBCDIC Cyrillic (Serbian, Bulgarian)) case 720: // (Arabic - Transparent ASMO) case 20866: // (Russian - KOI8) case 21866: // (Ukrainian - KOI8-U) return true; } } // False for IDNA and unknown return false; } } } #endif // FEATURE_CODEPAGES_FILE
// 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.InteropServices; using System.Globalization; using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.ComponentModel; using System.Security.Principal; using System.Security.Authentication.ExtendedProtection; using System.Security; using System.Collections; using System.Diagnostics; using Microsoft.Win32.SafeHandles; using System.Security.Authentication; namespace System.Net { // For Authentication (Kerberos, NTLM, Negotiate and WDigest): internal class SSPIAuthType: SSPIInterfaceNego { public void VerifyPackageInfo() { throw new NotImplementedException(); } public int AcquireCredentialsHandle(string moduleName, bool IsInBoundCred, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { Interop.Secur32.CredentialUse intent = IsInBoundCred ? Interop.Secur32.CredentialUse.Inbound : Interop.Secur32.CredentialUse.Outbound; return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, intent, ref authdata, out outCredential); } public int AcquireDefaultCredential(string moduleName, bool IsInBoundCred, out SafeFreeCredentials outCredential) { Interop.Secur32.CredentialUse intent = IsInBoundCred ? Interop.Secur32.CredentialUse.Inbound : Interop.Secur32.CredentialUse.Outbound; return SafeFreeCredentials.AcquireDefaultCredential(moduleName, intent, out outCredential); } public int AcquireCredentialsHandle(string moduleName, bool IsInBoundCred, ref Interop.Secur32.SecureCredential authdata, out SafeFreeCredentials outCredential) { Interop.Secur32.CredentialUse intent = IsInBoundCred ? Interop.Secur32.CredentialUse.Inbound : Interop.Secur32.CredentialUse.Outbound; return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, intent, ref authdata, out outCredential); } public int AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired) { Interop.Secur32.ContextFlags outFlags = Interop.Secur32.ContextFlags.Zero; return SafeDeleteContext.AcceptSecurityContext( ref credential, ref context, ServerRequiredFlags | (remoteCertRequired ? Interop.Secur32.ContextFlags.MutualAuth : Interop.Secur32.ContextFlags.Zero), Interop.Secur32.Endianness.Native, inputBuffer, null, outputBuffer, ref outFlags ); } public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int EncryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { int status = (int)Interop.SecurityStatus.InvalidHandle; bool ignore = false; context.DangerousAddRef(ref ignore); status = Interop.Secur32.EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber); context.DangerousRelease(); return status; } public unsafe int DecryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { int status = (int)Interop.SecurityStatus.InvalidHandle; uint qop = 0; try { bool ignore = false; context.DangerousAddRef(ref ignore); status = Interop.Secur32.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); } finally { context.DangerousRelease(); } const uint SECQOP_WRAP_NO_ENCRYPT = 0x80000001; if (status == 0 && qop == SECQOP_WRAP_NO_ENCRYPT) { GlobalLog.Assert("Secur32.DecryptMessage", "Expected qop = 0, returned value = " + qop.ToString("x", CultureInfo.InvariantCulture)); throw new InvalidOperationException(SR.net_auth_message_not_encrypted); } return status; } public int MakeSignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.Secur32.EncryptMessage(ref context._handle, Interop.Secur32.SECQOP_WRAP_NO_ENCRYPT, inputOutput, sequenceNumber); } finally { context.DangerousRelease(); } } public Interop.SecurityStatus VerifySignature(SafeDeleteContext securityContext, byte[] payload, uint sequenceNumber) { try { bool ignore = false; uint qop = 0; context.DangerousAddRef(ref ignore); return Interop.Secur32.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); } finally { context.DangerousRelease(); } } public int QueryContextChannelBinding(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding binding) { // Querying an auth SSP for a CBT doesn't make sense binding = null; throw new NotSupportedException(); } public unsafe int QueryContextAttributes(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, byte[] buffer, Type handleType, out SafeHandle refHandle) { refHandle = null; if (handleType != null) { if (handleType == typeof(SafeFreeContextBuffer)) { refHandle = SafeFreeContextBuffer.CreateEmptyHandle(); } else if (handleType == typeof(SafeFreeCertContext)) { refHandle = new SafeFreeCertContext(); } else { throw new ArgumentException(SR.Format(SR.SSPIInvalidHandleType, handleType.FullName), "handleType"); } } fixed (byte* bufferPtr = buffer) { return SafeFreeContextBuffer.QueryContextAttributes(context, attribute, bufferPtr, refHandle); } } public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken) { return GetSecurityContextToken(phContext, out phToken); } public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) { return SafeDeleteContext.CompleteAuthToken(ref refContext, inputBuffers); } private static int GetSecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle safeHandle) { int status = (int)Interop.SecurityStatus.InvalidHandle; safeHandle = null; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.Secur32.QuerySecurityContextToken(ref phContext._handle, out safeHandle); } finally { phContext.DangerousRelease(); } return status; } } }
// 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. #if ARM #define _TARGET_ARM_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define FEATURE_HFA #elif ARM64 #define _TARGET_ARM64_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #define FEATURE_HFA #elif X86 #define _TARGET_X86_ #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLINGCONVENTION_CALLEE_POPS #elif AMD64 #if UNIXAMD64 #define UNIX_AMD64_ABI #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #else #endif #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define _TARGET_AMD64_ #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #else #error Unknown architecture! #endif using System; using System.Collections.Generic; using System.Diagnostics; using Internal.Runtime.Augments; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime; using Internal.Runtime.CompilerServices; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.Runtime.CallConverter; using ArgIterator = Internal.Runtime.CallConverter.ArgIterator; namespace Internal.Runtime.TypeLoader { public class CallConverterThunk { private static LowLevelList<IntPtr> s_allocatedThunks = new LowLevelList<IntPtr>(); private static object s_thunkPoolHeap; internal static IntPtr CommonInputThunkStub = IntPtr.Zero; #if CALLDESCR_FPARGREGSARERETURNREGS #else #if _TARGET_X86_ internal static IntPtr ReturnFloatingPointReturn4Thunk = IntPtr.Zero; internal static IntPtr ReturnFloatingPointReturn8Thunk = IntPtr.Zero; #endif #endif internal static IntPtr ReturnVoidReturnThunk = IntPtr.Zero; internal static IntPtr ReturnIntegerPointReturnThunk = IntPtr.Zero; #if _TARGET_X86_ // Correctness of using this data structure relies on thread static structs being allocated in a location which cannot be moved by the GC [ThreadStatic] internal static ReturnBlock t_NonArgRegisterReturnSpace; #endif // CallingConventionConverter_CommonCallingStub indirection information structure // This is filled in during the class constructor for this type, and holds data // that is constant across all uses of the call conversion thunks. A pointer to // this is passed to each invocation of the common calling stub. internal struct CallingConventionConverter_CommonCallingStub_PointerData { public IntPtr ManagedCallConverterThunk; public IntPtr UniversalThunk; } // Wrapper class used for reference type parameters passed byref in dynamic invoker thunks internal class DynamicInvokeByRefArgObjectWrapper { internal object _object; } internal static CallingConventionConverter_CommonCallingStub_PointerData s_commonStubData; [DllImport("*", ExactSpelling = true, EntryPoint = "CallingConventionConverter_GetStubs")] private extern static unsafe void CallingConventionConverter_GetStubs(out IntPtr returnVoidStub, out IntPtr returnIntegerStub, out IntPtr commonStub #if CALLDESCR_FPARGREGSARERETURNREGS #else , out IntPtr returnFloatingPointReturn4Thunk, out IntPtr returnFloatingPointReturn8Thunk #endif ); #if _TARGET_ARM_ [DllImport("*", ExactSpelling = true, EntryPoint = "CallingConventionConverter_SpecifyCommonStubData")] private extern static unsafe void CallingConventionConverter_SpecifyCommonStubData(IntPtr commonStubData); #endif static unsafe CallConverterThunk() { CallingConventionConverter_GetStubs(out ReturnVoidReturnThunk, out ReturnIntegerPointReturnThunk, out CommonInputThunkStub #if CALLDESCR_FPARGREGSARERETURNREGS #else , out ReturnFloatingPointReturn4Thunk, out ReturnFloatingPointReturn8Thunk #endif ); s_commonStubData.ManagedCallConverterThunk = Intrinsics.AddrOf<Func<IntPtr, IntPtr, IntPtr>>(CallConversionThunk); s_commonStubData.UniversalThunk = RuntimeAugments.GetUniversalTransitionThunk(); #if _TARGET_ARM_ fixed (CallingConventionConverter_CommonCallingStub_PointerData* commonStubData = &s_commonStubData) { CallingConventionConverter_SpecifyCommonStubData((IntPtr)commonStubData); } #endif } internal static bool GetByRefIndicatorAtIndex(int index, bool[] lookup) { if (lookup == null) return false; if (index < lookup.Length) return lookup[index]; return false; } public enum ThunkKind { StandardToStandardInstantiating, StandardToGenericInstantiating, StandardToGenericInstantiatingIfNotHasThis, StandardToGeneric, StandardToGenericPassthruInstantiating, StandardToGenericPassthruInstantiatingIfNotHasThis, GenericToStandard, StandardUnboxing, StandardUnboxingAndInstantiatingGeneric, GenericToStandardWithTargetPointerArg, GenericToStandardWithTargetPointerArgAndParamArg, GenericToStandardWithTargetPointerArgAndMaybeParamArg, DelegateInvokeOpenStaticThunk, DelegateInvokeClosedStaticThunk, DelegateInvokeOpenInstanceThunk, DelegateInvokeInstanceClosedOverGenericMethodThunk, DelegateMulticastThunk, DelegateObjectArrayThunk, DelegateDynamicInvokeThunk, ReflectionDynamicInvokeThunk, } // WARNING: These constants are also declared in System.Private.CoreLib\src\System\Delegate.cs // Do not change their values unless you change the values decalred in Delegate.cs private const int MulticastThunk = 0; private const int ClosedStaticThunk = 1; private const int OpenStaticThunk = 2; private const int ClosedInstanceThunkOverGenericMethod = 3; private const int DelegateInvokeThunk = 4; private const int OpenInstanceThunk = 5; private const int ReversePinvokeThunk = 6; private const int ObjectArrayThunk = 7; public static unsafe IntPtr MakeThunk(ThunkKind thunkKind, IntPtr targetPointer, IntPtr instantiatingArg, bool hasThis, RuntimeTypeHandle[] parameters, bool[] byRefParameters, bool[] paramsByRefForced) { // Build thunk data TypeHandle thReturnType = new TypeHandle(GetByRefIndicatorAtIndex(0, byRefParameters), parameters[0]); TypeHandle[] thParameters = null; if (parameters.Length > 1) { thParameters = new TypeHandle[parameters.Length - 1]; for (int i = 1; i < parameters.Length; i++) { thParameters[i - 1] = new TypeHandle(GetByRefIndicatorAtIndex(i, byRefParameters), parameters[i]); } } int callConversionInfo = CallConversionInfo.RegisterCallConversionInfo(thunkKind, targetPointer, instantiatingArg, hasThis, thReturnType, thParameters, paramsByRefForced); return FindExistingOrAllocateThunk(callConversionInfo); } public static unsafe IntPtr MakeThunk(ThunkKind thunkKind, IntPtr targetPointer, RuntimeSignature methodSignature, IntPtr instantiatingArg, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs) { int callConversionInfo = CallConversionInfo.RegisterCallConversionInfo(thunkKind, targetPointer, methodSignature, instantiatingArg, typeArgs, methodArgs); return FindExistingOrAllocateThunk(callConversionInfo); } internal static unsafe IntPtr MakeThunk(ThunkKind thunkKind, IntPtr targetPointer, IntPtr instantiatingArg, ArgIteratorData argIteratorData, bool[] paramsByRefForced) { int callConversionInfo = CallConversionInfo.RegisterCallConversionInfo(thunkKind, targetPointer, instantiatingArg, argIteratorData, paramsByRefForced); return FindExistingOrAllocateThunk(callConversionInfo); } private static unsafe IntPtr FindExistingOrAllocateThunk(int callConversionInfo) { IntPtr thunk = IntPtr.Zero; lock (s_allocatedThunks) { if (callConversionInfo < s_allocatedThunks.Count && s_allocatedThunks[callConversionInfo] != IntPtr.Zero) return s_allocatedThunks[callConversionInfo]; if (s_thunkPoolHeap == null) { s_thunkPoolHeap = RuntimeAugments.CreateThunksHeap(CommonInputThunkStub); Debug.Assert(s_thunkPoolHeap != null); } thunk = RuntimeAugments.AllocateThunk(s_thunkPoolHeap); Debug.Assert(thunk != IntPtr.Zero); fixed (CallingConventionConverter_CommonCallingStub_PointerData* commonStubData = &s_commonStubData) { RuntimeAugments.SetThunkData(s_thunkPoolHeap, thunk, new IntPtr(callConversionInfo), new IntPtr(commonStubData)); if (callConversionInfo >= s_allocatedThunks.Count) { s_allocatedThunks.Expand(count: callConversionInfo + 1); } Debug.Assert(s_allocatedThunks[callConversionInfo] == IntPtr.Zero); s_allocatedThunks[callConversionInfo] = thunk; } } return thunk; } public static unsafe IntPtr GetDelegateThunk(Delegate delegateObject, int thunkKind) { if (thunkKind == ReversePinvokeThunk) { // Special unsupported thunk kind. Similar behavior to the thunks generated by the delegate ILTransform for this thunk kind RuntimeTypeHandle thDummy; bool isOpenResolverDummy; Action throwNotSupportedException = () => { throw new NotSupportedException(); }; return RuntimeAugments.GetDelegateLdFtnResult(throwNotSupportedException, out thDummy, out isOpenResolverDummy); } RuntimeTypeHandle delegateType = RuntimeAugments.GetRuntimeTypeHandleFromObjectReference(delegateObject); Debug.Assert(RuntimeAugments.IsGenericType(delegateType)); RuntimeTypeHandle[] typeArgs; RuntimeTypeHandle genericTypeDefHandle; genericTypeDefHandle = RuntimeAugments.GetGenericInstantiation(delegateType, out typeArgs); Debug.Assert(typeArgs != null && typeArgs.Length > 0); RuntimeSignature invokeMethodSignature; bool gotInvokeMethodSignature = TypeBuilder.TryGetDelegateInvokeMethodSignature(delegateType, out invokeMethodSignature); if (!gotInvokeMethodSignature) { Environment.FailFast("Unable to compute delegate invoke signature"); } switch (thunkKind) { case DelegateInvokeThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateDynamicInvokeThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case ObjectArrayThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateObjectArrayThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case MulticastThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateMulticastThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case OpenInstanceThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeOpenInstanceThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case ClosedInstanceThunkOverGenericMethod: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeInstanceClosedOverGenericMethodThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case ClosedStaticThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeClosedStaticThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case OpenStaticThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeOpenStaticThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); default: Environment.FailFast("Invalid delegate thunk kind"); return IntPtr.Zero; } } public static unsafe bool TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(IntPtr potentialStub, RuntimeTypeHandle exactType, out IntPtr nonUnboxingMethod) { IntPtr callConversionId; IntPtr commonStubDataPtr; if (!RuntimeAugments.TryGetThunkData(s_thunkPoolHeap, potentialStub, out callConversionId, out commonStubDataPtr)) { // This isn't a call conversion stub nonUnboxingMethod = IntPtr.Zero; return false; } CallConversionInfo conversionInfo = CallConversionInfo.GetConverter(callConversionId.ToInt32()); if (conversionInfo.IsUnboxingThunk) { // In this case the call converter is serving as an unboxing/instantiating stub // This case is not yet handled, and we don't need support for it yet. throw NotImplemented.ByDesign; } IntPtr underlyingTargetMethod; IntPtr newInstantiatingArg; if (conversionInfo.CalleeHasParamType) { // In this case the call converter is an instantiating stub wrapping an unboxing thunk. // Use the redhawk GetCodeTarget to see through the unboxing stub and get the real underlying method // and the instantiation arg does not need changing. underlyingTargetMethod = RuntimeAugments.GetCodeTarget(conversionInfo.TargetFunctionPointer); newInstantiatingArg = conversionInfo.InstantiatingStubArgument; } else { // At this point we've got a standard to generic converter wrapping an unboxing and instantiating // stub. We need to convert that into a fat function pointer directly calling the underlying method // or a calling convention converter instantiating stub wrapping the underlying method IntPtr underlyingUnboxingAndInstantiatingMethod = RuntimeAugments.GetCodeTarget(conversionInfo.TargetFunctionPointer); if (!TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(underlyingUnboxingAndInstantiatingMethod, out underlyingTargetMethod)) { // We aren't wrapping an unboxing and instantiating stub. This should never happen throw new NotSupportedException(); } newInstantiatingArg = exactType.ToIntPtr(); } Debug.Assert(conversionInfo.CallerForcedByRefData == null); bool canUseFatFunctionPointerInsteadOfThunk = true; if (conversionInfo.CalleeForcedByRefData != null) { foreach (bool forcedByRef in conversionInfo.CalleeForcedByRefData) { if (forcedByRef) { canUseFatFunctionPointerInsteadOfThunk = false; break; } } } if (canUseFatFunctionPointerInsteadOfThunk) { nonUnboxingMethod = FunctionPointerOps.GetGenericMethodFunctionPointer(underlyingTargetMethod, newInstantiatingArg); return true; } else { // Construct a new StandardToGenericInstantiating thunk around the underlyingTargetMethod nonUnboxingMethod = MakeThunk(ThunkKind.StandardToGenericInstantiating, underlyingTargetMethod, newInstantiatingArg, conversionInfo.ArgIteratorData, conversionInfo.CalleeForcedByRefData); return true; } } // This struct shares a layout with CallDescrData in the MRT codebase. internal unsafe struct CallDescrData { // // Input arguments // public void* pSrc; public int numStackSlots; public uint fpReturnSize; // Both of the following pointers are always present to reduce the spread of ifdefs in the C++ and ASM definitions of the struct public ArgumentRegisters* pArgumentRegisters; // Not used by AMD64 public FloatArgumentRegisters* pFloatArgumentRegisters; // Not used by X86 public void* pTarget; // // Return value // public void* pReturnBuffer; } // This function fills a piece of memory in a GC safe way. It makes the guarantee // that it will fill memory in at least pointer sized chunks whenever possible. // Unaligned memory at the beginning and remaining bytes at the end are written bytewise. // We must make this guarantee whenever we clear memory in the GC heap that could contain // object references. The GC or other user threads can read object references at any time, // clearing them bytewise can result in a read on another thread getting incorrect data. unsafe internal static void gcSafeMemzeroPointer(byte* pointer, int size) { byte* memBytes = pointer; byte* endBytes = (pointer + size); // handle unaligned bytes at the beginning while (!ArgIterator.IS_ALIGNED(new IntPtr(memBytes), (int)IntPtr.Size) && (memBytes < endBytes)) *memBytes++ = (byte)0; // now write pointer sized pieces long nPtrs = (endBytes - memBytes) / IntPtr.Size; IntPtr* memPtr = (IntPtr*)memBytes; for (int i = 0; i < nPtrs; i++) *memPtr++ = IntPtr.Zero; // handle remaining bytes at the end memBytes = (byte*)memPtr; while (memBytes < endBytes) *memBytes++ = (byte)0; } unsafe internal static void memzeroPointer(byte* pointer, int size) { for (int i = 0; i < size; i++) pointer[i] = 0; } unsafe internal static void memzeroPointerAligned(byte* pointer, int size) { size = ArgIterator.ALIGN_UP(size, IntPtr.Size); size /= IntPtr.Size; for (int i = 0; i < size; i++) { ((IntPtr*)pointer)[i] = IntPtr.Zero; } } unsafe private static bool isPointerAligned(void* pointer) { if (sizeof(IntPtr) == 4) { return ((int)pointer & 3) == 0; } Debug.Assert(sizeof(IntPtr) == 8); return ((long)pointer & 7) == 0; } #if CCCONVERTER_TRACE private static int s_numConversionsExecuted = 0; #endif private unsafe delegate void InvokeTargetDel(void* allocatedbuffer, ref CallConversionParameters conversionParams); [DebuggerGuidedStepThroughAttribute] unsafe private static IntPtr CallConversionThunk(IntPtr callerTransitionBlockParam, IntPtr callConversionId) { CallConversionParameters conversionParams = default(CallConversionParameters); try { conversionParams = new CallConversionParameters(CallConversionInfo.GetConverter(callConversionId.ToInt32()), callerTransitionBlockParam); #if CCCONVERTER_TRACE System.Threading.Interlocked.Increment(ref s_numConversionsExecuted); CallingConventionConverterLogger.WriteLine("CallConversionThunk executing... COUNT = " + s_numConversionsExecuted.LowLevelToString()); CallingConventionConverterLogger.WriteLine("Executing thunk of type " + conversionParams._conversionInfo.ThunkKindString() + ": "); #endif if (conversionParams._conversionInfo.IsMulticastDelegate) { MulticastDelegateInvoke(ref conversionParams); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } else { // Create a transition block on the stack. // Note that SizeOfFrameArgumentArray does overflow checks with sufficient margin to prevent overflows here int nStackBytes = conversionParams._calleeArgs.SizeOfFrameArgumentArray(); int dwAllocaSize = TransitionBlock.GetNegSpaceSize() + sizeof(TransitionBlock) + nStackBytes; IntPtr invokeTargetPtr = Intrinsics.AddrOf((InvokeTargetDel)InvokeTarget); RuntimeAugments.RunFunctionWithConservativelyReportedBuffer(dwAllocaSize, invokeTargetPtr, ref conversionParams); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } return conversionParams._invokeReturnValue; } finally { conversionParams.ResetPinnedObjects(); } } [DebuggerGuidedStepThroughAttribute] unsafe private static IntPtr MulticastDelegateInvoke(ref CallConversionParameters conversionParams) { // Create a transition block on the stack. // Note that SizeOfFrameArgumentArray does overflow checks with sufficient margin to prevent overflows here int nStackBytes = conversionParams._calleeArgs.SizeOfFrameArgumentArray(); int dwAllocaSize = TransitionBlock.GetNegSpaceSize() + sizeof(TransitionBlock) + nStackBytes; IntPtr invokeTargetPtr = Intrinsics.AddrOf((InvokeTargetDel)InvokeTarget); for (int i = 0; i < conversionParams.MulticastDelegateCallCount; i++) { conversionParams.PrepareNextMulticastDelegateCall(i); conversionParams._copyReturnValue = (i == (conversionParams.MulticastDelegateCallCount - 1)); RuntimeAugments.RunFunctionWithConservativelyReportedBuffer(dwAllocaSize, invokeTargetPtr, ref conversionParams); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } return conversionParams._invokeReturnValue; } [DebuggerGuidedStepThroughAttribute] unsafe private static void InvokeTarget(void* allocatedStackBuffer, ref CallConversionParameters conversionParams) { byte* callerTransitionBlock = conversionParams._callerTransitionBlock; byte* calleeTransitionBlock = ((byte*)allocatedStackBuffer) + TransitionBlock.GetNegSpaceSize(); // // Setup some of the special parameters on the output transition block // void* thisPointer = conversionParams.ThisPointer; void* callerRetBuffer = conversionParams.CallerReturnBuffer; void* VASigCookie = conversionParams.VarArgSigCookie; void* instantiatingStubArgument = (void*)conversionParams.InstantiatingStubArgument; { Debug.Assert((thisPointer != null && conversionParams._calleeArgs.HasThis()) || (thisPointer == null && !conversionParams._calleeArgs.HasThis())); if (thisPointer != null) { *((void**)(calleeTransitionBlock + ArgIterator.GetThisOffset())) = thisPointer; } Debug.Assert((callerRetBuffer != null && conversionParams._calleeArgs.HasRetBuffArg()) || (callerRetBuffer == null && !conversionParams._calleeArgs.HasRetBuffArg())); if (callerRetBuffer != null) { *((void**)(calleeTransitionBlock + conversionParams._calleeArgs.GetRetBuffArgOffset())) = callerRetBuffer; } Debug.Assert((VASigCookie != null && conversionParams._calleeArgs.IsVarArg()) || (VASigCookie == null && !conversionParams._calleeArgs.IsVarArg())); if (VASigCookie != null) { *((void**)(calleeTransitionBlock + conversionParams._calleeArgs.GetVASigCookieOffset())) = VASigCookie; } Debug.Assert((instantiatingStubArgument != null && conversionParams._calleeArgs.HasParamType()) || (instantiatingStubArgument == null && !conversionParams._calleeArgs.HasParamType())); if (instantiatingStubArgument != null) { *((void**)(calleeTransitionBlock + conversionParams._calleeArgs.GetParamTypeArgOffset())) = instantiatingStubArgument; } } #if CCCONVERTER_TRACE if (thisPointer != null) CallingConventionConverterLogger.WriteLine(" ThisPtr = " + new IntPtr(thisPointer).LowLevelToString()); if (callerRetBuffer != null) CallingConventionConverterLogger.WriteLine(" RetBuf = " + new IntPtr(callerRetBuffer).LowLevelToString()); if (VASigCookie != null) CallingConventionConverterLogger.WriteLine(" VASig = " + new IntPtr(VASigCookie).LowLevelToString()); if (instantiatingStubArgument != null) CallingConventionConverterLogger.WriteLine(" InstArg = " + new IntPtr(instantiatingStubArgument).LowLevelToString()); #endif object[] argumentsAsObjectArray = null; IntPtr pinnedResultObject = IntPtr.Zero; CallDescrData callDescrData = default(CallDescrData); IntPtr functionPointerToCall = conversionParams.FunctionPointerToCall; // // Setup the rest of the parameters on the ouput transition block by copying them from the input transition block // int ofsCallee; int ofsCaller; TypeHandle thDummy; TypeHandle thValueType; IntPtr argPtr; #if CALLDESCR_FPARGREGS FloatArgumentRegisters* pFloatArgumentRegisters = null; #endif { uint arg = 0; while (true) { // Setup argument offsets. ofsCallee = conversionParams._calleeArgs.GetNextOffset(); ofsCaller = int.MaxValue; // Check to see if we've handled all the arguments that we are to pass to the callee. if (TransitionBlock.InvalidOffset == ofsCallee) { if (!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) ofsCaller = conversionParams._callerArgs.GetNextOffset(); break; } #if CALLDESCR_FPARGREGS // Under CALLDESCR_FPARGREGS -ve offsets indicate arguments in floating point registers. If we // have at least one such argument we point the call worker at the floating point area of the // frame (we leave it null otherwise since the worker can perform a useful optimization if it // knows no floating point registers need to be set up). if ((ofsCallee < 0) && (pFloatArgumentRegisters == null)) pFloatArgumentRegisters = (FloatArgumentRegisters*)(calleeTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters()); #endif byte* pDest = calleeTransitionBlock + ofsCallee; byte* pSrc = null; int stackSizeCallee = int.MaxValue; int stackSizeCaller = int.MaxValue; bool isCalleeArgPassedByRef = false; bool isCallerArgPassedByRef = false; // // Compute size and pointer to caller's arg // { if (conversionParams._conversionInfo.IsClosedStaticDelegate) { if (arg == 0) { // Do not advance the caller's ArgIterator yet argPtr = conversionParams.ClosedStaticDelegateThisPointer; pSrc = (byte*)&argPtr; stackSizeCaller = IntPtr.Size; isCallerArgPassedByRef = false; } else { ofsCaller = conversionParams._callerArgs.GetNextOffset(); pSrc = callerTransitionBlock + ofsCaller; stackSizeCaller = conversionParams._callerArgs.GetArgSize(); isCallerArgPassedByRef = conversionParams._callerArgs.IsArgPassedByRef(); } stackSizeCallee = conversionParams._calleeArgs.GetArgSize(); isCalleeArgPassedByRef = conversionParams._calleeArgs.IsArgPassedByRef(); } else if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { // The caller's ArgIterator for delegate or reflection dynamic invoke thunks has a different (and special) signature than // the target method called by the delegate. We do not use it when setting up the callee's transition block. // Input arguments are not read from the caller's transition block, but form the dynamic invoke infrastructure. // Get all arguments info from the callee's ArgIterator instead. int index; InvokeUtils.DynamicInvokeParamLookupType paramLookupType; RuntimeTypeHandle argumentRuntimeTypeHandle; CorElementType argType = conversionParams._calleeArgs.GetArgType(out thValueType); if (argType == CorElementType.ELEMENT_TYPE_BYREF) { TypeHandle thByRefArgType; conversionParams._calleeArgs.GetByRefArgType(out thByRefArgType); Debug.Assert(!thByRefArgType.IsNull()); argumentRuntimeTypeHandle = thByRefArgType.GetRuntimeTypeHandle(); } else { argumentRuntimeTypeHandle = (thValueType.IsNull() ? typeof(object).TypeHandle : thValueType.GetRuntimeTypeHandle()); } object invokeParam = InvokeUtils.DynamicInvokeParamHelperCore( argumentRuntimeTypeHandle, out paramLookupType, out index, conversionParams._calleeArgs.IsArgPassedByRef() ? InvokeUtils.DynamicInvokeParamType.Ref : InvokeUtils.DynamicInvokeParamType.In); if (paramLookupType == InvokeUtils.DynamicInvokeParamLookupType.ValuetypeObjectReturned) { CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = invokeParam; argPtr = CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.GetRawTargetAddress() + IntPtr.Size; } else { Debug.Assert(paramLookupType == InvokeUtils.DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned); Debug.Assert((invokeParam is object[]) && index < ((object[])invokeParam).Length); CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = ((object[])invokeParam)[index]; pinnedResultObject = CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.GetRawTargetAddress(); if (conversionParams._calleeArgs.IsArgPassedByRef()) { // We need to keep track of the array of parameters used by the InvokeUtils infrastructure, so we can copy // back results of byref parameters conversionParams._dynamicInvokeParams = conversionParams._dynamicInvokeParams ?? (object[])invokeParam; // Use wrappers to pass objects byref (Wrappers can handle both null and non-null input byref parameters) conversionParams._dynamicInvokeByRefObjectArgs = conversionParams._dynamicInvokeByRefObjectArgs ?? new DynamicInvokeByRefArgObjectWrapper[conversionParams._dynamicInvokeParams.Length]; // The wrapper objects need to be pinned while we take the address of the byref'd object, and copy it to the callee // transition block (which is conservatively reported). Once the copy is done, we can safely unpin the wrapper object. if (pinnedResultObject == IntPtr.Zero) { // Input byref parameter has a null value conversionParams._dynamicInvokeByRefObjectArgs[index] = new DynamicInvokeByRefArgObjectWrapper(); } else { // Input byref parameter has a non-null value conversionParams._dynamicInvokeByRefObjectArgs[index] = new DynamicInvokeByRefArgObjectWrapper { _object = conversionParams._dynamicInvokeParams[index] }; } CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = conversionParams._dynamicInvokeByRefObjectArgs[index]; argPtr = CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.GetRawTargetAddress() + IntPtr.Size; } else { argPtr = new IntPtr(&pinnedResultObject); } } if (conversionParams._calleeArgs.IsArgPassedByRef()) { pSrc = (byte*)&argPtr; } else { pSrc = (byte*)argPtr; } stackSizeCaller = stackSizeCallee = conversionParams._calleeArgs.GetArgSize(); isCallerArgPassedByRef = isCalleeArgPassedByRef = conversionParams._calleeArgs.IsArgPassedByRef(); } else { ofsCaller = conversionParams._callerArgs.GetNextOffset(); pSrc = callerTransitionBlock + ofsCaller; stackSizeCallee = conversionParams._calleeArgs.GetArgSize(); stackSizeCaller = conversionParams._callerArgs.GetArgSize(); isCalleeArgPassedByRef = conversionParams._calleeArgs.IsArgPassedByRef(); isCallerArgPassedByRef = conversionParams._callerArgs.IsArgPassedByRef(); } } Debug.Assert(stackSizeCallee == stackSizeCaller); if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk) { // Box (if needed) and copy arguments to an object array instead of the callee's transition block argumentsAsObjectArray = argumentsAsObjectArray ?? new object[conversionParams._callerArgs.NumFixedArgs()]; conversionParams._callerArgs.GetArgType(out thValueType); if (thValueType.IsNull()) { Debug.Assert(!isCallerArgPassedByRef); Debug.Assert(conversionParams._callerArgs.GetArgSize() == IntPtr.Size); argumentsAsObjectArray[arg] = Unsafe.As<IntPtr, Object>(ref *(IntPtr*)pSrc); } else { if (isCallerArgPassedByRef) { argumentsAsObjectArray[arg] = RuntimeAugments.Box(thValueType.GetRuntimeTypeHandle(), new IntPtr(*((void**)pSrc))); } else { argumentsAsObjectArray[arg] = RuntimeAugments.Box(thValueType.GetRuntimeTypeHandle(), new IntPtr(pSrc)); } } } else { if (isCalleeArgPassedByRef == isCallerArgPassedByRef) { // Argument copies without adjusting calling convention. switch (stackSizeCallee) { case 1: case 2: case 4: *((int*)pDest) = *((int*)pSrc); break; case 8: *((long*)pDest) = *((long*)pSrc); break; default: if (isCalleeArgPassedByRef) { // even though this argument is passed by value, the actual calling convention // passes a pointer to the value of the argument. Debug.Assert(isCallerArgPassedByRef); // Copy the pointer from the incoming arguments to the outgoing arguments. *((void**)pDest) = *((void**)pSrc); } else { // In this case, the valuetype is passed directly on the stack, even though it is // a non-integral size. Buffer.MemoryCopy(pSrc, pDest, stackSizeCallee, stackSizeCallee); } break; } } else { // Calling convention adjustment. Used to handle conversion from universal shared generic form to standard // calling convention and vice versa if (isCalleeArgPassedByRef) { // Pass as the byref pointer a pointer to the position in the transition block of the input argument *((void**)pDest) = pSrc; } else { // Copy into the destination the data pointed at by the pointer in the source(caller) data. Buffer.MemoryCopy(*(byte**)pSrc, pDest, stackSizeCaller, stackSizeCaller); } } #if CCCONVERTER_TRACE CallingConventionConverterLogger.WriteLine(" Arg" + arg.LowLevelToString() + " " + (isCalleeArgPassedByRef ? "ref = " : " = ") + new IntPtr(*(void**)pDest).LowLevelToString() + " - RTTH = " + conversionParams._calleeArgs.GetEETypeDebugName((int)arg) + " - StackSize = " + stackSizeCallee.LowLevelToString()); #endif } if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { // The calleeTransitionBlock is GC-protected, so we can now safely unpin the return value of DynamicInvokeParamHelperCore, // since we just copied it to the callee TB. CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = null; } arg++; } } if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { IntPtr argSetupStatePtr = conversionParams.GetArgSetupStateDataPointer(); InvokeUtils.DynamicInvokeArgSetupPtrComplete(argSetupStatePtr); } uint fpReturnSize = conversionParams._calleeArgs.GetFPReturnSize(); if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk) { Debug.Assert(conversionParams._callerArgs.HasRetBuffArg() == conversionParams._calleeArgs.HasRetBuffArg()); pinnedResultObject = conversionParams.InvokeObjectArrayDelegate(argumentsAsObjectArray); } else { if ((TransitionBlock.InvalidOffset != ofsCaller) != conversionParams._conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget && !conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { // The condition on the loop above is only verifying that callee has reach the end of its arguments. // Here we check to see that caller has done so as well. Environment.FailFast("Argument mismatch between caller and callee"); } if (conversionParams._conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget && !conversionParams._conversionInfo.CalleeMayHaveParamType) { int stackSizeCaller = conversionParams._callerArgs.GetArgSize(); Debug.Assert(stackSizeCaller == IntPtr.Size); void* pSrc = callerTransitionBlock + ofsCaller; functionPointerToCall = *((IntPtr*)pSrc); ofsCaller = conversionParams._callerArgs.GetNextOffset(); if (TransitionBlock.InvalidOffset != ofsCaller) { Environment.FailFast("Argument mismatch between caller and callee"); } } callDescrData.pSrc = calleeTransitionBlock + sizeof(TransitionBlock); callDescrData.numStackSlots = conversionParams._calleeArgs.SizeOfFrameArgumentArray() / ArchitectureConstants.STACK_ELEM_SIZE; #if CALLDESCR_ARGREGS callDescrData.pArgumentRegisters = (ArgumentRegisters*)(calleeTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters()); #endif #if CALLDESCR_FPARGREGS callDescrData.pFloatArgumentRegisters = pFloatArgumentRegisters; #endif callDescrData.fpReturnSize = fpReturnSize; callDescrData.pTarget = (void*)functionPointerToCall; ReturnBlock returnBlockForIgnoredData = default(ReturnBlock); if (conversionParams._callerArgs.HasRetBuffArg() == conversionParams._calleeArgs.HasRetBuffArg()) { // If there is no return buffer explictly in use, return to a buffer which is conservatively reported // by the universal transition frame. // OR // If there IS a return buffer in use, the function doesn't really return anything in the normal // return value registers, but CallDescrThunk will always copy a pointer sized chunk into the // ret buf. Make that ok by giving it a valid location to stash bits. callDescrData.pReturnBuffer = (void*)(callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock()); } else if (conversionParams._calleeArgs.HasRetBuffArg()) { // This is the case when the caller doesn't have a return buffer argument, but the callee does. // In that case the return value captured by CallDescrWorker is ignored. // When CallDescrWorkerInternal is called, have it return values into a temporary unused buffer // In actuality its returning its return information into the return value block already, but that return buffer // was setup as a passed in argument instead of being filled in by the CallDescrWorker function directly. callDescrData.pReturnBuffer = (void*)&returnBlockForIgnoredData; } else { // If there is no return buffer explictly in use by the callee, return to a buffer which is conservatively reported // by the universal transition frame. // This is the case where HasRetBuffArg is false for the callee, but the caller has a return buffer. // In this case we need to capture the direct return value from callee into a buffer which may contain // a gc reference (or not), and then once the call is complete, copy the value into the return buffer // passed by the caller. (Do not directly use the return buffer provided by the caller, as CallDescrWorker // does not properly use a write barrier, and the actual return buffer provided may be on the GC heap.) callDescrData.pReturnBuffer = (void*)(callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock()); } ////////////////////////////////////////////////////////////// //// Call the Callee ////////////////////////////////////////////////////////////// RuntimeAugments.CallDescrWorker(new IntPtr(&callDescrData)); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } // For dynamic invoke thunks, we need to copy back values of reference type parameters that were passed byref if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk && conversionParams._dynamicInvokeParams != null) { for (int i = 0; i < conversionParams._dynamicInvokeParams.Length; i++) { if (conversionParams._dynamicInvokeByRefObjectArgs[i] == null) continue; object byrefObjectArgValue = conversionParams._dynamicInvokeByRefObjectArgs[i]._object; conversionParams._dynamicInvokeParams[i] = byrefObjectArgValue; } } if (!conversionParams._copyReturnValue) return; bool forceByRefUnused; CorElementType returnType; // Note that the caller's ArgIterator for delegate dynamic invoke thunks has a different (and special) signature than // the target method called by the delegate. Use the callee's ArgIterator instead to get the return type info if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { returnType = conversionParams._calleeArgs.GetReturnType(out thValueType, out forceByRefUnused); } else { returnType = conversionParams._callerArgs.GetReturnType(out thValueType, out forceByRefUnused); } int returnSize = TypeHandle.GetElemSize(returnType, thValueType); // Unbox result of object array delegate call if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk && !thValueType.IsNull() && pinnedResultObject != IntPtr.Zero) pinnedResultObject += IntPtr.Size; // Process return values if ((conversionParams._callerArgs.HasRetBuffArg() && !conversionParams._calleeArgs.HasRetBuffArg()) || (conversionParams._callerArgs.HasRetBuffArg() && conversionParams._conversionInfo.IsObjectArrayDelegateThunk)) { // We should never get here for dynamic invoke thunks Debug.Assert(!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk); // The CallDescrWorkerInternal function will have put the return value into the return buffer, as register return values are // extended to the size of a register, we can't just ask the CallDescrWorker to write directly into the return buffer. // Thus we copy only the correct amount of data here to the real target address byte* incomingRetBufPointer = *((byte**)(callerTransitionBlock + conversionParams._callerArgs.GetRetBuffArgOffset())); void* sourceBuffer = conversionParams._conversionInfo.IsObjectArrayDelegateThunk ? (void*)pinnedResultObject : callDescrData.pReturnBuffer; Debug.Assert(sourceBuffer != null || conversionParams._conversionInfo.IsObjectArrayDelegateThunk); if (sourceBuffer == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case gcSafeMemzeroPointer(incomingRetBufPointer, returnSize); } else { // Because we are copying into a caller provided buffer, we can't use a simple memory copy, we need to use a // gc protected copy as the actual return buffer may be on the heap. bool useGCSafeCopy = false; if ((returnType == CorElementType.ELEMENT_TYPE_CLASS) || !thValueType.IsNull()) { // The GC Safe copy assumes that memory pointers are pointer-aligned and copy length is a multiple of pointer-size if (isPointerAligned(incomingRetBufPointer) && isPointerAligned(sourceBuffer) && (returnSize % sizeof(IntPtr) == 0)) { useGCSafeCopy = true; } } if (useGCSafeCopy) { RuntimeAugments.BulkMoveWithWriteBarrier(new IntPtr(incomingRetBufPointer), new IntPtr(sourceBuffer), returnSize); } else { Buffer.MemoryCopy(sourceBuffer, incomingRetBufPointer, returnSize, returnSize); } } #if CALLINGCONVENTION_CALLEE_POPS // Don't setup the callee pop argument until after copying into the ret buff. We may be using the location // of the callee pop argument to keep track of the ret buff location SetupCallerPopArgument(callerTransitionBlock, conversionParams._callerArgs); #endif #if _TARGET_X86_ SetupCallerActualReturnData(callerTransitionBlock); // On X86 the return buffer pointer is returned in eax. t_NonArgRegisterReturnSpace.returnValue = new IntPtr(incomingRetBufPointer); conversionParams._invokeReturnValue = ReturnIntegerPointReturnThunk; return; #else // Because the return value was really returned on the heap, simply return as if void was returned. conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; #endif } else { #if CALLINGCONVENTION_CALLEE_POPS SetupCallerPopArgument(callerTransitionBlock, conversionParams._callerArgs); #endif // The CallDescrWorkerInternal function will have put the return value into the return buffer. // Here we copy the return buffer data into the argument registers for the return thunks. // // A return thunk takes an argument(by value) that is what is to be returned. // // The simplest case is the one where there is no return value bool dummyBool; if (conversionParams._callerArgs.GetReturnType(out thDummy, out dummyBool) == CorElementType.ELEMENT_TYPE_VOID) { conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; } // The second simplest case is when there is a return buffer argument for both the caller and callee // In that case, we simply treat this as if we are returning void #if _TARGET_X86_ // Except on X86 where the return buffer is returned in the eax register, and looks like an integer return #else if (conversionParams._callerArgs.HasRetBuffArg() && conversionParams._calleeArgs.HasRetBuffArg()) { Debug.Assert(!conversionParams._conversionInfo.IsObjectArrayDelegateThunk); Debug.Assert(!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk); conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; } #endif void* returnValueToCopy = (void*)(callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock()); if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk) { if (!thValueType.IsNull()) { returnValueToCopy = (void*)pinnedResultObject; #if _TARGET_X86_ Debug.Assert(returnSize <= sizeof(ReturnBlock)); if (returnValueToCopy == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case memzeroPointer((byte*)(&((TransitionBlock*)callerTransitionBlock)->m_returnBlock), returnSize); } else { if (isPointerAligned(&((TransitionBlock*)callerTransitionBlock)->m_returnBlock) && isPointerAligned(returnValueToCopy) && (returnSize % sizeof(IntPtr) == 0)) RuntimeAugments.BulkMoveWithWriteBarrier(new IntPtr(&((TransitionBlock*)callerTransitionBlock)->m_returnBlock), new IntPtr(returnValueToCopy), returnSize); else Buffer.MemoryCopy(returnValueToCopy, &((TransitionBlock*)callerTransitionBlock)->m_returnBlock, returnSize, returnSize); } #endif } else { returnValueToCopy = (void*)&pinnedResultObject; #if _TARGET_X86_ ((TransitionBlock*)callerTransitionBlock)->m_returnBlock.returnValue = pinnedResultObject; #endif } } else if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk && !thValueType.IsNull()) { Debug.Assert(returnValueToCopy != null); if (!conversionParams._callerArgs.HasRetBuffArg() && conversionParams._calleeArgs.HasRetBuffArg()) returnValueToCopy = (void*)(new IntPtr(*((void**)returnValueToCopy)) + IntPtr.Size); // Need to box value type before returning it object returnValue = RuntimeAugments.Box(thValueType.GetRuntimeTypeHandle(), new IntPtr(returnValueToCopy)); CallConversionParameters.s_pinnedGCHandles._returnObjectHandle.Target = returnValue; pinnedResultObject = CallConversionParameters.s_pinnedGCHandles._returnObjectHandle.GetRawTargetAddress(); returnValueToCopy = (void*)&pinnedResultObject; #if _TARGET_X86_ ((TransitionBlock*)callerTransitionBlock)->m_returnBlock.returnValue = pinnedResultObject; #endif } // Handle floating point returns // The previous fpReturnSize was the callee fpReturnSize. Now reset to the caller return size to handle // returning to the caller. fpReturnSize = conversionParams._callerArgs.GetFPReturnSize(); if (fpReturnSize != 0) { // We should never get here for delegate dynamic invoke thunks (the return type is always a boxed object) Debug.Assert(!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk); #if CALLDESCR_FPARGREGSARERETURNREGS Debug.Assert(fpReturnSize <= sizeof(FloatArgumentRegisters)); memzeroPointerAligned(calleeTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters(), sizeof(FloatArgumentRegisters)); if (returnValueToCopy == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case Debug.Assert(conversionParams._conversionInfo.IsObjectArrayDelegateThunk); memzeroPointer(callerTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters(), (int)fpReturnSize); } else { Buffer.MemoryCopy(returnValueToCopy, callerTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters(), (int)fpReturnSize, (int)fpReturnSize); } conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; #else #if CALLDESCR_FPARGREGS #error Case not yet handled #endif Debug.Assert(fpReturnSize <= sizeof(ArgumentRegisters)); #if _TARGET_X86_ SetupCallerActualReturnData(callerTransitionBlock); t_NonArgRegisterReturnSpace = ((TransitionBlock*)callerTransitionBlock)->m_returnBlock; #else #error Platform not implemented #endif if (fpReturnSize == 4) { conversionParams._invokeReturnValue = ReturnFloatingPointReturn4Thunk; } else { conversionParams._invokeReturnValue = ReturnFloatingPointReturn8Thunk; } return; #endif } #if _TARGET_X86_ SetupCallerActualReturnData(callerTransitionBlock); t_NonArgRegisterReturnSpace = ((TransitionBlock*)callerTransitionBlock)->m_returnBlock; conversionParams._invokeReturnValue = ReturnIntegerPointReturnThunk; return; #else // If we reach here, we are returning value in the integer registers. if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk && (!thValueType.IsNull())) { if (returnValueToCopy == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case memzeroPointer(callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters(), returnSize); } else { if (isPointerAligned(callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters()) && isPointerAligned(returnValueToCopy) && (returnSize % sizeof(IntPtr) == 0)) RuntimeAugments.BulkMoveWithWriteBarrier(new IntPtr(callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters()), new IntPtr(returnValueToCopy), returnSize); else Buffer.MemoryCopy(returnValueToCopy, callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters(), returnSize, returnSize); } } else { Debug.Assert(returnValueToCopy != null); Buffer.MemoryCopy(returnValueToCopy, callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters(), ArchitectureConstants.ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE, ArchitectureConstants.ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE); } conversionParams._invokeReturnValue = ReturnIntegerPointReturnThunk; #endif } } #if CALLINGCONVENTION_CALLEE_POPS private static unsafe void SetupCallerPopArgument(byte* callerTransitionBlock, ArgIterator callerArgs) { int argStackPopSize = callerArgs.CbStackPop(); #if _TARGET_X86_ // In a callee pops architecture, we must specify how much stack space to pop to reset the frame // to the ReturnValue thunk. ((TransitionBlock*)callerTransitionBlock)->m_argumentRegisters.ecx = new IntPtr(argStackPopSize); #else #error handling of how callee pop is handled is not yet implemented for this platform #endif } #endif #if _TARGET_X86_ unsafe internal static void SetupCallerActualReturnData(byte* callerTransitionBlock) { // X86 needs to pass callee pop information to the return value thunks, so, since it // only has 2 argument registers and may/may not need to return 8 bytes of data, put the return // data in a seperate thread local store passed in the other available register (edx) fixed (ReturnBlock* actualReturnDataStructAddress = &t_NonArgRegisterReturnSpace) { ((TransitionBlock*)callerTransitionBlock)->m_argumentRegisters.edx = new IntPtr(actualReturnDataStructAddress); } } #endif } internal static class CallingConventionConverterLogger { [Conditional("CCCONVERTER_TRACE")] public static void WriteLine(string message) { Debug.WriteLine(message); } } }
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Input; namespace Eft.Win32 { /// <summary> /// Provides methods for sending keyboard input /// </summary> public class Keyboard { /// <summary>The first X mouse button</summary> public const int XButton1 = 0x01; /// <summary>The second X mouse button</summary> public const int XButton2 = 0x02; /// <summary> /// Inject keyboard input into the system /// </summary> /// <param name="key">indicates the key pressed or released. Can be one of the constants defined in the Key enum</param> /// <param name="press">true to inject a key press, false to inject a key release</param> public static void SendKeyboardInput(Key key, bool press) { APIWrapper.INPUT ki = new APIWrapper.INPUT(); ki.type = APIWrapper.INPUT_KEYBOARD; ki.union.keyboardInput.wVk = (short) KeyInterop.VirtualKeyFromKey(key); ki.union.keyboardInput.wScan = (short) APIWrapper.MapVirtualKey(ki.union.keyboardInput.wVk, 0); int dwFlags = 0; if (ki.union.keyboardInput.wScan > 0) { dwFlags |= APIWrapper.KEYEVENTF_SCANCODE; } if (false == press) { dwFlags |= APIWrapper.KEYEVENTF_KEYUP; } ki.union.keyboardInput.dwFlags = dwFlags; if (IsExtendedKey(key)) { ki.union.keyboardInput.dwFlags |= APIWrapper.KEYEVENTF_EXTENDEDKEY; } ki.union.keyboardInput.time = 0; ki.union.keyboardInput.dwExtraInfo = new IntPtr(0); if (0 == APIWrapper.SendInput(1, ref ki, Marshal.SizeOf(ki))) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } /// <summary> /// Injects a unicode character as keyboard input into the system /// </summary> /// <param name="key">indicates the key to be pressed or released. Can be any unicode character</param> /// <param name="press">true to inject a key press, false to inject a key release</param> public static void SendUnicodeKeyboardInput(char key, bool press) { APIWrapper.INPUT ki = new APIWrapper.INPUT(); ki.type = APIWrapper.INPUT_KEYBOARD; ki.union.keyboardInput.wVk = 0; ki.union.keyboardInput.wScan = (short) key; ki.union.keyboardInput.dwFlags = APIWrapper.KEYEVENTF_UNICODE | (press ? 0 : APIWrapper.KEYEVENTF_KEYUP); ki.union.keyboardInput.time = 0; ki.union.keyboardInput.dwExtraInfo = new IntPtr(0); if (0 == APIWrapper.SendInput(1, ref ki, Marshal.SizeOf(ki))) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } /// <summary> /// Injects a string of Unicode characters using simulated keyboard input /// It should be noted that this overload just sends the whole string /// with no pauses, depending on the recieving applications input processing /// it may not be able to keep up with the speed, resulting in corruption or /// loss of the input data. /// </summary> /// <param name="data">The unicode string to be sent</param> public static void SendUnicodeString(string data) { InternalSendUnicodeString(data, -1, 0); } /// <summary> /// Injects a string of Unicode characters using simulated keyboard input /// with user defined timing. /// </summary> /// <param name="data">The unicode string to be sent</param> /// <param name="sleepFrequency">How many characters to send between sleep calls</param> /// <param name="sleepLength">How long, in milliseconds, to sleep for at each sleep call</param> public static void SendUnicodeString(string data, int sleepFrequency, int sleepLength) { if (sleepFrequency < 1) { throw new ArgumentOutOfRangeException("sleepFrequency"); } if (sleepLength < 0) { throw new ArgumentOutOfRangeException("sleepLength"); } InternalSendUnicodeString(data, sleepFrequency, sleepLength); } /// <summary> /// Checks whether the specified key is currently up or down /// </summary> /// <param name="key">The Key to check</param> /// <returns>true if the specified key is currently down (being pressed), false if it is up</returns> public static bool GetAsyncKeyState(Key key) { int vKey = KeyInterop.VirtualKeyFromKey(key); int resp = APIWrapper.GetAsyncKeyState(vKey); if (resp == 0) { throw new InvalidOperationException("GetAsyncKeyStateFailed"); } return resp < 0; } // Used internally by the HWND SetFocus code - it sends a hotkey to // itself - because it uses a VK that's not on the keyboard, it needs // to send the VK directly, not the scan code, which regular // SendKeyboardInput does. // Note that this method is public, but this class is private, so // this is not externally visible. internal static void SendKeyboardInputVK(byte vk, bool press) { APIWrapper.INPUT ki = new APIWrapper.INPUT(); ki.type = APIWrapper.INPUT_KEYBOARD; ki.union.keyboardInput.wVk = vk; ki.union.keyboardInput.wScan = 0; ki.union.keyboardInput.dwFlags = press ? 0 : APIWrapper.KEYEVENTF_KEYUP; ki.union.keyboardInput.time = 0; ki.union.keyboardInput.dwExtraInfo = new IntPtr(0); if (0 == APIWrapper.SendInput(1, ref ki, Marshal.SizeOf(ki))) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } internal static bool IsExtendedKey(Key key) { // From the SDK: // The extended-key flag indicates whether the keystroke message originated from one of // the additional keys on the enhanced keyboard. The extended keys consist of the ALT and // CTRL keys on the right-hand side of the keyboard; the INS, DEL, HOME, END, PAGE UP, // PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; the NUM LOCK // key; the BREAK (CTRL+PAUSE) key; the PRINT SCRN key; and the divide (/) and ENTER keys in // the numeric keypad. The extended-key flag is set if the key is an extended key. // // - docs appear to be incorrect. Use of Spy++ indicates that break is not an extended key. // Also, menu key and windows keys also appear to be extended. return key == Key.RightAlt || key == Key.RightCtrl || key == Key.NumLock || key == Key.Insert || key == Key.Delete || key == Key.Home || key == Key.End || key == Key.Prior || key == Key.Next || key == Key.Up || key == Key.Down || key == Key.Left || key == Key.Right || key == Key.Apps || key == Key.RWin || key == Key.LWin; // Note that there are no distinct values for the following keys: // numpad divide // numpad enter } // Injects a string of Unicode characters using simulated keyboard input // with user defined timing // <param name="data">The unicode string to be sent</param> // <param name="sleepFrequency">How many characters to send between sleep calls // A sleepFrequency of -1 means to never sleep</param> // <param name="sleepLength">How long, in milliseconds, to sleep for at each sleep call</param> private static void InternalSendUnicodeString(string data, int sleepFrequency, int sleepLength) { char[] chardata = data.ToCharArray(); int counter = -1; foreach (char c in chardata) { // Every sleepFrequency characters, sleep for sleepLength ms to avoid overflowing the input buffer. counter++; if (counter > sleepFrequency) { counter = 0; Thread.Sleep(sleepLength); } SendUnicodeKeyboardInput(c, true); SendUnicodeKeyboardInput(c, false); } } public static void Command(IntPtr wnd) { APIWrapper.PostMessage(APIWrapper.HWND.Cast(wnd), (int) WindowsMessages.WM_COMMAND, 0x0000e101, 0); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: A1021Response.txt #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace DolphinServer.ProtoEntity { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class A1021Response { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_A1021Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1021Response, global::DolphinServer.ProtoEntity.A1021Response.Builder> internal__static_A1021Response__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_A1021User__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1021User, global::DolphinServer.ProtoEntity.A1021User.Builder> internal__static_A1021User__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static A1021Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFBMTAyMVJlc3BvbnNlLnR4dCKqAQoNQTEwMjFSZXNwb25zZRIRCglFcnJv", "ckluZm8YASABKAkSEQoJRXJyb3JDb2RlGAIgASgFEhEKCU5pYW9DYXJkMRgE", "IAEoBRIRCglOaWFvQ2FyZDIYBSABKAUSEAoITmlhb1VpZDEYBiABKAkSEAoI", "Tmlhb1VpZDIYByABKAkSGQoFVXNlcnMYCCADKAsyCi5BMTAyMVVzZXISDgoG", "RGVzVWlkGAkgASgJIksKCUExMDIxVXNlchILCgNVaWQYASABKAkSDQoFU2Nv", "cmUYAiABKAUSEgoKVG90YWxTY29yZRgDIAEoBRIOCgZIdVR5cGUYBCABKAVC", "HKoCGURvbHBoaW5TZXJ2ZXIuUHJvdG9FbnRpdHk=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_A1021Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_A1021Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1021Response, global::DolphinServer.ProtoEntity.A1021Response.Builder>(internal__static_A1021Response__Descriptor, new string[] { "ErrorInfo", "ErrorCode", "NiaoCard1", "NiaoCard2", "NiaoUid1", "NiaoUid2", "Users", "DesUid", }); internal__static_A1021User__Descriptor = Descriptor.MessageTypes[1]; internal__static_A1021User__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1021User, global::DolphinServer.ProtoEntity.A1021User.Builder>(internal__static_A1021User__Descriptor, new string[] { "Uid", "Score", "TotalScore", "HuType", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1021Response : pb::GeneratedMessage<A1021Response, A1021Response.Builder> { private A1021Response() { } private static readonly A1021Response defaultInstance = new A1021Response().MakeReadOnly(); private static readonly string[] _a1021ResponseFieldNames = new string[] { "DesUid", "ErrorCode", "ErrorInfo", "NiaoCard1", "NiaoCard2", "NiaoUid1", "NiaoUid2", "Users" }; private static readonly uint[] _a1021ResponseFieldTags = new uint[] { 74, 16, 10, 32, 40, 50, 58, 66 }; public static A1021Response DefaultInstance { get { return defaultInstance; } } public override A1021Response DefaultInstanceForType { get { return DefaultInstance; } } protected override A1021Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1021Response.internal__static_A1021Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1021Response, A1021Response.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1021Response.internal__static_A1021Response__FieldAccessorTable; } } public const int ErrorInfoFieldNumber = 1; private bool hasErrorInfo; private string errorInfo_ = ""; public bool HasErrorInfo { get { return hasErrorInfo; } } public string ErrorInfo { get { return errorInfo_; } } public const int ErrorCodeFieldNumber = 2; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int NiaoCard1FieldNumber = 4; private bool hasNiaoCard1; private int niaoCard1_; public bool HasNiaoCard1 { get { return hasNiaoCard1; } } public int NiaoCard1 { get { return niaoCard1_; } } public const int NiaoCard2FieldNumber = 5; private bool hasNiaoCard2; private int niaoCard2_; public bool HasNiaoCard2 { get { return hasNiaoCard2; } } public int NiaoCard2 { get { return niaoCard2_; } } public const int NiaoUid1FieldNumber = 6; private bool hasNiaoUid1; private string niaoUid1_ = ""; public bool HasNiaoUid1 { get { return hasNiaoUid1; } } public string NiaoUid1 { get { return niaoUid1_; } } public const int NiaoUid2FieldNumber = 7; private bool hasNiaoUid2; private string niaoUid2_ = ""; public bool HasNiaoUid2 { get { return hasNiaoUid2; } } public string NiaoUid2 { get { return niaoUid2_; } } public const int UsersFieldNumber = 8; private pbc::PopsicleList<global::DolphinServer.ProtoEntity.A1021User> users_ = new pbc::PopsicleList<global::DolphinServer.ProtoEntity.A1021User>(); public scg::IList<global::DolphinServer.ProtoEntity.A1021User> UsersList { get { return users_; } } public int UsersCount { get { return users_.Count; } } public global::DolphinServer.ProtoEntity.A1021User GetUsers(int index) { return users_[index]; } public const int DesUidFieldNumber = 9; private bool hasDesUid; private string desUid_ = ""; public bool HasDesUid { get { return hasDesUid; } } public string DesUid { get { return desUid_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1021ResponseFieldNames; if (hasErrorInfo) { output.WriteString(1, field_names[2], ErrorInfo); } if (hasErrorCode) { output.WriteInt32(2, field_names[1], ErrorCode); } if (hasNiaoCard1) { output.WriteInt32(4, field_names[3], NiaoCard1); } if (hasNiaoCard2) { output.WriteInt32(5, field_names[4], NiaoCard2); } if (hasNiaoUid1) { output.WriteString(6, field_names[5], NiaoUid1); } if (hasNiaoUid2) { output.WriteString(7, field_names[6], NiaoUid2); } if (users_.Count > 0) { output.WriteMessageArray(8, field_names[7], users_); } if (hasDesUid) { output.WriteString(9, field_names[0], DesUid); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasErrorInfo) { size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode); } if (hasNiaoCard1) { size += pb::CodedOutputStream.ComputeInt32Size(4, NiaoCard1); } if (hasNiaoCard2) { size += pb::CodedOutputStream.ComputeInt32Size(5, NiaoCard2); } if (hasNiaoUid1) { size += pb::CodedOutputStream.ComputeStringSize(6, NiaoUid1); } if (hasNiaoUid2) { size += pb::CodedOutputStream.ComputeStringSize(7, NiaoUid2); } foreach (global::DolphinServer.ProtoEntity.A1021User element in UsersList) { size += pb::CodedOutputStream.ComputeMessageSize(8, element); } if (hasDesUid) { size += pb::CodedOutputStream.ComputeStringSize(9, DesUid); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1021Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1021Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1021Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1021Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1021Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1021Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1021Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1021Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1021Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1021Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1021Response MakeReadOnly() { users_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1021Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1021Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1021Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1021Response result; private A1021Response PrepareBuilder() { if (resultIsReadOnly) { A1021Response original = result; result = new A1021Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1021Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1021Response.Descriptor; } } public override A1021Response DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1021Response.DefaultInstance; } } public override A1021Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1021Response) { return MergeFrom((A1021Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1021Response other) { if (other == global::DolphinServer.ProtoEntity.A1021Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasErrorInfo) { ErrorInfo = other.ErrorInfo; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.HasNiaoCard1) { NiaoCard1 = other.NiaoCard1; } if (other.HasNiaoCard2) { NiaoCard2 = other.NiaoCard2; } if (other.HasNiaoUid1) { NiaoUid1 = other.NiaoUid1; } if (other.HasNiaoUid2) { NiaoUid2 = other.NiaoUid2; } if (other.users_.Count != 0) { result.users_.Add(other.users_); } if (other.HasDesUid) { DesUid = other.DesUid; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1021ResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1021ResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasErrorInfo = input.ReadString(ref result.errorInfo_); break; } case 16: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 32: { result.hasNiaoCard1 = input.ReadInt32(ref result.niaoCard1_); break; } case 40: { result.hasNiaoCard2 = input.ReadInt32(ref result.niaoCard2_); break; } case 50: { result.hasNiaoUid1 = input.ReadString(ref result.niaoUid1_); break; } case 58: { result.hasNiaoUid2 = input.ReadString(ref result.niaoUid2_); break; } case 66: { input.ReadMessageArray(tag, field_name, result.users_, global::DolphinServer.ProtoEntity.A1021User.DefaultInstance, extensionRegistry); break; } case 74: { result.hasDesUid = input.ReadString(ref result.desUid_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasErrorInfo { get { return result.hasErrorInfo; } } public string ErrorInfo { get { return result.ErrorInfo; } set { SetErrorInfo(value); } } public Builder SetErrorInfo(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasErrorInfo = true; result.errorInfo_ = value; return this; } public Builder ClearErrorInfo() { PrepareBuilder(); result.hasErrorInfo = false; result.errorInfo_ = ""; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public bool HasNiaoCard1 { get { return result.hasNiaoCard1; } } public int NiaoCard1 { get { return result.NiaoCard1; } set { SetNiaoCard1(value); } } public Builder SetNiaoCard1(int value) { PrepareBuilder(); result.hasNiaoCard1 = true; result.niaoCard1_ = value; return this; } public Builder ClearNiaoCard1() { PrepareBuilder(); result.hasNiaoCard1 = false; result.niaoCard1_ = 0; return this; } public bool HasNiaoCard2 { get { return result.hasNiaoCard2; } } public int NiaoCard2 { get { return result.NiaoCard2; } set { SetNiaoCard2(value); } } public Builder SetNiaoCard2(int value) { PrepareBuilder(); result.hasNiaoCard2 = true; result.niaoCard2_ = value; return this; } public Builder ClearNiaoCard2() { PrepareBuilder(); result.hasNiaoCard2 = false; result.niaoCard2_ = 0; return this; } public bool HasNiaoUid1 { get { return result.hasNiaoUid1; } } public string NiaoUid1 { get { return result.NiaoUid1; } set { SetNiaoUid1(value); } } public Builder SetNiaoUid1(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasNiaoUid1 = true; result.niaoUid1_ = value; return this; } public Builder ClearNiaoUid1() { PrepareBuilder(); result.hasNiaoUid1 = false; result.niaoUid1_ = ""; return this; } public bool HasNiaoUid2 { get { return result.hasNiaoUid2; } } public string NiaoUid2 { get { return result.NiaoUid2; } set { SetNiaoUid2(value); } } public Builder SetNiaoUid2(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasNiaoUid2 = true; result.niaoUid2_ = value; return this; } public Builder ClearNiaoUid2() { PrepareBuilder(); result.hasNiaoUid2 = false; result.niaoUid2_ = ""; return this; } public pbc::IPopsicleList<global::DolphinServer.ProtoEntity.A1021User> UsersList { get { return PrepareBuilder().users_; } } public int UsersCount { get { return result.UsersCount; } } public global::DolphinServer.ProtoEntity.A1021User GetUsers(int index) { return result.GetUsers(index); } public Builder SetUsers(int index, global::DolphinServer.ProtoEntity.A1021User value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.users_[index] = value; return this; } public Builder SetUsers(int index, global::DolphinServer.ProtoEntity.A1021User.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.users_[index] = builderForValue.Build(); return this; } public Builder AddUsers(global::DolphinServer.ProtoEntity.A1021User value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.users_.Add(value); return this; } public Builder AddUsers(global::DolphinServer.ProtoEntity.A1021User.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.users_.Add(builderForValue.Build()); return this; } public Builder AddRangeUsers(scg::IEnumerable<global::DolphinServer.ProtoEntity.A1021User> values) { PrepareBuilder(); result.users_.Add(values); return this; } public Builder ClearUsers() { PrepareBuilder(); result.users_.Clear(); return this; } public bool HasDesUid { get { return result.hasDesUid; } } public string DesUid { get { return result.DesUid; } set { SetDesUid(value); } } public Builder SetDesUid(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasDesUid = true; result.desUid_ = value; return this; } public Builder ClearDesUid() { PrepareBuilder(); result.hasDesUid = false; result.desUid_ = ""; return this; } } static A1021Response() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1021Response.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1021User : pb::GeneratedMessage<A1021User, A1021User.Builder> { private A1021User() { } private static readonly A1021User defaultInstance = new A1021User().MakeReadOnly(); private static readonly string[] _a1021UserFieldNames = new string[] { "HuType", "Score", "TotalScore", "Uid" }; private static readonly uint[] _a1021UserFieldTags = new uint[] { 32, 16, 24, 10 }; public static A1021User DefaultInstance { get { return defaultInstance; } } public override A1021User DefaultInstanceForType { get { return DefaultInstance; } } protected override A1021User ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1021Response.internal__static_A1021User__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1021User, A1021User.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1021Response.internal__static_A1021User__FieldAccessorTable; } } public const int UidFieldNumber = 1; private bool hasUid; private string uid_ = ""; public bool HasUid { get { return hasUid; } } public string Uid { get { return uid_; } } public const int ScoreFieldNumber = 2; private bool hasScore; private int score_; public bool HasScore { get { return hasScore; } } public int Score { get { return score_; } } public const int TotalScoreFieldNumber = 3; private bool hasTotalScore; private int totalScore_; public bool HasTotalScore { get { return hasTotalScore; } } public int TotalScore { get { return totalScore_; } } public const int HuTypeFieldNumber = 4; private bool hasHuType; private int huType_; public bool HasHuType { get { return hasHuType; } } public int HuType { get { return huType_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1021UserFieldNames; if (hasUid) { output.WriteString(1, field_names[3], Uid); } if (hasScore) { output.WriteInt32(2, field_names[1], Score); } if (hasTotalScore) { output.WriteInt32(3, field_names[2], TotalScore); } if (hasHuType) { output.WriteInt32(4, field_names[0], HuType); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasUid) { size += pb::CodedOutputStream.ComputeStringSize(1, Uid); } if (hasScore) { size += pb::CodedOutputStream.ComputeInt32Size(2, Score); } if (hasTotalScore) { size += pb::CodedOutputStream.ComputeInt32Size(3, TotalScore); } if (hasHuType) { size += pb::CodedOutputStream.ComputeInt32Size(4, HuType); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1021User ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1021User ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1021User ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1021User ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1021User ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1021User ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1021User ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1021User ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1021User ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1021User ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1021User MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1021User prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1021User, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1021User cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1021User result; private A1021User PrepareBuilder() { if (resultIsReadOnly) { A1021User original = result; result = new A1021User(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1021User MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1021User.Descriptor; } } public override A1021User DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1021User.DefaultInstance; } } public override A1021User BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1021User) { return MergeFrom((A1021User) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1021User other) { if (other == global::DolphinServer.ProtoEntity.A1021User.DefaultInstance) return this; PrepareBuilder(); if (other.HasUid) { Uid = other.Uid; } if (other.HasScore) { Score = other.Score; } if (other.HasTotalScore) { TotalScore = other.TotalScore; } if (other.HasHuType) { HuType = other.HuType; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1021UserFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1021UserFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasUid = input.ReadString(ref result.uid_); break; } case 16: { result.hasScore = input.ReadInt32(ref result.score_); break; } case 24: { result.hasTotalScore = input.ReadInt32(ref result.totalScore_); break; } case 32: { result.hasHuType = input.ReadInt32(ref result.huType_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasUid { get { return result.hasUid; } } public string Uid { get { return result.Uid; } set { SetUid(value); } } public Builder SetUid(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUid = true; result.uid_ = value; return this; } public Builder ClearUid() { PrepareBuilder(); result.hasUid = false; result.uid_ = ""; return this; } public bool HasScore { get { return result.hasScore; } } public int Score { get { return result.Score; } set { SetScore(value); } } public Builder SetScore(int value) { PrepareBuilder(); result.hasScore = true; result.score_ = value; return this; } public Builder ClearScore() { PrepareBuilder(); result.hasScore = false; result.score_ = 0; return this; } public bool HasTotalScore { get { return result.hasTotalScore; } } public int TotalScore { get { return result.TotalScore; } set { SetTotalScore(value); } } public Builder SetTotalScore(int value) { PrepareBuilder(); result.hasTotalScore = true; result.totalScore_ = value; return this; } public Builder ClearTotalScore() { PrepareBuilder(); result.hasTotalScore = false; result.totalScore_ = 0; return this; } public bool HasHuType { get { return result.hasHuType; } } public int HuType { get { return result.HuType; } set { SetHuType(value); } } public Builder SetHuType(int value) { PrepareBuilder(); result.hasHuType = true; result.huType_ = value; return this; } public Builder ClearHuType() { PrepareBuilder(); result.hasHuType = false; result.huType_ = 0; return this; } } static A1021User() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1021Response.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; using System.Collections; namespace Anycmd.Xacml.Runtime.Functions { using Interfaces; using typ = DataTypes; /// <summary> /// Generic function base used to implement common IFunction members. /// </summary> public abstract class FunctionBase : IFunction { #region IFunctionParameter Members /// <summary> /// Gets the data type of the value. /// </summary> /// <param name="context">The evaluation context.</param> /// <returns>The data type descriptor.</returns> public IDataType GetType(EvaluationContext context) { return DataTypeDescriptor.Function; } /// <summary> /// Gets the value as a generic object. /// </summary> /// <param name="dataType">The expected data type of the value.</param> /// <param name="parNo">The number of parameter used only for error notification.</param> /// <returns></returns> public virtual object GetTypedValue(IDataType dataType, int parNo) { return this; } /// <summary> /// Whether the value is a bag. /// </summary> public bool IsBag { get { throw new EvaluationException(Properties.Resource.exc_invalid_function_usage); } } /// <summary> /// If the value is a bag the size will be returned otherwise an exception is thrown. /// </summary> public int BagSize { get { throw new EvaluationException(Properties.Resource.exc_invalid_function_usage); } } /// <summary> /// The elements of the bag value. /// </summary> public ArrayList Elements { get { throw new EvaluationException(Properties.Resource.exc_invalid_function_usage); } } /// <summary> /// The instantiated function. /// </summary> /// <param name="parNo">THe number of parameter used only for error notification.</param> /// <returns></returns> public IFunction GetFunction(int parNo) { return this; } #endregion #region Abstract methods /// <summary> /// The function Id defined in the specification. /// </summary> public abstract string Id { get; } /// <summary> /// Evaluates the function. /// </summary> /// <param name="context">The Evaluation context information.</param> /// <param name="args">The function arguments.</param> /// <returns>The result value of the function evaluation.</returns> public abstract EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args); /// <summary> /// The data type of the return value. /// </summary> public abstract IDataType Returns { get; } /// <summary> /// Defines the data types for the function arguments. /// </summary> public abstract IDataType[] Arguments { get; } /// <summary> /// Whether the function defines variable arguments. The data type of the variable arguments will be the /// data type of the last parameter. /// </summary> public virtual bool VarArgs { get { return false; } } #endregion #region Protected methods /// <summary> /// Returns the value of the argument in the index specified of the type int. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The integer value.</returns> protected static int GetIntegerArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (int)args[index].GetTypedValue(DataTypeDescriptor.Integer, index); } /// <summary> /// Returns the value of the argument in the index specified of the type bool. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The bool value.</returns> protected static bool GetBooleanArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (bool)args[index].GetTypedValue(DataTypeDescriptor.Boolean, index); } /// <summary> /// Returns the value of the argument in the index specified of the type AnyUri. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The Uri value.</returns> protected static Uri GetAnyUriArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (Uri)args[index].GetTypedValue(DataTypeDescriptor.AnyUri, index); } /// <summary> /// Returns the value of the argument in the index specified of the type String. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The String value.</returns> protected static string GetStringArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (string)args[index].GetTypedValue(DataTypeDescriptor.String, index); } /// <summary> /// Returns the value of the argument in the index specified of the type Base64Binary. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The Base64Binary value.</returns> protected static typ.Base64Binary GetBase64BinaryArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.Base64Binary)args[index].GetTypedValue(DataTypeDescriptor.Base64Binary, index); } /// <summary> /// Returns the value of the argument in the index specified of the type Date. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The Date value.</returns> protected static DateTime GetDateArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (DateTime)args[index].GetTypedValue(DataTypeDescriptor.Date, index); } /// <summary> /// Returns the value of the argument in the index specified of the type Time. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The Time value.</returns> protected static DateTime GetTimeArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (DateTime)args[index].GetTypedValue(DataTypeDescriptor.Time, index); } /// <summary> /// Returns the value of the argument in the index specified of the type DateTime. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The DateTime value.</returns> protected static DateTime GetDateTimeArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (DateTime)args[index].GetTypedValue(DataTypeDescriptor.DateTime, index); } /// <summary> /// Returns the value of the argument in the index specified of the type DaytimeDuration. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The DaytimeDuration value.</returns> protected static typ.DaytimeDuration GetDaytimeDurationArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.DaytimeDuration)args[index].GetTypedValue(DataTypeDescriptor.DaytimeDuration, index); } /// <summary> /// Returns the value of the argument in the index specified of the type Double. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The Double value.</returns> protected static double GetDoubleArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (double)args[index].GetTypedValue(DataTypeDescriptor.Double, index); } /// <summary> /// Returns the value of the argument in the index specified of the type HexBinary. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The HexBinary value.</returns> protected static typ.HexBinary GetHexBinaryArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.HexBinary)args[index].GetTypedValue(DataTypeDescriptor.HexBinary, index); } /// <summary> /// Returns the value of the argument in the index specified of the type Rfc822Name. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The Rfc822Name value.</returns> protected static typ.Rfc822Name GetRfc822NameArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.Rfc822Name)args[index].GetTypedValue(DataTypeDescriptor.Rfc822Name, index); } /// <summary> /// Returns the value of the argument in the index specified of the type X500Name. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The X500Name value.</returns> protected static typ.X500Name GetX500NameArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.X500Name)args[index].GetTypedValue(DataTypeDescriptor.X500Name, index); } /// <summary> /// Returns the value of the argument in the index specified of the type YearMonthDuration. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The YearMonthDuration value.</returns> protected static typ.YearMonthDuration GetYearMonthDurationArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); if (args == null) throw new ArgumentNullException("args"); return (typ.YearMonthDuration)args[index].GetTypedValue(DataTypeDescriptor.YearMonthDuration, index); } /// <summary> /// Returns the value of the argument in the index specified of the type DnsName. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The DnsName value.</returns> protected static typ.DnsNameDataType GetDnsNameArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.DnsNameDataType)args[index].GetTypedValue(DataTypeDescriptor.DnsName, index); } /// <summary> /// Returns the value of the argument in the index specified of the type IPAddress. /// </summary> /// <param name="args">The arguments list</param> /// <param name="index">The index</param> /// <returns>The IPAddress value.</returns> protected static typ.IpAddress GetIpAddressArgument(IFunctionParameter[] args, int index) { if (args == null) throw new ArgumentNullException("args"); return (typ.IpAddress)args[index].GetTypedValue(DataTypeDescriptor.IpAddress, index); } #endregion } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse 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. *********************************************************************/ using System; using System.IO; using System.Diagnostics; using Axiom.MathLib; using Axiom.Core; using Axiom.Graphics; using Axiom.Utility; using Multiverse; using Multiverse.CollisionLib; using System.Security.Cryptography; namespace Axiom.SceneManagers.Multiverse { public class TreeRenderArgs { public int AlphaTestValue; public int LOD; public bool Active; public TreeRenderArgs() { } } /// <summary> /// Summary description for Tree. /// </summary> public class Tree : IDisposable { private Vector3 location; protected float[] billboard0; protected float[] billboard1; private SpeedTreeWrapper speedTree; private bool renderFlag = false; private AxisAlignedBox bounds; private TreeGroup group; private bool disposed = false; // These values are returned by speedtree.GetGeometry(). They only change when // the camera moves. protected TreeRenderArgs branchRenderArgs = new TreeRenderArgs(); protected TreeRenderArgs frondRenderArgs = new TreeRenderArgs(); protected TreeRenderArgs leaf0RenderArgs = new TreeRenderArgs(); protected TreeRenderArgs leaf1RenderArgs = new TreeRenderArgs(); protected TreeRenderArgs billboard0RenderArgs = new TreeRenderArgs(); protected TreeRenderArgs billboard1RenderArgs = new TreeRenderArgs(); public Tree(TreeGroup group, SpeedTreeWrapper speedTree, Vector3 location) { this.group = group; this.location = location; this.speedTree = speedTree; billboard0 = new float[20]; billboard1 = new float[20]; // set location for the instance speedTree.TreePosition = SpeedTreeUtil.ToSpeedTree(location); // set bounding box AxisAlignedBox stbox = SpeedTreeUtil.FromSpeedTree(speedTree.BoundingBox); this.bounds = new AxisAlignedBox(stbox.Minimum + location, stbox.Maximum + location); } /// <summary> /// This method must be called whenever the camera changes. It gets the new /// camera dependent rendering arguments from SpeedTree. /// </summary> protected void UpdateRenderArgs() { // let speedtree compute the LOD for this tree speedTree.ComputeLodLevel(); // update geometry for all parts TreeGeometry geometry = group.Geometry; speedTree.GetGeometry(geometry, SpeedTreeWrapper.GeometryFlags.AllGeometry, -1, -1, -1); // copy out branch args branchRenderArgs.AlphaTestValue = (int)geometry.BranchAlphaTestValue; branchRenderArgs.LOD = geometry.Branches.DiscreteLodLevel; branchRenderArgs.Active = branchRenderArgs.AlphaTestValue < 255; // copy out frond args frondRenderArgs.AlphaTestValue = (int)geometry.FrondAlphaTestValue; frondRenderArgs.LOD = geometry.Fronds.DiscreteLodLevel; frondRenderArgs.Active = frondRenderArgs.AlphaTestValue < 255; // copy out leaf args leaf0RenderArgs.AlphaTestValue = (int)geometry.Leaves0.AlphaTestValue; leaf0RenderArgs.LOD = geometry.Leaves0.DiscreteLodLevel; leaf0RenderArgs.Active = geometry.Leaves0.IsActive; leaf1RenderArgs.AlphaTestValue = (int)geometry.Leaves1.AlphaTestValue; leaf1RenderArgs.LOD = geometry.Leaves1.DiscreteLodLevel; leaf1RenderArgs.Active = geometry.Leaves1.IsActive; // copy out billboard args // NOTE - billboards dont have LOD billboard0RenderArgs.AlphaTestValue = (int)geometry.Billboard0.AlphaTestValue; billboard0RenderArgs.Active = geometry.Billboard0.IsActive; billboard0RenderArgs.LOD = 0; billboard1RenderArgs.AlphaTestValue = (int)geometry.Billboard1.AlphaTestValue; billboard1RenderArgs.Active = geometry.Billboard1.IsActive; billboard1RenderArgs.LOD = 0; if (billboard0RenderArgs.Active) { FillBillboardBuffer(billboard0, geometry.Billboard0); } if (billboard1RenderArgs.Active) { FillBillboardBuffer(billboard1, geometry.Billboard1); } group.AddVisible(this, branchRenderArgs.Active, frondRenderArgs.Active, leaf0RenderArgs.Active || leaf1RenderArgs.Active, billboard0RenderArgs.Active || billboard1RenderArgs.Active); } public RenderOperation CreateBillboardBuffer() { RenderOperation renderOp = new RenderOperation(); renderOp.operationType = OperationType.TriangleFan; renderOp.useIndices = false; VertexData vertexData = new VertexData(); vertexData.vertexCount = 4; vertexData.vertexStart = 0; // free the original vertex declaration to avoid a leak HardwareBufferManager.Instance.DestroyVertexDeclaration(vertexData.vertexDeclaration); // use common vertex declaration vertexData.vertexDeclaration = TreeGroup.BillboardVertexDeclaration; // create the hardware vertex buffer and set up the buffer binding HardwareVertexBuffer hvBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( vertexData.vertexDeclaration.GetVertexSize(0), vertexData.vertexCount, BufferUsage.DynamicWriteOnly, false); vertexData.vertexBufferBinding.SetBinding(0, hvBuffer); renderOp.vertexData = vertexData; return renderOp; } public void FillBillboardBuffer(float [] buffer, TreeGeometry.Billboard billboard) { unsafe { float * srcCoord = billboard.Coords; float * srcTexCoord = billboard.TexCoords; // Position buffer[0] = srcCoord[0] + location.x; buffer[1] = srcCoord[1] + location.y; buffer[2] = srcCoord[2] + location.z; // Texture buffer[3] = srcTexCoord[0]; buffer[4] = srcTexCoord[1]; // Position buffer[5] = srcCoord[3] + location.x; buffer[6] = srcCoord[4] + location.y; buffer[7] = srcCoord[5] + location.z; // Texture buffer[8] = srcTexCoord[2]; buffer[9] = srcTexCoord[3]; // Position buffer[10] = srcCoord[6] + location.x; buffer[11] = srcCoord[7] + location.y; buffer[12] = srcCoord[8] + location.z; // Texture buffer[13] = srcTexCoord[4]; buffer[14] = srcTexCoord[5]; // Position buffer[15] = srcCoord[9] + location.x; buffer[16] = srcCoord[10] + location.y; buffer[17] = srcCoord[11] + location.z; // Texture buffer[18] = srcTexCoord[6]; buffer[19] = srcTexCoord[7]; } return; } // formerly UpdateVisibility(Camera camera) public void CameraChange(Camera camera) { // we need to draw the tree if it intersects with the camera frustrum renderFlag = camera.IsObjectVisible(bounds); if (renderFlag) { // if the tree is still visible, update the camera dependent rendering args UpdateRenderArgs(); } } public bool RenderFlag { get { return renderFlag; } } public AxisAlignedBox Bounds { get { return bounds; } } public void FindObstaclesInBox(AxisAlignedBox box, CollisionTileManager.AddTreeObstaclesCallback callback) { if (box.Intersects(location)) callback(speedTree); } public TreeRenderArgs BranchRenderArgs { get { return branchRenderArgs; } } public TreeRenderArgs FrondRenderArgs { get { return frondRenderArgs; } } public TreeRenderArgs Leaf0RenderArgs { get { return leaf0RenderArgs; } } public TreeRenderArgs Leaf1RenderArgs { get { return leaf1RenderArgs; } } public TreeRenderArgs Billboard0RenderArgs { get { return billboard0RenderArgs; } } public TreeRenderArgs Billboard1RenderArgs { get { return billboard1RenderArgs; } } public Vector3 Location { get { return location; } } public SpeedTreeWrapper SpeedTree { get { return speedTree; } } public float[] Billboard0 { get { return billboard0; } } public float[] Billboard1 { get { return billboard1; } } #region IDisposable Members public void Dispose() { Debug.Assert(!disposed); disposed = true; } #endregion } }
// Copyright 2007 Google Inc. // // 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.Net; using System.Text; using System.IO; namespace GoogleEmailUploader { // We abstract out the http request responses we do so that we can test // GoogleEmailUploader using a mocks. /// <summary> /// Interface for creating http requests. /// </summary> public interface IHttpFactory { /// <summary> /// Create a http get request. /// </summary> IHttpRequest CreateGetRequest(string url); /// <summary> /// Create a http post request. /// </summary> IHttpRequest CreatePostRequest(string url); /// <summary> /// Create a http put request. /// </summary> IHttpRequest CreatePutRequest(string url); } /// <summary> /// Iterface representing http request. /// </summary> public interface IHttpRequest { /// <summary> /// The content type of the http request. /// </summary> string ContentType { set; } /// <summary> /// The user agent for the request. /// </summary> string UserAgent { set; } /// <summary> /// The length of content. /// </summary> long ContentLength { set; } /// <summary> /// Method to add key value pairs to the request header. /// </summary> void AddToHeader(string key, string value); /// <summary> /// Get the request stream to add the conent of the request. /// </summary> Stream GetRequestStream(); /// <summary> /// Process the request and get the response. /// </summary> IHttpResponse GetResponse(); } /// <summary> /// Interface representing http response. /// </summary> public interface IHttpResponse { /// <summary> /// Returns the http headers as a string. /// </summary> string Headers { get; } /// <summary> /// Get the response stream to read the conent of response /// </summary> Stream GetResponseStream(); /// <summary> /// Close the response. /// </summary> void Close(); } /// <summary> /// Status for the http eexceptions /// </summary> public enum HttpExceptionStatus { /// <summary> /// The client provided with wrong credentials /// </summary> Unauthorized, /// <summary> /// The client cant uplaod to the given account /// </summary> Forbidden, /// <summary> /// Connection closed because of large upload. /// </summary> BadGateway, /// <summary> /// The request could not be carried out because of a conflict /// on the server. /// </summary> Conflict, /// <summary> /// The request had some errors. /// </summary> BadRequest, /// <summary> /// Corresponds to WebExceptionStatus.ProtocolError which is not one of the /// above /// </summary> ProtocolError, /// <summary> /// Corresponds to WebExceptionStatus.Timeout /// </summary> Timeout, /// <summary> /// Corresponds to any other WebExceptionStatus /// </summary> Other, } public class HttpException : Exception { HttpExceptionStatus status; IHttpResponse response; public HttpException(string message, HttpExceptionStatus status, IHttpResponse response) : base(message) { this.status = status; this.response = response; } public HttpExceptionStatus Status { get { return this.status; } } public IHttpResponse Response { get { return this.response; } } public string GetResponseString() { string exceptionResponseString = string.Empty; if (response != null) { using (Stream respStream = response.GetResponseStream()) { using (StreamReader textReader = new StreamReader(respStream)) { exceptionResponseString = textReader.ReadToEnd(); } } } return exceptionResponseString; } internal static HttpException FromWebException(WebException webException) { try { GoogleEmailUploaderTrace.EnteringMethod( "HttpException.FromWebException"); GoogleEmailUploaderTrace.WriteLine( "Exception ({0}): {1}", webException.Status.ToString(), webException.ToString()); HttpResponse httpResponse = null; if (webException.Response != null) { GoogleEmailUploaderTrace.WriteLine( "Headers: {0}", webException.Response.Headers.ToString()); httpResponse = new HttpResponse((HttpWebResponse)webException.Response); } HttpExceptionStatus httpExceptionStatus; switch (webException.Status) { case WebExceptionStatus.ProtocolError: if (webException.Response != null) { HttpStatusCode httpStatusCode = ((HttpWebResponse)webException.Response).StatusCode; if (httpStatusCode == HttpStatusCode.Unauthorized) { httpExceptionStatus = HttpExceptionStatus.Unauthorized; break; } else if (httpStatusCode == HttpStatusCode.Forbidden) { httpExceptionStatus = HttpExceptionStatus.Forbidden; break; } else if (httpStatusCode == HttpStatusCode.BadGateway) { httpExceptionStatus = HttpExceptionStatus.BadGateway; break; } else if (httpStatusCode == HttpStatusCode.Conflict) { httpExceptionStatus = HttpExceptionStatus.Conflict; break; } else if (httpStatusCode == HttpStatusCode.BadRequest) { httpExceptionStatus = HttpExceptionStatus.BadRequest; break; } } httpExceptionStatus = HttpExceptionStatus.ProtocolError; break; case WebExceptionStatus.Timeout: httpExceptionStatus = HttpExceptionStatus.Timeout; break; default: httpExceptionStatus = HttpExceptionStatus.Other; break; } return new HttpException(webException.Message, httpExceptionStatus, httpResponse); } finally { GoogleEmailUploaderTrace.ExitingMethod( "HttpException.FromWebException"); } } } class HttpFactory : IHttpFactory { IHttpRequest IHttpFactory.CreateGetRequest(string url) { try { GoogleEmailUploaderTrace.EnteringMethod("HttpFactory.CreateGetRequest"); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "GET"; httpWebRequest.KeepAlive = false; httpWebRequest.ProtocolVersion = HttpVersion.Version10; return new HttpRequest(httpWebRequest); } catch (WebException we) { throw HttpException.FromWebException(we); } finally { GoogleEmailUploaderTrace.ExitingMethod("HttpFactory.CreateGetRequest"); } } IHttpRequest IHttpFactory.CreatePostRequest(string url) { try { GoogleEmailUploaderTrace.EnteringMethod( "HttpFactory.CreatePostRequest"); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "POST"; httpWebRequest.AllowAutoRedirect = false; httpWebRequest.KeepAlive = false; httpWebRequest.ProtocolVersion = HttpVersion.Version10; return new HttpRequest(httpWebRequest); } catch (WebException we) { throw HttpException.FromWebException(we); } finally { GoogleEmailUploaderTrace.ExitingMethod("HttpFactory.CreatePostRequest"); } } IHttpRequest IHttpFactory.CreatePutRequest(string url) { try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "PUT"; httpWebRequest.AllowAutoRedirect = false; httpWebRequest.KeepAlive = false; httpWebRequest.ProtocolVersion = HttpVersion.Version10; return new HttpRequest(httpWebRequest); } catch (WebException we) { throw HttpException.FromWebException(we); } } } class HttpRequest : IHttpRequest { HttpWebRequest httpWebRequest; internal HttpRequest(HttpWebRequest httpWebRequest) { this.httpWebRequest = httpWebRequest; } #region IHttpRequest Members string IHttpRequest.ContentType { set { this.httpWebRequest.ContentType = value; } } string IHttpRequest.UserAgent { set { this.httpWebRequest.UserAgent = value; } } long IHttpRequest.ContentLength { set { this.httpWebRequest.ContentLength = value; } } void IHttpRequest.AddToHeader(string key, string value) { try { this.httpWebRequest.Headers.Add(key, value); } catch (WebException we) { throw HttpException.FromWebException(we); } } Stream IHttpRequest.GetRequestStream() { try { GoogleEmailUploaderTrace.EnteringMethod( "HttpRequest.GetRequestStream"); return this.httpWebRequest.GetRequestStream(); } catch (WebException we) { throw HttpException.FromWebException(we); } finally { GoogleEmailUploaderTrace.ExitingMethod( "HttpRequest.GetRequestStream"); } } IHttpResponse IHttpRequest.GetResponse() { try { GoogleEmailUploaderTrace.EnteringMethod( "HttpRequest.GetResponse"); GoogleEmailUploaderTrace.WriteLine( "Headers: {0}", this.httpWebRequest.Headers.ToString()); HttpWebResponse httpWebResponse = (HttpWebResponse)this.httpWebRequest.GetResponse(); return new HttpResponse(httpWebResponse); } catch (WebException we) { throw HttpException.FromWebException(we); } finally { GoogleEmailUploaderTrace.ExitingMethod( "HttpRequest.GetResponse"); } } #endregion } class HttpResponse : IHttpResponse { HttpWebResponse httpWebResponse; internal HttpResponse(HttpWebResponse httpWebResponse) { GoogleEmailUploaderTrace.EnteringMethod( "HttpResponse.HttpResponse"); GoogleEmailUploaderTrace.WriteLine( "Headers: {0}", httpWebResponse.Headers.ToString()); this.httpWebResponse = httpWebResponse; GoogleEmailUploaderTrace.ExitingMethod( "HttpResponse.HttpResponse"); } #region IHttpResponse Members string IHttpResponse.Headers { get { return httpWebResponse.Headers.ToString(); } } Stream IHttpResponse.GetResponseStream() { try { return this.httpWebResponse.GetResponseStream(); } catch (WebException we) { throw HttpException.FromWebException(we); } } void IHttpResponse.Close() { try { this.httpWebResponse.Close(); } catch (WebException we) { throw HttpException.FromWebException(we); } } #endregion } }
#if !BESTHTTP_DISABLE_SOCKETIO using System; using System.Collections.Generic; namespace BestHTTP.SocketIO { using BestHTTP; using BestHTTP.SocketIO.Events; /// <summary> /// This class represents a Socket.IO namespace. /// </summary> public sealed class Socket : ISocket { #region Public Properties /// <summary> /// The SocketManager instance that created this socket. /// </summary> public SocketManager Manager { get; private set; } /// <summary> /// The namespace that this socket is bound to. /// </summary> public string Namespace { get; private set; } /// <summary> /// True if the socket is connected and open to the server. False otherwise. /// </summary> public bool IsOpen { get; private set; } /// <summary> /// While this property is True, the socket will decode the Packet's Payload data using the parent SocketManager's Encoder. You must set this property before any event subsciption! Its default value is True; /// </summary> public bool AutoDecodePayload { get; set; } #endregion #region Privates /// <summary> /// A table to store acknowlegement callbacks associated to the given ids. /// </summary> private Dictionary<int, SocketIOAckCallback> AckCallbacks; /// <summary> /// Tha callback table that helps this class to manage event subsciption and dispatching events. /// </summary> private EventTable EventCallbacks; /// <summary> /// Cached list to spare some GC alloc. /// </summary> private List<object> arguments = new List<object>(); #endregion /// <summary> /// Internal constructor. /// </summary> internal Socket(string nsp, SocketManager manager) { this.Namespace = nsp; this.Manager = manager; this.IsOpen = false; this.AutoDecodePayload = true; this.EventCallbacks = new EventTable(this); } #region Socket Handling /// <summary> /// Internal function to start opening the socket. /// </summary> void ISocket.Open() { // The transport already estabilished the connection if (Manager.State == SocketManager.States.Open) OnTransportOpen(Manager.Socket, null); else { // We want to receive a message when we are connected. Manager.Socket.Off(EventNames.Connect, OnTransportOpen); Manager.Socket.On(EventNames.Connect, OnTransportOpen); if (Manager.Options.AutoConnect && Manager.State == SocketManager.States.Initial) Manager.Open(); } } /// <summary> /// Disconnects this socket/namespace. /// </summary> public void Disconnect() { (this as ISocket).Disconnect(true); } /// <summary> /// Disconnects this socket/namespace. /// </summary> void ISocket.Disconnect(bool remove) { // Send a disconnect packet to the server if (IsOpen) { Packet packet = new Packet(TransportEventTypes.Message, SocketIOEventTypes.Disconnect, this.Namespace, string.Empty); (Manager as IManager).SendPacket(packet); // IsOpen must be false, becouse in the OnPacket preprocessing the packet would call this function again IsOpen = false; (this as ISocket).OnPacket(packet); } if (AckCallbacks != null) AckCallbacks.Clear(); if (remove) { EventCallbacks.Clear(); (Manager as IManager).Remove(this); } } #endregion #region Emit Implementations public Socket Emit(string eventName, params object[] args) { return Emit(eventName, null, args); } public Socket Emit(string eventName, SocketIOAckCallback callback, params object[] args) { bool blackListed = EventNames.IsBlacklisted(eventName); if (blackListed) throw new ArgumentException("Blacklisted event: " + eventName); arguments.Clear(); arguments.Add(eventName); // Find and swap any binary data(byte[]) to a placeholder string. // Server side these will be swapped back. List<byte[]> attachments = null; if (args != null && args.Length > 0) { int idx = 0; for (int i = 0; i < args.Length; ++i) { byte[] binData = args[i] as byte[]; if (binData != null) { if (attachments == null) attachments = new List<byte[]>(); Dictionary<string, object> placeholderObj = new Dictionary<string, object>(2); placeholderObj.Add(Packet.Placeholder, true); placeholderObj.Add("num", idx++); arguments.Add(placeholderObj); attachments.Add(binData); } else arguments.Add(args[i]); } } string payload = null; try { payload = Manager.Encoder.Encode(arguments); } catch(Exception ex) { (this as ISocket).EmitError(SocketIOErrors.Internal, "Error while encoding payload: " + ex.Message + " " + ex.StackTrace); return this; } // We don't use it further in this function, so we can clear it to not hold any unwanted reference. arguments.Clear(); if (payload == null) throw new ArgumentException("Encoding the arguments to JSON failed!"); int id = 0; if (callback != null) { id = Manager.NextAckId; if (AckCallbacks == null) AckCallbacks = new Dictionary<int, SocketIOAckCallback>(); AckCallbacks[id] = callback; } Packet packet = new Packet(TransportEventTypes.Message, attachments == null ? SocketIOEventTypes.Event : SocketIOEventTypes.BinaryEvent, this.Namespace, payload, 0, id); if (attachments != null) packet.Attachments = attachments; // This will set the AttachmentCount property too. (Manager as IManager).SendPacket(packet); return this; } public Socket EmitAck(Packet originalPacket, params object[] args) { if (originalPacket == null) throw new ArgumentNullException("originalPacket == null!"); if (/*originalPacket.Id == 0 ||*/ (originalPacket.SocketIOEvent != SocketIOEventTypes.Event && originalPacket.SocketIOEvent != SocketIOEventTypes.BinaryEvent)) throw new ArgumentException("Wrong packet - you can't send an Ack for a packet with id == 0 and SocketIOEvent != Event or SocketIOEvent != BinaryEvent!"); arguments.Clear(); if (args != null && args.Length > 0) arguments.AddRange(args); string payload = null; try { payload = Manager.Encoder.Encode(arguments); } catch (Exception ex) { (this as ISocket).EmitError(SocketIOErrors.Internal, "Error while encoding payload: " + ex.Message + " " + ex.StackTrace); return this; } if (payload == null) throw new ArgumentException("Encoding the arguments to JSON failed!"); Packet packet = new Packet(TransportEventTypes.Message, originalPacket.SocketIOEvent == SocketIOEventTypes.Event ? SocketIOEventTypes.Ack : SocketIOEventTypes.BinaryAck, this.Namespace, payload, 0, originalPacket.Id); (Manager as IManager).SendPacket(packet); return this; } #endregion #region On Implementations /// <summary> /// Register a callback for a given name /// </summary> public void On(string eventName, SocketIOCallback callback) { EventCallbacks.Register(eventName, callback, false, this.AutoDecodePayload); } public void On(SocketIOEventTypes type, SocketIOCallback callback) { string eventName = EventNames.GetNameFor(type); EventCallbacks.Register(eventName, callback, false, this.AutoDecodePayload); } public void On(string eventName, SocketIOCallback callback, bool autoDecodePayload) { EventCallbacks.Register(eventName, callback, false, autoDecodePayload); } public void On(SocketIOEventTypes type, SocketIOCallback callback, bool autoDecodePayload) { string eventName = EventNames.GetNameFor(type); EventCallbacks.Register(eventName, callback, false, autoDecodePayload); } #endregion #region Once Implementations public void Once(string eventName, SocketIOCallback callback) { EventCallbacks.Register(eventName, callback, true, this.AutoDecodePayload); } public void Once(SocketIOEventTypes type, SocketIOCallback callback) { EventCallbacks.Register(EventNames.GetNameFor(type), callback, true, this.AutoDecodePayload); } public void Once(string eventName, SocketIOCallback callback, bool autoDecodePayload) { EventCallbacks.Register(eventName, callback, true, autoDecodePayload); } public void Once(SocketIOEventTypes type, SocketIOCallback callback, bool autoDecodePayload) { EventCallbacks.Register(EventNames.GetNameFor(type), callback, true, autoDecodePayload); } #endregion #region Off Implementations /// <summary> /// Remove all callbacks for all events. /// </summary> public void Off() { EventCallbacks.Clear(); } /// <summary> /// Removes all callbacks to the given event. /// </summary> public void Off(string eventName) { EventCallbacks.Unregister(eventName); } /// <summary> /// Removes all callbacks to the given event. /// </summary> public void Off(SocketIOEventTypes type) { Off(EventNames.GetNameFor(type)); } /// <summary> /// Remove the specified callback. /// </summary> public void Off(string eventName, SocketIOCallback callback) { EventCallbacks.Unregister(eventName, callback); } /// <summary> /// Remove the specified callback. /// </summary> public void Off(SocketIOEventTypes type, SocketIOCallback callback) { EventCallbacks.Unregister(EventNames.GetNameFor(type), callback); } #endregion #region Packet Handling /// <summary> /// Last call of the OnPacket chain(Transport -> Manager -> Socket), we will dispatch the event if there is any callback /// </summary> void ISocket.OnPacket(Packet packet) { // Some preprocessing of the the packet switch(packet.SocketIOEvent) { case SocketIOEventTypes.Disconnect: if (IsOpen) { IsOpen = false; EventCallbacks.Call(EventNames.GetNameFor(SocketIOEventTypes.Disconnect), packet); Disconnect(); } break; // Create an Error object from the server-sent json string case SocketIOEventTypes.Error: bool success = false; object result = JSON.Json.Decode(packet.Payload, ref success); if (success) { var errDict = result as Dictionary<string, object>; Error err; if (errDict != null && errDict.ContainsKey("code")) err = new Error((SocketIOErrors)Convert.ToInt32(errDict["code"]), errDict["message"] as string); else err = new Error(SocketIOErrors.Custom, packet.Payload); EventCallbacks.Call(EventNames.GetNameFor(SocketIOEventTypes.Error), packet, err); return; } break; } // Dispatch the event to all subscriber EventCallbacks.Call(packet); // call Ack callbacks if ((packet.SocketIOEvent == SocketIOEventTypes.Ack || packet.SocketIOEvent == SocketIOEventTypes.BinaryAck) && AckCallbacks != null) { SocketIOAckCallback ackCallback = null; if (AckCallbacks.TryGetValue(packet.Id, out ackCallback) && ackCallback != null) { try { ackCallback(this, packet, this.AutoDecodePayload ? packet.Decode(Manager.Encoder) : null); } catch (Exception ex) { HTTPManager.Logger.Exception("Socket", "ackCallback", ex); } } AckCallbacks.Remove(packet.Id); } } #endregion /// <summary> /// Emits an internal packet-less event to the user level. /// </summary> void ISocket.EmitEvent(SocketIOEventTypes type, params object[] args) { (this as ISocket).EmitEvent(EventNames.GetNameFor(type), args); } /// <summary> /// Emits an internal packet-less event to the user level. /// </summary> void ISocket.EmitEvent(string eventName, params object[] args) { if (!string.IsNullOrEmpty(eventName)) EventCallbacks.Call(eventName, null, args); } void ISocket.EmitError(SocketIOErrors errCode, string msg) { (this as ISocket).EmitEvent(SocketIOEventTypes.Error, new Error(errCode, msg)); } #region Private Helper Functions /// <summary> /// Called when a "connect" event received to the root namespace /// </summary> private void OnTransportOpen(Socket socket, Packet packet, params object[] args) { // If this is not the root namespace, then we send a connect message to the server if (this.Namespace != "/") (Manager as IManager).SendPacket(new Packet(TransportEventTypes.Message, SocketIOEventTypes.Connect, this.Namespace, string.Empty)); // and we are no open IsOpen = true; } #endregion } } #endif
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Calendar Dates for Absences Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KCCDataSet : EduHubDataSet<KCC> { /// <inheritdoc /> public override string Name { get { return "KCC"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KCCDataSet(EduHubContext Context) : base(Context) { Index_CURRENT_QUILT = new Lazy<NullDictionary<string, IReadOnlyList<KCC>>>(() => this.ToGroupedNullDictionary(i => i.CURRENT_QUILT)); Index_KCCKEY = new Lazy<Dictionary<DateTime, KCC>>(() => this.ToDictionary(i => i.KCCKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KCC" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KCC" /> fields for each CSV column header</returns> internal override Action<KCC, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KCC, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KCCKEY": mapper[i] = (e, v) => e.KCCKEY = DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "DAYTODAY": mapper[i] = (e, v) => e.DAYTODAY = v; break; case "DAY_TYPE": mapper[i] = (e, v) => e.DAY_TYPE = v; break; case "JULIAN": mapper[i] = (e, v) => e.JULIAN = v == null ? (short?)null : short.Parse(v); break; case "SEMESTER": mapper[i] = (e, v) => e.SEMESTER = v == null ? (short?)null : short.Parse(v); break; case "DAY_YEAR": mapper[i] = (e, v) => e.DAY_YEAR = v == null ? (short?)null : short.Parse(v); break; case "DAY_MONTH": mapper[i] = (e, v) => e.DAY_MONTH = v == null ? (short?)null : short.Parse(v); break; case "TERM": mapper[i] = (e, v) => e.TERM = v == null ? (short?)null : short.Parse(v); break; case "WEEK": mapper[i] = (e, v) => e.WEEK = v == null ? (short?)null : short.Parse(v); break; case "DAY_CYCLE": mapper[i] = (e, v) => e.DAY_CYCLE = v == null ? (short?)null : short.Parse(v); break; case "CURRENT_QUILT": mapper[i] = (e, v) => e.CURRENT_QUILT = v; break; case "HALF_DAY_GENERATED": mapper[i] = (e, v) => e.HALF_DAY_GENERATED = v; break; case "PERIOD_GENERATED": mapper[i] = (e, v) => e.PERIOD_GENERATED = v; break; case "PAR_SOURCE": mapper[i] = (e, v) => e.PAR_SOURCE = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KCC" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KCC" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KCC" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KCC}"/> of entities</returns> internal override IEnumerable<KCC> ApplyDeltaEntities(IEnumerable<KCC> Entities, List<KCC> DeltaEntities) { HashSet<DateTime> Index_KCCKEY = new HashSet<DateTime>(DeltaEntities.Select(i => i.KCCKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KCCKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KCCKEY.Remove(entity.KCCKEY); if (entity.KCCKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<KCC>>> Index_CURRENT_QUILT; private Lazy<Dictionary<DateTime, KCC>> Index_KCCKEY; #endregion #region Index Methods /// <summary> /// Find KCC by CURRENT_QUILT field /// </summary> /// <param name="CURRENT_QUILT">CURRENT_QUILT value used to find KCC</param> /// <returns>List of related KCC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCC> FindByCURRENT_QUILT(string CURRENT_QUILT) { return Index_CURRENT_QUILT.Value[CURRENT_QUILT]; } /// <summary> /// Attempt to find KCC by CURRENT_QUILT field /// </summary> /// <param name="CURRENT_QUILT">CURRENT_QUILT value used to find KCC</param> /// <param name="Value">List of related KCC entities</param> /// <returns>True if the list of related KCC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCURRENT_QUILT(string CURRENT_QUILT, out IReadOnlyList<KCC> Value) { return Index_CURRENT_QUILT.Value.TryGetValue(CURRENT_QUILT, out Value); } /// <summary> /// Attempt to find KCC by CURRENT_QUILT field /// </summary> /// <param name="CURRENT_QUILT">CURRENT_QUILT value used to find KCC</param> /// <returns>List of related KCC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCC> TryFindByCURRENT_QUILT(string CURRENT_QUILT) { IReadOnlyList<KCC> value; if (Index_CURRENT_QUILT.Value.TryGetValue(CURRENT_QUILT, out value)) { return value; } else { return null; } } /// <summary> /// Find KCC by KCCKEY field /// </summary> /// <param name="KCCKEY">KCCKEY value used to find KCC</param> /// <returns>Related KCC entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCC FindByKCCKEY(DateTime KCCKEY) { return Index_KCCKEY.Value[KCCKEY]; } /// <summary> /// Attempt to find KCC by KCCKEY field /// </summary> /// <param name="KCCKEY">KCCKEY value used to find KCC</param> /// <param name="Value">Related KCC entity</param> /// <returns>True if the related KCC entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKCCKEY(DateTime KCCKEY, out KCC Value) { return Index_KCCKEY.Value.TryGetValue(KCCKEY, out Value); } /// <summary> /// Attempt to find KCC by KCCKEY field /// </summary> /// <param name="KCCKEY">KCCKEY value used to find KCC</param> /// <returns>Related KCC entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCC TryFindByKCCKEY(DateTime KCCKEY) { KCC value; if (Index_KCCKEY.Value.TryGetValue(KCCKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCC table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KCC]( [KCCKEY] datetime NOT NULL, [DAYTODAY] varchar(10) NULL, [DAY_TYPE] varchar(1) NULL, [JULIAN] smallint NULL, [SEMESTER] smallint NULL, [DAY_YEAR] smallint NULL, [DAY_MONTH] smallint NULL, [TERM] smallint NULL, [WEEK] smallint NULL, [DAY_CYCLE] smallint NULL, [CURRENT_QUILT] varchar(8) NULL, [HALF_DAY_GENERATED] varchar(1) NULL, [PERIOD_GENERATED] varchar(1) NULL, [PAR_SOURCE] varchar(3) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KCC_Index_KCCKEY] PRIMARY KEY CLUSTERED ( [KCCKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KCC_Index_CURRENT_QUILT] ON [dbo].[KCC] ( [CURRENT_QUILT] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCC]') AND name = N'KCC_Index_CURRENT_QUILT') ALTER INDEX [KCC_Index_CURRENT_QUILT] ON [dbo].[KCC] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCC]') AND name = N'KCC_Index_CURRENT_QUILT') ALTER INDEX [KCC_Index_CURRENT_QUILT] ON [dbo].[KCC] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCC"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KCC"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCC> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<DateTime> Index_KCCKEY = new List<DateTime>(); foreach (var entity in Entities) { Index_KCCKEY.Add(entity.KCCKEY); } builder.AppendLine("DELETE [dbo].[KCC] WHERE"); // Index_KCCKEY builder.Append("[KCCKEY] IN ("); for (int index = 0; index < Index_KCCKEY.Count; index++) { if (index != 0) builder.Append(", "); // KCCKEY var parameterKCCKEY = $"@p{parameterIndex++}"; builder.Append(parameterKCCKEY); command.Parameters.Add(parameterKCCKEY, SqlDbType.DateTime).Value = Index_KCCKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCC data set</returns> public override EduHubDataSetDataReader<KCC> GetDataSetDataReader() { return new KCCDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCC data set</returns> public override EduHubDataSetDataReader<KCC> GetDataSetDataReader(List<KCC> Entities) { return new KCCDataReader(new EduHubDataSetLoadedReader<KCC>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KCCDataReader : EduHubDataSetDataReader<KCC> { public KCCDataReader(IEduHubDataSetReader<KCC> Reader) : base (Reader) { } public override int FieldCount { get { return 17; } } public override object GetValue(int i) { switch (i) { case 0: // KCCKEY return Current.KCCKEY; case 1: // DAYTODAY return Current.DAYTODAY; case 2: // DAY_TYPE return Current.DAY_TYPE; case 3: // JULIAN return Current.JULIAN; case 4: // SEMESTER return Current.SEMESTER; case 5: // DAY_YEAR return Current.DAY_YEAR; case 6: // DAY_MONTH return Current.DAY_MONTH; case 7: // TERM return Current.TERM; case 8: // WEEK return Current.WEEK; case 9: // DAY_CYCLE return Current.DAY_CYCLE; case 10: // CURRENT_QUILT return Current.CURRENT_QUILT; case 11: // HALF_DAY_GENERATED return Current.HALF_DAY_GENERATED; case 12: // PERIOD_GENERATED return Current.PERIOD_GENERATED; case 13: // PAR_SOURCE return Current.PAR_SOURCE; case 14: // LW_DATE return Current.LW_DATE; case 15: // LW_TIME return Current.LW_TIME; case 16: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DAYTODAY return Current.DAYTODAY == null; case 2: // DAY_TYPE return Current.DAY_TYPE == null; case 3: // JULIAN return Current.JULIAN == null; case 4: // SEMESTER return Current.SEMESTER == null; case 5: // DAY_YEAR return Current.DAY_YEAR == null; case 6: // DAY_MONTH return Current.DAY_MONTH == null; case 7: // TERM return Current.TERM == null; case 8: // WEEK return Current.WEEK == null; case 9: // DAY_CYCLE return Current.DAY_CYCLE == null; case 10: // CURRENT_QUILT return Current.CURRENT_QUILT == null; case 11: // HALF_DAY_GENERATED return Current.HALF_DAY_GENERATED == null; case 12: // PERIOD_GENERATED return Current.PERIOD_GENERATED == null; case 13: // PAR_SOURCE return Current.PAR_SOURCE == null; case 14: // LW_DATE return Current.LW_DATE == null; case 15: // LW_TIME return Current.LW_TIME == null; case 16: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KCCKEY return "KCCKEY"; case 1: // DAYTODAY return "DAYTODAY"; case 2: // DAY_TYPE return "DAY_TYPE"; case 3: // JULIAN return "JULIAN"; case 4: // SEMESTER return "SEMESTER"; case 5: // DAY_YEAR return "DAY_YEAR"; case 6: // DAY_MONTH return "DAY_MONTH"; case 7: // TERM return "TERM"; case 8: // WEEK return "WEEK"; case 9: // DAY_CYCLE return "DAY_CYCLE"; case 10: // CURRENT_QUILT return "CURRENT_QUILT"; case 11: // HALF_DAY_GENERATED return "HALF_DAY_GENERATED"; case 12: // PERIOD_GENERATED return "PERIOD_GENERATED"; case 13: // PAR_SOURCE return "PAR_SOURCE"; case 14: // LW_DATE return "LW_DATE"; case 15: // LW_TIME return "LW_TIME"; case 16: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KCCKEY": return 0; case "DAYTODAY": return 1; case "DAY_TYPE": return 2; case "JULIAN": return 3; case "SEMESTER": return 4; case "DAY_YEAR": return 5; case "DAY_MONTH": return 6; case "TERM": return 7; case "WEEK": return 8; case "DAY_CYCLE": return 9; case "CURRENT_QUILT": return 10; case "HALF_DAY_GENERATED": return 11; case "PERIOD_GENERATED": return 12; case "PAR_SOURCE": return 13; case "LW_DATE": return 14; case "LW_TIME": return 15; case "LW_USER": return 16; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace PatternsIntro.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Spellcheck; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.SpellCheck { public class SpellCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpSpellCheckCodeFixProvider()); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestNoSpellcheckForIfOnly2Characters() { var text = @"class Foo { void Bar() { var a = new [|Fo|] } }"; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestAfterNewExpression() { var text = @"class Foo { void Bar() { void a = new [|Fooa|].ToString(); } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Fooa", "Foo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInLocalType() { var text = @"class Foo { void Bar() { [|Foa|] a; } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo"), String.Format(FeaturesResources.Change_0_to_1, "Foa", "for") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInFunc() { var text = @" using System; class Foo { void Bar(Func<[|Foa|]> f) { } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInExpression() { var text = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + [|zza|]; } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "zza", "zzz") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInTypeOfIsExpression() { var text = @"using System; public class Class1 { void F() { if (x is [|Boolea|]) {} } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Boolea", "Boolean"), String.Format(FeaturesResources.Change_0_to_1, "Boolea", "bool") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInvokeCorrectIdentifier() { var text = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + [|zza|]; } }"; var expected = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + zzz; } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestAfterDot() { var text = @"class Program { static void Main(string[] args) { Program.[|Mair|] } }"; var expected = @"class Program { static void Main(string[] args) { Program.Main } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestNotInaccessibleProperty() { var text = @"class Program { void Main(string[] args) { var z = new c().[|membr|] } } class c { protected int member { get; } }"; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestGenericName1() { var text = @"class Foo<T> { private [|Foo2|]<T> x; }"; var expected = @"class Foo<T> { private Foo<T> x; }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestGenericName2() { var text = @"class Foo<T> { private [|Foo2|] x; }"; var expected = @"class Foo<T> { private Foo x; }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestQualifiedName1() { var text = @"class Program { private object x = new [|Foo2|].Bar } class Foo { class Bar { } }"; var expected = @"class Program { private object x = new Foo.Bar } class Foo { class Bar { } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestQualifiedName2() { var text = @"class Program { private object x = new Foo.[|Ba2|] } class Foo { public class Bar { } }"; var expected = @"class Program { private object x = new Foo.Bar } class Foo { public class Bar { } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestMiddleOfDottedExpression() { var text = @"class Program { void Main(string[] args) { var z = new c().[|membr|].ToString(); } } class c { public int member { get; } }"; var expected = @"class Program { void Main(string[] args) { var z = new c().member.ToString(); } } class c { public int member { get; } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestNotForOverloadResolutionFailure() { var text = @"class Program { void Main(string[] args) { } void Foo() { [|Method|](); } int Method(int argument) { } }"; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestHandlePredefinedTypeKeywordCorrectly() { var text = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { [|Int3|] i; } }"; var expected = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { int i; } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestHandlePredefinedTypeKeywordCorrectly1() { var text = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { [|Int3|] i; } }"; var expected = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { Int32 i; } }"; await TestInRegularAndScriptAsync(text, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestOnGeneric() { var text = @" interface Enumerable<T> { } class C { void Main(string[] args) { [|IEnumerable|]<int> x; } }"; var expected = @" interface Enumerable<T> { } class C { void Main(string[] args) { Enumerable<int> x; } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestTestObjectConstruction() { await TestInRegularAndScriptAsync( @"class AwesomeClass { void M() { var foo = new [|AwesomeClas()|]; } }", @"class AwesomeClass { void M() { var foo = new AwesomeClass(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestTestMissingName() { await TestMissingInRegularAndScriptAsync( @"[assembly: Microsoft.CodeAnalysis.[||]]"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(12990, "https://github.com/dotnet/roslyn/issues/12990")] public async Task TestTrivia1() { var text = @" using System.Text; class C { void M() { /*leading*/ [|stringbuilder|] /*trailing*/ sb = null; } }"; var expected = @" using System.Text; class C { void M() { /*leading*/ StringBuilder /*trailing*/ sb = null; } }"; await TestInRegularAndScriptAsync(text, expected, ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")] public async Task TestNotMissingOnKeywordWhichIsAlsoASnippet() { await TestInRegularAndScriptAsync( @"class C { void M() { // here 'for' is a keyword and snippet, so we should offer to spell check to it. [|foo|]; } }", @"class C { void M() { // here 'for' is a keyword and snippet, so we should offer to spell check to it. for; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(18626, "https://github.com/dotnet/roslyn/issues/18626")] public async Task TestForExplicitInterfaceTypeName() { await TestInRegularAndScriptAsync( @"interface IProjectConfigurationsService { void Method(); } class Program : IProjectConfigurationsService { void [|IProjectConfigurationService|].Method() { } }", @"interface IProjectConfigurationsService { void Method(); } class Program : IProjectConfigurationsService { void IProjectConfigurationsService.Method() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")] public async Task TestMissingOnKeywordWhichIsOnlyASnippet() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { // here 'for' is *only* a snippet, and we should not offer to spell check to it. var v = [|foo|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(15733, "https://github.com/dotnet/roslyn/issues/15733")] public async Task TestMissingOnVar() { await TestMissingInRegularAndScriptAsync( @" namespace bar { } class C { void M() { var y = [|var|] } }"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Reflection; using System.Windows.Forms; using Skybound.VisualTips.Rendering; namespace Skybound.VisualTips { [System.ComponentModel.ProvideProperty("VisualTip", typeof(System.Object))] [System.ComponentModel.DefaultEvent("AccessKeyPressed")] public class VisualTipProvider : System.ComponentModel.Component, System.ComponentModel.IExtenderProvider { private delegate void ShowTipCoreMethod(System.Windows.Forms.Control control, object component, Skybound.VisualTips.VisualTip tip, System.Drawing.Rectangle toolArea, Skybound.VisualTips.VisualTipDisplayOptions options); private class NotifyImages { public static readonly System.Drawing.Image Error; public static readonly System.Drawing.Image Information; public static readonly System.Drawing.Image Warning; static NotifyImages() { System.Reflection.Assembly assembly = typeof(Skybound.VisualTips.VisualTipProvider.NotifyImages).Assembly; System.Type type = typeof(Skybound.VisualTips.VisualTipProvider.NotifyImages); Skybound.VisualTips.VisualTipProvider.NotifyImages.Error = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream(type, "NotifyError.png")); Skybound.VisualTips.VisualTipProvider.NotifyImages.Warning = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream(type, "NotifyWarning.png")); Skybound.VisualTips.VisualTipProvider.NotifyImages.Information = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream(type, "NotifyInformation.png")); } public NotifyImages() { } public static System.Drawing.Image FromIcon(Skybound.VisualTips.VisualTipNotifyIcon icon) { switch (icon) { case Skybound.VisualTips.VisualTipNotifyIcon.Error: return Skybound.VisualTips.VisualTipProvider.NotifyImages.Error; case Skybound.VisualTips.VisualTipNotifyIcon.Warning: return Skybound.VisualTips.VisualTipProvider.NotifyImages.Warning; case Skybound.VisualTips.VisualTipNotifyIcon.Information: return Skybound.VisualTips.VisualTipProvider.NotifyImages.Information; } return null; } } // class NotifyImages private class StatusBarExtender : Skybound.VisualTips.IVisualTipExtender { private const int SB_GETRECT = 1034; public StatusBarExtender() { } public System.Drawing.Rectangle GetBounds(object component) { System.Windows.Forms.StatusBar statusBar = (component as System.Windows.Forms.StatusBarPanel).Parent; int[] iArr = new int[4]; Skybound.VisualTips.VisualTipProvider.StatusBarExtender.SendMessage(statusBar.Handle, 1034, new System.IntPtr(statusBar.Panels.IndexOf(component as System.Windows.Forms.StatusBarPanel)), iArr); return System.Drawing.Rectangle.FromLTRB(iArr[0], iArr[1], iArr[2], iArr[3]); } public object GetChildAtPoint(System.Windows.Forms.Control control, int x, int y) { object obj; System.Windows.Forms.StatusBar statusBar = control as System.Windows.Forms.StatusBar; System.Drawing.Size size = System.Windows.Forms.SystemInformation.Border3DSize; System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(size.Width, size.Height, 0, statusBar.Height - (size.Height * 2)); foreach (System.Windows.Forms.StatusBarPanel statusBarPanel in statusBar.Panels) { rectangle.Width = statusBarPanel.Width; if (rectangle.Contains(x, y)) { return statusBarPanel; } rectangle.X += rectangle.Width + size.Width; } return null; } public System.Type[] GetChildTypes() { return new System.Type[] { typeof(System.Windows.Forms.StatusBarPanel) }; } public object GetParent(object component) { return (component as System.Windows.Forms.StatusBarPanel).Parent; } [System.Runtime.InteropServices.PreserveSig] [System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] private static extern System.IntPtr SendMessage(System.IntPtr hwnd, int wMsg, System.IntPtr wParam, int[] lParam); } // class StatusBarExtender private class ToolBarExtender : Skybound.VisualTips.IVisualTipExtender { public ToolBarExtender() { } public System.Drawing.Rectangle GetBounds(object component) { return (component as System.Windows.Forms.ToolBarButton).Rectangle; } public object GetChildAtPoint(System.Windows.Forms.Control control, int x, int y) { object obj; System.Windows.Forms.ToolBar toolBar = control as System.Windows.Forms.ToolBar; foreach (System.Windows.Forms.ToolBarButton toolBarButton in toolBar.Buttons) { System.Drawing.Rectangle rectangle = toolBarButton.Rectangle; if (rectangle.Contains(x, y)) { return toolBarButton; } } return null; } public System.Type[] GetChildTypes() { return new System.Type[] { typeof(System.Windows.Forms.ToolBarButton) }; } public object GetParent(object component) { return (component as System.Windows.Forms.ToolBarButton).Parent; } } // class ToolBarExtender private class ToolStripExtender : Skybound.VisualTips.IVisualTipExtender { public ToolStripExtender() { } public System.Drawing.Rectangle GetBounds(object component) { return (System.Drawing.Rectangle)component.GetType().GetMethod("get_Bounds", System.Type.EmptyTypes).Invoke(component, null); } public object GetChildAtPoint(System.Windows.Forms.Control control, int x, int y) { System.Type[] typeArr = new System.Type[] { typeof(int), typeof(int) }; object[] objArr = new object[] { x, y }; return control.GetType().GetMethod("GetItemAt", typeArr).Invoke(control, objArr); } public System.Type[] GetChildTypes() { return new System.Type[] { Skybound.VisualTips.Version2Types.ToolStripItem }; } public object GetParent(object component) { return component.GetType().GetMethod("GetCurrentParent", System.Type.EmptyTypes).Invoke(component, null); } } // class ToolStripExtender internal class VisualTipWindowStack : System.Collections.ReadOnlyCollectionBase { private struct WindowStackItem { public System.Windows.Forms.Control Control; public Skybound.VisualTips.VisualTipWindow Window; } public VisualTipWindowStack() { } public void Add(Skybound.VisualTips.VisualTipWindow window, System.Windows.Forms.Control control) { Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack.WindowStackItem windowStackItem; UndisplayWindow(control); windowStackItem = new Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack.WindowStackItem(); windowStackItem.Window = window; windowStackItem.Control = control; InnerList.Add(windowStackItem); } public bool ProcessKeyDown(System.Windows.Forms.Keys key) { if (key == System.Windows.Forms.Keys.Escape) return UndisplayWindow(null); if (InnerList.Count > 0) { Skybound.VisualTips.VisualTip visualTip = ((Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack.WindowStackItem)InnerList[InnerList.Count - 1]).Window.DisplayedTip; if (((System.Windows.Forms.Shortcut)visualTip.AccessKey) == ((System.Windows.Forms.Shortcut)key)) { Skybound.VisualTips.VisualTipEventArgs visualTipEventArgs = new Skybound.VisualTips.VisualTipEventArgs(visualTip.Provider.CurrentTip, visualTip.Provider.CurrentComponent != null ? visualTip.Provider.CurrentComponent : visualTip.Provider.CurrentControl); UndisplayWindow(null); visualTip.Provider.OnAccessKeyPressed(visualTipEventArgs); return true; } } return false; } public void Remove(Skybound.VisualTips.VisualTipWindow window) { for (int i = InnerList.Count - 1; i >= 0; i--) { if (((Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack.WindowStackItem)InnerList[InnerList.Count - 1]).Window == window) { InnerList.RemoveAt(i); return; } } } private bool UndisplayWindow(System.Windows.Forms.Control control) { for (int i = InnerList.Count - 1; i >= 0; i--) { Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack.WindowStackItem windowStackItem = (Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack.WindowStackItem)InnerList[i]; if (windowStackItem.Window.IsDisplayed) { if ((control != null) && (windowStackItem.Control != control)) goto label_1; bool flag = (windowStackItem.Window.Options & Skybound.VisualTips.VisualTipDisplayOptions.ForwardEscapeKey) == Skybound.VisualTips.VisualTipDisplayOptions.Default; windowStackItem.Window.Undisplay(); return flag; } InnerList.RemoveAt(i); label_1:; } return false; } } // class VisualTipWindowStack private const System.Windows.Forms.Shortcut AccessKeyDefault = (System.Windows.Forms.Shortcut.Ins | System.Windows.Forms.Shortcut.CtrlB); private const int EM_POSFROMCHAR = 214; private System.Windows.Forms.Shortcut _AccessKey; private Skybound.VisualTips.VisualTipAnimation _Animation; private Skybound.VisualTips.VisualTip _CurrentTip; private string _DisabledMessage; private bool _DisplayAtMousePosition; private Skybound.VisualTips.VisualTipDisplayMode _DisplayMode; private Skybound.VisualTips.VisualTipDisplayPosition _DisplayPosition; private System.Drawing.Image _FooterImage; private string _FooterText; private int _InitialDelay; private int _MaximumWidth; private double _Opacity; private Skybound.VisualTips.Rendering.VisualTipRenderer _Renderer; private int _ReshowDelay; private Skybound.VisualTips.VisualTipShadow _Shadow; private bool _ShowAlways; private System.Drawing.Image _TitleImage; private object CurrentComponent; private System.Windows.Forms.Control CurrentControl; private Skybound.VisualTips.VisualTipWindow CurrentTipWindow; private System.Collections.Hashtable VisualTipMap; private static Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack _WindowStack; private static object DisplayModeChangedEvent; private static object DisplayPositionChangedEvent; private static System.Collections.Hashtable Extenders; private static System.Collections.ArrayList Instances; private static Skybound.VisualTips.VisualTipProvider NotifyProvider; private static Skybound.VisualTips.VisualTip PreventDisplayTip; private static object RendererChangedEvent; private static Skybound.VisualTips.VisualTipWindow TrackedTipWindow; [System.ComponentModel.Description("Occurs when the access key is pressed for a VisualTip.")] [System.ComponentModel.Category("Key")] public event Skybound.VisualTips.VisualTipEventHandler AccessKeyPressed; [System.ComponentModel.Category("Property Changed")] [System.ComponentModel.Description("Occurs when the value of the DisplayMode property is changed.")] public event System.EventHandler DisplayModeChanged { add { Events.AddHandler(Skybound.VisualTips.VisualTipProvider.DisplayModeChangedEvent, value); } remove { Events.RemoveHandler(Skybound.VisualTips.VisualTipProvider.DisplayModeChangedEvent, value); } } [System.ComponentModel.Description("Occurs when the value of the DisplayPosition property is changed.")] [System.ComponentModel.Category("Property Changed")] public event System.EventHandler DisplayPositionChanged { add { Events.AddHandler(Skybound.VisualTips.VisualTipProvider.DisplayPositionChangedEvent, value); } remove { Events.RemoveHandler(Skybound.VisualTips.VisualTipProvider.DisplayPositionChangedEvent, value); } } [System.ComponentModel.Description("Occurs when the value of the Renderer property is changed.")] [System.ComponentModel.Category("Property Changed")] public event System.EventHandler RendererChanged { add { Events.AddHandler(Skybound.VisualTips.VisualTipProvider.RendererChangedEvent, value); } remove { Events.RemoveHandler(Skybound.VisualTips.VisualTipProvider.RendererChangedEvent, value); } } [System.ComponentModel.Description("Occurs before a VisualTip is displayed.")] public event Skybound.VisualTips.VisualTipEventHandler TipPopup; [System.ComponentModel.Localizable(true)] [System.ComponentModel.Description("The keyboard shortcut that may be pressed to raise the AccessKeyPressed event when a tip is displayed.")] [System.ComponentModel.Category("Behavior")] public System.Windows.Forms.Shortcut AccessKey { get { if (!ShouldSerializeAccessKey()) { if (DisplayMode != Skybound.VisualTips.VisualTipDisplayMode.MouseHover) return System.Windows.Forms.Shortcut.None; return System.Windows.Forms.Shortcut.F1; } return _AccessKey; } set { _AccessKey = value; } } [System.ComponentModel.Category("Appearance")] [System.ComponentModel.Description("Determines if and how a VisualTip is animated when it is displayed.")] [System.ComponentModel.DefaultValue(Skybound.VisualTips.VisualTipAnimation.SystemDefault)] public Skybound.VisualTips.VisualTipAnimation Animation { get { return _Animation; } set { if (!System.Enum.IsDefined(typeof(Skybound.VisualTips.VisualTipAnimation), value)) throw new System.ComponentModel.InvalidEnumArgumentException("Animation", (int)value, typeof(Skybound.VisualTips.VisualTipAnimation)); _Animation = value; } } private Skybound.VisualTips.VisualTip CurrentTip { get { return _CurrentTip; } } [System.ComponentModel.Localizable(true)] [System.ComponentModel.Description("The title message written in bold above the text when the control is disabled.")] [System.ComponentModel.DefaultValue("")] [System.ComponentModel.Category("Appearance")] public string DisabledMessage { get { if (_DisabledMessage != null) return _DisabledMessage; return ""; } set { _DisabledMessage = value; } } [System.ComponentModel.Description("Whether VisualTips are displayed at the mouse position.")] [System.ComponentModel.Category("Behavior")] [System.ComponentModel.DefaultValue(true)] public bool DisplayAtMousePosition { get { return _DisplayAtMousePosition; } set { _DisplayAtMousePosition = value; } } [System.ComponentModel.Category("Behavior")] [System.ComponentModel.DefaultValue(Skybound.VisualTips.VisualTipDisplayMode.MouseHover)] [System.ComponentModel.Description("Determines when a visual tip is displayed.")] public Skybound.VisualTips.VisualTipDisplayMode DisplayMode { get { return _DisplayMode; } set { if (!System.Enum.IsDefined(typeof(Skybound.VisualTips.VisualTipDisplayMode), value)) throw new System.ComponentModel.InvalidEnumArgumentException("DisplayMode", (int)value, typeof(Skybound.VisualTips.VisualTipDisplayMode)); if (_DisplayMode != value) { _DisplayMode = value; foreach (Skybound.VisualTips.VisualTip visualTip in VisualTipMap.Values) { if (visualTip != null) visualTip.OnProviderDisplayModeChanged(System.EventArgs.Empty); } OnDisplayModeChanged(System.EventArgs.Empty); } } } [System.ComponentModel.DefaultValue(Skybound.VisualTips.VisualTipDisplayPosition.Bottom)] [System.ComponentModel.Description("Determines where a visual tip is displayed in relation to the tool area.")] [System.ComponentModel.Category("Behavior")] public Skybound.VisualTips.VisualTipDisplayPosition DisplayPosition { get { return _DisplayPosition; } set { if (!System.Enum.IsDefined(typeof(Skybound.VisualTips.VisualTipDisplayPosition), value)) throw new System.ComponentModel.InvalidEnumArgumentException("DisplayPosition", (int)value, typeof(Skybound.VisualTips.VisualTipDisplayPosition)); if (_DisplayPosition != value) { _DisplayPosition = value; OnDisplayPositionChanged(System.EventArgs.Empty); } } } [System.ComponentModel.Category("Appearance")] [System.ComponentModel.Localizable(true)] [System.ComponentModel.DefaultValue(null)] [System.ComponentModel.Editor(typeof(Skybound.Drawing.Design.IconImageEditor), typeof(System.Drawing.Design.UITypeEditor))] [System.ComponentModel.Description("The default image displayed beside the footer text on a VisualTip.")] public System.Drawing.Image FooterImage { get { return _FooterImage; } set { if ((value != null) && ((value.Width > 128) || (value.Height > 128))) throw new System.InvalidOperationException("The maximum image size is 128x128."); _FooterImage = value; } } [System.ComponentModel.Category("Appearance")] [System.ComponentModel.Localizable(true)] [System.ComponentModel.DefaultValue("")] [System.ComponentModel.Description("The default footer text on a VisualTip.")] public string FooterText { get { if (_FooterText != null) return _FooterText; return ""; } set { _FooterText = value; } } [System.ComponentModel.Category("Behavior")] [System.ComponentModel.Description("The amount of time which passes, in milliseconds, before a tip is displayed.")] public int InitialDelay { get { return _InitialDelay; } set { if (_InitialDelay != value) { Skybound.VisualTips.VisualTipTracker.RemoveHandler(_InitialDelay, new System.EventHandler(OnMouseHover)); _InitialDelay = value; Skybound.VisualTips.VisualTipTracker.AddHandler(_InitialDelay, new System.EventHandler(OnMouseHover)); } } } [System.ComponentModel.Browsable(false)] public bool IsTipDisplayed { get { if (CurrentTipWindow != null) return CurrentTipWindow.IsDisplayed; return false; } } [System.ComponentModel.Description("The maximum width of a VisualTip.")] [System.ComponentModel.DefaultValue(256)] [System.ComponentModel.Localizable(true)] [System.ComponentModel.Category("Appearance")] public int MaximumWidth { get { return _MaximumWidth; } set { _MaximumWidth = System.Math.Max(value, 192); } } [System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.OpacityConverter))] [System.ComponentModel.DefaultValue(0.94)] [System.ComponentModel.Description("The opacity level of the tip, ranging from 0% (transparent) to 100% (opaque).")] [System.ComponentModel.Category("Appearance")] public double Opacity { get { return _Opacity; } set { if (value < 0.0) value = 0.0; else if (value > 1.0) value = 1.0; _Opacity = value; } } [System.ComponentModel.Description("The renderer used to draw and measure a tip.")] [System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)] [System.ComponentModel.Category("Appearance")] public Skybound.VisualTips.Rendering.VisualTipRenderer Renderer { get { return _Renderer; } set { if (value == null) value = Skybound.VisualTips.Rendering.VisualTipRenderer.DefaultRenderer; if (_Renderer != value) { _Renderer = value; OnRendererChanged(System.EventArgs.Empty); } } } [System.ComponentModel.Category("Behavior")] [System.ComponentModel.Description("The amount of time which must pass, in milliseconds, before a tip is displayed when the mouse is moved from one component to another.")] public int ReshowDelay { get { return _ReshowDelay; } set { _ReshowDelay = value; } } [System.ComponentModel.DefaultValue(Skybound.VisualTips.VisualTipShadow.SystemDefault)] [System.ComponentModel.Description("Determines whether a VisualTip has a shadow.")] [System.ComponentModel.Category("Appearance")] public Skybound.VisualTips.VisualTipShadow Shadow { get { return _Shadow; } set { if (!System.Enum.IsDefined(typeof(Skybound.VisualTips.VisualTipShadow), value)) throw new System.ComponentModel.InvalidEnumArgumentException("Shadow", (int)value, typeof(Skybound.VisualTips.VisualTipShadow)); _Shadow = value; } } [System.ComponentModel.DefaultValue(false)] [System.ComponentModel.Category("Behavior")] [System.ComponentModel.Description("Whether VisualTips are displayed even when the form does not have the input focus.")] public bool ShowAlways { get { return _ShowAlways; } set { _ShowAlways = value; } } [System.ComponentModel.Editor(typeof(Skybound.Drawing.Design.IconImageEditor), typeof(System.Drawing.Design.UITypeEditor))] [System.ComponentModel.DefaultValue(null)] [System.ComponentModel.Category("Appearance")] [System.ComponentModel.Description("The image displayed beside the title of a visual tip which does not have another image assigned.")] [System.ComponentModel.Localizable(true)] public System.Drawing.Image TitleImage { get { return _TitleImage; } set { if ((value != null) && ((value.Width > 128) || (value.Height > 128))) throw new System.InvalidOperationException("The maximum image size is 128x128."); _TitleImage = value; } } public override System.ComponentModel.ISite Site { get { return base.Site; } set { if ((value != null) && value.DesignMode) RemoveInstance(); base.Site = value; } } internal static System.Windows.Forms.Control TrackedControl { get { if (Skybound.VisualTips.VisualTipTracker.TrackingProvider != null) return Skybound.VisualTips.VisualTipTracker.TrackingProvider.CurrentControl; return null; } } public static Skybound.VisualTips.VisualTip TrackedTip { get { if (Skybound.VisualTips.VisualTipTracker.TrackingProvider != null) return Skybound.VisualTips.VisualTipTracker.TrackingProvider.CurrentTip; return null; } } internal static Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack WindowStack { get { return Skybound.VisualTips.VisualTipProvider._WindowStack; } } public VisualTipProvider() { _Renderer = Skybound.VisualTips.Rendering.VisualTipRenderer.DefaultRenderer; _Opacity = 0.94; _MaximumWidth = 256; _AccessKey = System.Windows.Forms.Shortcut.Ins | System.Windows.Forms.Shortcut.CtrlB; _InitialDelay = System.Windows.Forms.SystemInformation.DoubleClickTime * 2; _ReshowDelay = System.Windows.Forms.SystemInformation.DoubleClickTime; _DisplayAtMousePosition = true; VisualTipMap = new System.Collections.Hashtable(); Skybound.VisualTips.VisualTipTracker.AddHandler(InitialDelay, new System.EventHandler(OnMouseHover)); Skybound.VisualTips.VisualTipProvider.Instances.Add(this); Skybound.VisualTips.VisualTipTracker.Enable(); } public VisualTipProvider(System.ComponentModel.IContainer container) { _Renderer = Skybound.VisualTips.Rendering.VisualTipRenderer.DefaultRenderer; _Opacity = 0.94; _MaximumWidth = 256; _AccessKey = System.Windows.Forms.Shortcut.Ins | System.Windows.Forms.Shortcut.CtrlB; _InitialDelay = System.Windows.Forms.SystemInformation.DoubleClickTime * 2; _ReshowDelay = System.Windows.Forms.SystemInformation.DoubleClickTime; _DisplayAtMousePosition = true; VisualTipMap = new System.Collections.Hashtable(); Skybound.VisualTips.VisualTipTracker.AddHandler(InitialDelay, new System.EventHandler(OnMouseHover)); Skybound.VisualTips.VisualTipProvider.Instances.Add(this); Skybound.VisualTips.VisualTipTracker.Enable(); if (container == null) throw new System.ArgumentNullException("container"); container.Add(this); } static VisualTipProvider() { Skybound.VisualTips.VisualTipProvider.Instances = new System.Collections.ArrayList(); Skybound.VisualTips.VisualTipProvider.Extenders = new System.Collections.Hashtable(); Skybound.VisualTips.VisualTipProvider.RendererChangedEvent = new System.Object(); Skybound.VisualTips.VisualTipProvider.DisplayModeChangedEvent = new System.Object(); Skybound.VisualTips.VisualTipProvider.DisplayPositionChangedEvent = new System.Object(); Skybound.VisualTips.VisualTipProvider._WindowStack = new Skybound.VisualTips.VisualTipProvider.VisualTipWindowStack(); Skybound.VisualTips.VisualTipProvider.SetExtender(typeof(System.Windows.Forms.ToolBar), new Skybound.VisualTips.VisualTipProvider.ToolBarExtender()); Skybound.VisualTips.VisualTipProvider.SetExtender(typeof(System.Windows.Forms.StatusBar), new Skybound.VisualTips.VisualTipProvider.StatusBarExtender()); if (System.Environment.Version.Major >= 2) Skybound.VisualTips.VisualTipProvider.SetExtender(Skybound.VisualTips.Version2Types.ToolStrip, new Skybound.VisualTips.VisualTipProvider.ToolStripExtender()); } public bool CanExtend(object extendee) { if (extendee == null) return false; System.Type type = extendee.GetType(); if (type.IsSubclassOf(typeof(System.Windows.Forms.Control))) return true; if (typeof(System.Windows.Forms.ToolBarButton).IsAssignableFrom(type)) return true; if (typeof(System.Windows.Forms.StatusBarPanel).IsAssignableFrom(type)) return true; if ((type.GetEvent("MouseEnter") == null) || (type.GetEvent("MouseLeave") == null)) return type.GetField("IsVisualTipComponent", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic) != null; return true; } private Skybound.VisualTips.VisualTip GetEffectiveVisualTip(System.Windows.Forms.Control control, object component) { Skybound.VisualTips.VisualTip visualTip = null; if (component != null) visualTip = VisualTipMap[component] as Skybound.VisualTips.VisualTip; if (visualTip == null) visualTip = VisualTipMap[control] as Skybound.VisualTips.VisualTip; if ((visualTip != null) && !visualTip.Active) visualTip = null; return visualTip; } private System.Drawing.Rectangle GetToolArea(System.Windows.Forms.Control control, object component) { System.Drawing.Rectangle rectangle = System.Drawing.Rectangle.Empty; if (!DisplayAtMousePosition) { if (component == null) { if (control is System.Windows.Forms.Form) { rectangle = System.Drawing.Rectangle.Empty; goto label_1; } return control.Parent.RectangleToScreen(control.Bounds); } Skybound.VisualTips.IVisualTipExtender ivisualTipExtender = Skybound.VisualTips.VisualTipProvider.GetExtender(control.GetType()); rectangle = ivisualTipExtender != null ? ivisualTipExtender.GetBounds(component) : System.Drawing.Rectangle.Empty; } label_1: if (rectangle != System.Drawing.Rectangle.Empty) return control.RectangleToScreen(rectangle); return new System.Drawing.Rectangle(System.Windows.Forms.Cursor.Position, new System.Drawing.Size(16, 16)); } [System.ComponentModel.Description("The VisualTip displayed when the mouse hovers over the current component.")] [System.ComponentModel.MergableProperty(false)] public Skybound.VisualTips.VisualTip GetVisualTip(object component) { Skybound.VisualTips.VisualTip visualTip = VisualTipMap[component] as Skybound.VisualTips.VisualTip; if (visualTip == null) { visualTip = new Skybound.VisualTips.VisualTip(); VisualTipMap[component] = new Skybound.VisualTips.VisualTip(); visualTip.SetProvider(this); Skybound.VisualTips.VisualTipProvider.UpdateTipTarget(visualTip, component); } return visualTip; } [System.ComponentModel.Description("All of the VisualTip.")] [System.ComponentModel.MergableProperty(false)] public Skybound.VisualTips.VisualTip[] GetVisualTips() { System.Collections.Generic.List<Skybound.VisualTips.VisualTip> list = new System.Collections.Generic.List<Skybound.VisualTips.VisualTip>(); foreach (object obj in VisualTipMap.Values) { list.Add((Skybound.VisualTips.VisualTip)obj); } return list.ToArray(); } private void HideShowTip(System.Windows.Forms.Control control) { control.MouseDown -= new System.Windows.Forms.MouseEventHandler(ShowTipControl_MouseDown); control.LostFocus -= new System.EventHandler(ShowTipControl_LostFocus); control.KeyDown -= new System.Windows.Forms.KeyEventHandler(ShowTipControl_KeyDown); control.KeyPress -= new System.Windows.Forms.KeyPressEventHandler(ShowTipControl_KeyPress); control.HandleDestroyed -= new System.EventHandler(ShowTipControl_HandleDestroyed); System.Windows.Forms.Form form = control.FindForm(); if (form != null) form.Deactivate -= new System.EventHandler(ShowTipControl_Form_Deactivate); if (CurrentControl == control) HideTip(); } public void HideTip() { if (CurrentTipWindow != null) CurrentTipWindow.Undisplay(); } internal void OnMouseHover(object sender, System.EventArgs e) { if ((DisplayMode == Skybound.VisualTips.VisualTipDisplayMode.MouseHover) && (CurrentTip == null)) { if ((Skybound.VisualTips.VisualTipTracker.TrackingProvider != null) && (Skybound.VisualTips.VisualTipTracker.TrackingProvider != this)) return; System.Windows.Forms.Control control = Skybound.VisualTips.VisualTipTracker.LastMouseEventControl; if ((control != null) && !control.IsDisposed) { System.Windows.Forms.Form form1 = System.Windows.Forms.Form.ActiveForm; if (form1 == null) return; if (!ShowAlways) { System.Windows.Forms.Form form2 = control.FindForm(); if ((form2 == null) || (form2 == form1) || (form2.IsMdiChild && (form2.MdiParent == form1) && (form2.MdiParent.ActiveMdiChild != form2))) return; } object obj = Skybound.VisualTips.VisualTipProvider.GetComponentAtPoint(control, control.PointToClient(System.Windows.Forms.Cursor.Position)); Skybound.VisualTips.VisualTip visualTip = GetEffectiveVisualTip(control, obj); if (visualTip != null) { if (visualTip == Skybound.VisualTips.VisualTipProvider.PreventDisplayTip) return; if (visualTip != CurrentTip) ShowTipCore(control, obj, visualTip, GetToolArea(control, obj), (Skybound.VisualTips.VisualTipDisplayOptions)(72 | (int)visualTip.DisplayPosition)); } } } } internal void OnUndisplay(Skybound.VisualTips.VisualTipWindow window) { if ((window == Skybound.VisualTips.VisualTipProvider.TrackedTipWindow) && (((Skybound.VisualTips.VisualTipProvider)Skybound.VisualTips.VisualTipTracker.TrackingProvider) == this)) Skybound.VisualTips.VisualTipTracker.TrackingProvider = null; _CurrentTip = null; CurrentControl = null; CurrentComponent = null; Skybound.VisualTips.VisualTipProvider.WindowStack.Remove(window); } private void RemoveInstance() { if (Skybound.VisualTips.VisualTipProvider.Instances.Contains(this)) { Skybound.VisualTips.VisualTipProvider.Instances.Remove(this); if (Skybound.VisualTips.VisualTipProvider.Instances.Count == 0) Skybound.VisualTips.VisualTipTracker.Disable(); } } private void ResetAccessKey() { _AccessKey = System.Windows.Forms.Shortcut.Ins | System.Windows.Forms.Shortcut.CtrlB; } private void ResetInitialDelay() { _InitialDelay = System.Windows.Forms.SystemInformation.DoubleClickTime * 2; } private void ResetRenderer() { Renderer = Skybound.VisualTips.Rendering.VisualTipRenderer.DefaultRenderer; } private void ResetReshowDelay() { _ReshowDelay = System.Windows.Forms.SystemInformation.DoubleClickTime; } private void ResetVisualTip(object component) { if (VisualTipMap.Contains(component)) GetVisualTip(component).Reset(); } public void SetVisualTip(object component, Skybound.VisualTips.VisualTip visualTip) { Skybound.VisualTips.VisualTip visualTip1 = VisualTipMap[component] as Skybound.VisualTips.VisualTip; if (visualTip1 != null) visualTip1.SetProvider(null); if ((visualTip != null) && (visualTip.Provider != null)) visualTip.Provider.SetVisualTip(component, null); VisualTipMap[component] = visualTip; if (visualTip != null) { visualTip.SetProvider(this); Skybound.VisualTips.VisualTipProvider.UpdateTipTarget(visualTip, component); } } private bool ShouldSerializeAccessKey() { return _AccessKey != (System.Windows.Forms.Shortcut.Ins | System.Windows.Forms.Shortcut.CtrlB); } private bool ShouldSerializeInitialDelay() { return _InitialDelay != (System.Windows.Forms.SystemInformation.DoubleClickTime * 2); } private bool ShouldSerializeRenderer() { return _Renderer != Skybound.VisualTips.Rendering.VisualTipRenderer.DefaultRenderer; } private bool ShouldSerializeReshowDelay() { return _ReshowDelay != System.Windows.Forms.SystemInformation.DoubleClickTime; } private bool ShouldSerializeVisualTip(object component) { if (!VisualTipMap.Contains(component)) return false; return GetVisualTip(component).ShouldSerialize(); } public void ShowTip(System.Windows.Forms.Control control, Skybound.VisualTips.VisualTipDisplayOptions options, System.Drawing.Rectangle exclude) { if (control == null) throw new System.ArgumentNullException("control"); Skybound.VisualTips.VisualTip visualTip = GetEffectiveVisualTip(control, null); if (visualTip != null) ShowTip(visualTip, exclude, control, options); } public void ShowTip(Skybound.VisualTips.VisualTip tip, System.Drawing.Rectangle exclude) { ShowTip(tip, exclude, null, (Skybound.VisualTips.VisualTipDisplayOptions)tip.DisplayPosition); } public void ShowTip(Skybound.VisualTips.VisualTip tip, System.Drawing.Rectangle exclude, System.Windows.Forms.Control sourceControl, Skybound.VisualTips.VisualTipDisplayOptions options) { if (tip == null) throw new System.ArgumentNullException("tip", "The tip parameter may not be null."); if ((sourceControl != null) && !sourceControl.IsDisposed) { if ((options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnKeyDown) == Skybound.VisualTips.VisualTipDisplayOptions.HideOnKeyDown) sourceControl.KeyDown += new System.Windows.Forms.KeyEventHandler(ShowTipControl_KeyDown); if ((options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnKeyPress) == Skybound.VisualTips.VisualTipDisplayOptions.HideOnKeyPress) sourceControl.KeyPress += new System.Windows.Forms.KeyPressEventHandler(ShowTipControl_KeyPress); if ((options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnLostFocus) == Skybound.VisualTips.VisualTipDisplayOptions.HideOnLostFocus) sourceControl.LostFocus += new System.EventHandler(ShowTipControl_LostFocus); if ((options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseDown) == Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseDown) sourceControl.MouseDown += new System.Windows.Forms.MouseEventHandler(ShowTipControl_MouseDown); if ((options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnTextChanged) == Skybound.VisualTips.VisualTipDisplayOptions.HideOnTextChanged) sourceControl.TextChanged += new System.EventHandler(ShowTipControl_TextChanged); sourceControl.HandleDestroyed += new System.EventHandler(ShowTipControl_HandleDestroyed); System.Windows.Forms.Form form = sourceControl.FindForm(); if (form != null) form.Deactivate += new System.EventHandler(ShowTipControl_Form_Deactivate); } ShowTipCore(sourceControl, null, tip, exclude, options); } public void ShowTip(System.Windows.Forms.Control control, Skybound.VisualTips.VisualTipDisplayOptions options) { if (control == null) throw new System.ArgumentNullException("control"); ShowTip(control, options, control.Parent == null ? control.Bounds : control.Parent.RectangleToScreen(control.Bounds)); } private void ShowTipControl_Form_Deactivate(object sender, System.EventArgs e) { if (CurrentControl != null) HideShowTip(CurrentControl); } private void ShowTipControl_HandleDestroyed(object sender, System.EventArgs e) { HideShowTip(sender as System.Windows.Forms.Control); } private void ShowTipControl_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { HideShowTip(sender as System.Windows.Forms.Control); } private void ShowTipControl_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { HideShowTip(sender as System.Windows.Forms.Control); } private void ShowTipControl_LostFocus(object sender, System.EventArgs e) { HideShowTip(sender as System.Windows.Forms.Control); } private void ShowTipControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { HideShowTip(sender as System.Windows.Forms.Control); } private void ShowTipControl_TextChanged(object sender, System.EventArgs e) { HideShowTip(sender as System.Windows.Forms.Control); } private void ShowTipCore(System.Windows.Forms.Control control, object component, Skybound.VisualTips.VisualTip tip, System.Drawing.Rectangle toolArea, Skybound.VisualTips.VisualTipDisplayOptions options) { if ((control != null) && control.InvokeRequired) { object[] objArr = new object[] { control, component, tip, toolArea, options }; control.BeginInvoke(new Skybound.VisualTips.VisualTipProvider.ShowTipCoreMethod(ShowTipCore), objArr); return; } bool flag = (options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseLeave) == Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseLeave; Skybound.VisualTips.VisualTipWindow visualTipWindow1 = flag ? Skybound.VisualTips.VisualTipProvider.TrackedTipWindow : CurrentTipWindow; if (visualTipWindow1 == null) { if (flag) { Skybound.VisualTips.VisualTipProvider.TrackedTipWindow = new Skybound.VisualTips.VisualTipWindow(); visualTipWindow1 = new Skybound.VisualTips.VisualTipWindow(); } else { Skybound.VisualTips.VisualTipWindow visualTipWindow2 = new Skybound.VisualTips.VisualTipWindow(); CurrentTipWindow = new Skybound.VisualTips.VisualTipWindow(); visualTipWindow1 = visualTipWindow2; } } if (visualTipWindow1.DisplayedTip != tip) { visualTipWindow1.Undisplay(); Skybound.VisualTips.VisualTipEventArgs visualTipEventArgs = new Skybound.VisualTips.VisualTipEventArgs(tip, component == null ? control : component); tip.SetProvider(this); Skybound.VisualTips.VisualTipProvider.UpdateTipTarget(tip, visualTipEventArgs.Instance); OnTipPopup(visualTipEventArgs); if (visualTipEventArgs.Cancel) { Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = tip; return; } _CurrentTip = tip; CurrentControl = control; CurrentComponent = component; if (flag) Skybound.VisualTips.VisualTipTracker.TrackingProvider = this; Skybound.VisualTips.VisualTipProvider.WindowStack.Add(visualTipWindow1, control); visualTipWindow1.Display(this, tip, toolArea, options); return; } visualTipWindow1.SetToolArea(toolArea, options); } internal void TrackKeyDown(System.Windows.Forms.KeyEventArgs e) { if (CurrentTip == null) return; if (e.KeyCode == System.Windows.Forms.Keys.Escape) { Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = CurrentTip; Skybound.VisualTips.VisualTipProvider.HideTrackedTip(); e.Handled = true; return; } if (((System.Windows.Forms.Shortcut)e.KeyCode) == ((System.Windows.Forms.Shortcut)CurrentTip.AccessKey)) { Skybound.VisualTips.VisualTipEventArgs visualTipEventArgs = new Skybound.VisualTips.VisualTipEventArgs(CurrentTip, CurrentComponent != null ? CurrentComponent : CurrentControl); Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = CurrentTip; Skybound.VisualTips.VisualTipProvider.HideTrackedTip(); e.Handled = true; OnAccessKeyPressed(visualTipEventArgs); } } internal void TrackMouseDownUp() { if ((Skybound.VisualTips.VisualTipProvider.TrackedTipWindow.Options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseDown) == Skybound.VisualTips.VisualTipDisplayOptions.Default) return; if (Skybound.VisualTips.VisualTipProvider.TrackedTip != null) Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = Skybound.VisualTips.VisualTipProvider.TrackedTip; Skybound.VisualTips.VisualTipProvider.HideTrackedTip(); } internal void TrackMouseLeave(System.EventArgs e) { if ((Skybound.VisualTips.VisualTipProvider.TrackedTipWindow.Options & Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseDown) == Skybound.VisualTips.VisualTipDisplayOptions.Default) return; System.Drawing.Rectangle rectangle = Skybound.VisualTips.VisualTipProvider.TrackedTipWindow.Bounds; if (rectangle.Contains(System.Windows.Forms.Cursor.Position)) { Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = CurrentTip; } else { Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = null; Skybound.VisualTips.VisualTipTracker.SetTimeoutHandler(ReshowDelay, new System.EventHandler(OnMouseHover)); } Skybound.VisualTips.VisualTipProvider.HideTrackedTip(); } internal void TrackMouseMove(System.Windows.Forms.MouseEventArgs e) { System.Windows.Forms.Control control = Skybound.VisualTips.VisualTipTracker.LastMouseEventControl; if (control != null) { Skybound.VisualTips.VisualTip visualTip = GetEffectiveVisualTip(control, Skybound.VisualTips.VisualTipProvider.GetComponentAtPoint(control, new System.Drawing.Point(e.X, e.Y))); if ((Skybound.VisualTips.VisualTipProvider.PreventDisplayTip != null) && (visualTip != Skybound.VisualTips.VisualTipProvider.PreventDisplayTip)) { Skybound.VisualTips.VisualTipProvider.PreventDisplayTip = null; return; } if (visualTip != CurrentTip) { Skybound.VisualTips.VisualTipTracker.SetTimeoutHandler(ReshowDelay, new System.EventHandler(OnMouseHover)); Skybound.VisualTips.VisualTipProvider.HideTrackedTip(); } } } protected override void Dispose(bool disposing) { Skybound.VisualTips.VisualTipTracker.RemoveHandler(InitialDelay, new System.EventHandler(OnMouseHover)); RemoveInstance(); base.Dispose(disposing); } protected virtual void OnAccessKeyPressed(Skybound.VisualTips.VisualTipEventArgs e) { if (AccessKeyPressed != null) AccessKeyPressed(this, e); } protected virtual void OnDisplayModeChanged(System.EventArgs e) { if (((System.EventHandler)Events[Skybound.VisualTips.VisualTipProvider.DisplayModeChangedEvent]) != null) ((System.EventHandler)Events[Skybound.VisualTips.VisualTipProvider.DisplayModeChangedEvent])(this, e); } protected virtual void OnDisplayPositionChanged(System.EventArgs e) { if (((System.EventHandler)Events[Skybound.VisualTips.VisualTipProvider.DisplayPositionChangedEvent]) != null) ((System.EventHandler)Events[Skybound.VisualTips.VisualTipProvider.DisplayPositionChangedEvent])(this, e); } protected virtual void OnRendererChanged(System.EventArgs e) { if (((System.EventHandler)Events[Skybound.VisualTips.VisualTipProvider.RendererChangedEvent]) != null) ((System.EventHandler)Events[Skybound.VisualTips.VisualTipProvider.RendererChangedEvent])(this, e); } protected virtual void OnTipPopup(Skybound.VisualTips.VisualTipEventArgs e) { if (TipPopup != null) TipPopup(this, e); } private static object GetComponentAtPoint(System.Windows.Forms.Control control, System.Drawing.Point point) { Skybound.VisualTips.IVisualTipExtender ivisualTipExtender = Skybound.VisualTips.VisualTipProvider.GetExtender(control.GetType()); object obj = ivisualTipExtender != null ? ivisualTipExtender.GetChildAtPoint(control, point.X, point.Y) : null; System.Windows.Forms.Control control1 = Skybound.VisualTips.VisualTipProvider.GetNestedChildAtPoint(control, control.PointToScreen(point)); if (control1 != control) return control1; return obj; } internal static Skybound.VisualTips.IVisualTipExtender GetExtender(System.Type controlOrComponentType) { Skybound.VisualTips.IVisualTipExtender ivisualTipExtender2; Skybound.VisualTips.IVisualTipExtender ivisualTipExtender1 = Skybound.VisualTips.VisualTipProvider.Extenders[controlOrComponentType] as Skybound.VisualTips.IVisualTipExtender; if (ivisualTipExtender1 == null) { System.Collections.IDictionaryEnumerator idictionaryEnumerator = Skybound.VisualTips.VisualTipProvider.Extenders.GetEnumerator(); try { while (idictionaryEnumerator.MoveNext()) { System.Collections.DictionaryEntry dictionaryEntry = (System.Collections.DictionaryEntry)idictionaryEnumerator.Current; if (controlOrComponentType.IsSubclassOf(dictionaryEntry.Key as System.Type)) { ivisualTipExtender2 = dictionaryEntry.Value as Skybound.VisualTips.IVisualTipExtender; return ivisualTipExtender2; } } } finally { System.IDisposable idisposable = idictionaryEnumerator as System.IDisposable; if (idisposable != null) idisposable.Dispose(); } } return ivisualTipExtender1; } private static System.Windows.Forms.Control GetNestedChildAtPoint(System.Windows.Forms.Control control, System.Drawing.Point screenPoint) { System.Windows.Forms.Control control1 = control.GetChildAtPoint(control.PointToClient(screenPoint), System.Windows.Forms.GetChildAtPointSkip.Invisible); if (control1 != null) return Skybound.VisualTips.VisualTipProvider.GetNestedChildAtPoint(control1, screenPoint); return control; } public static void HideTrackedTip() { if (Skybound.VisualTips.VisualTipProvider.TrackedTipWindow != null) Skybound.VisualTips.VisualTipProvider.TrackedTipWindow.Undisplay(); } public static void SetExtender(System.Type controlType, Skybound.VisualTips.IVisualTipExtender extender) { if (controlType == null) throw new System.ArgumentNullException("controlType"); if (extender == null) throw new System.ArgumentNullException("extender"); Skybound.VisualTips.VisualTipProvider.Extenders[controlType] = extender; System.Type[] typeArr1 = extender.GetChildTypes(); if (typeArr1 != null) { System.Type[] typeArr2 = typeArr1; for (int i = 0; i < typeArr2.Length; i++) { System.Type type = typeArr2[i]; Skybound.VisualTips.VisualTipProvider.Extenders[type] = extender; } } } [System.ComponentModel.Description] private static void SetExtender(System.Type controlType, object extender) { if (controlType == null) throw new System.ArgumentNullException("controlType"); if (extender == null) throw new System.ArgumentNullException("extender"); if (!Skybound.VisualTips.VisualTipExtenderAdapter.Validate(extender)) throw new System.ArgumentException("The object did not provide the required methods. Extenders must have 2 methods withthe following signatures:\r\n\r\nObject GetChildAtPoint(Control,Int32,Int32)\r\nObject GetParent(Object)", "extender"); Skybound.VisualTips.VisualTipProvider.SetExtender(controlType, new Skybound.VisualTips.VisualTipExtenderAdapter(extender)); } public static void ShowNotifyTip(System.Windows.Forms.Control control, string text, string title, Skybound.VisualTips.VisualTipNotifyIcon icon, Skybound.VisualTips.VisualTipDisplayOptions options) { if (control == null) throw new System.ArgumentNullException("control"); Skybound.VisualTips.VisualTipProvider.ShowNotifyTip(control, text, title, icon, options, control.Parent == null ? control.Bounds : control.Parent.RectangleToScreen(control.Bounds)); } public static void ShowNotifyTip(System.Windows.Forms.TextBox textBox, string text, string title, Skybound.VisualTips.VisualTipNotifyIcon icon, int charIndex) { if ((textBox == null) || textBox.IsDisposed) throw new System.ArgumentNullException("textBox", "textBox may not be null or disposed."); if ((charIndex < 0) || (charIndex > textBox.TextLength)) throw new System.ArgumentNullException("charIndex", "charIndex may not be less than zero or greater than the length of the TextBox text."); if (charIndex == textBox.TextLength) charIndex = System.Math.Max(charIndex - 1, 0); System.IntPtr intPtr = Skybound.VisualTips.VisualTipProvider.SendMessage(textBox.Handle, 214, new System.IntPtr(System.Math.Max(charIndex, 0)), System.IntPtr.Zero); int i = intPtr.ToInt32(); System.Drawing.Point point = textBox.PointToScreen(new System.Drawing.Point(i)); System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(point, new System.Drawing.Size(1, textBox.Font.Height)); Skybound.VisualTips.VisualTipProvider.ShowNotifyTip(textBox, text, title, icon, Skybound.VisualTips.VisualTipDisplayOptions.HideOnKeyPress | Skybound.VisualTips.VisualTipDisplayOptions.HideOnLostFocus, rectangle); } public static void ShowNotifyTip(System.Windows.Forms.Control control, string text, string title, Skybound.VisualTips.VisualTipNotifyIcon icon, Skybound.VisualTips.VisualTipDisplayOptions options, System.Drawing.Rectangle exclude) { if (control == null) throw new System.ArgumentNullException("control"); if (control.IsDisposed) throw new System.ArgumentOutOfRangeException("control", control, "A tip may not be displayed for a control which has already been disposed."); if (Skybound.VisualTips.VisualTipProvider.NotifyProvider == null) { Skybound.VisualTips.VisualTipProvider.NotifyProvider = new Skybound.VisualTips.VisualTipProvider(); Skybound.VisualTips.VisualTipProvider.NotifyProvider.Renderer = new Skybound.VisualTips.Rendering.VisualTipBalloonRenderer(); } exclude.X = exclude.X - 12; Skybound.VisualTips.VisualTip visualTip = new Skybound.VisualTips.VisualTip(text, title); visualTip.TitleImage = Skybound.VisualTips.VisualTipProvider.NotifyImages.FromIcon(icon); Skybound.VisualTips.VisualTipProvider.NotifyProvider.ShowTip(visualTip, exclude, control, options); } public static void ShowNotifyTip(System.Windows.Forms.Control control, string text, string title, Skybound.VisualTips.VisualTipNotifyIcon icon, System.Drawing.Rectangle exclude) { Skybound.VisualTips.VisualTipProvider.ShowNotifyTip(control, text, title, icon, Skybound.VisualTips.VisualTipDisplayOptions.Default, exclude); } public static void ShowNotifyTip(System.Windows.Forms.Control control, string text, string title) { Skybound.VisualTips.VisualTipProvider.ShowNotifyTip(control, text, title, Skybound.VisualTips.VisualTipNotifyIcon.None, Skybound.VisualTips.VisualTipDisplayOptions.Default); } public static void ShowNotifyTip(System.Windows.Forms.Control control, string text, string title, Skybound.VisualTips.VisualTipNotifyIcon icon) { Skybound.VisualTips.VisualTipProvider.ShowNotifyTip(control, text, title, icon, Skybound.VisualTips.VisualTipDisplayOptions.Default); } private static void UpdateTipTarget(Skybound.VisualTips.VisualTip tip, object component) { if (component == null) { tip.SetTarget(null, null); return; } if ((component is System.Windows.Forms.Control)) { tip.SetTarget(component as System.Windows.Forms.Control, null); return; } Skybound.VisualTips.IVisualTipExtender ivisualTipExtender = Skybound.VisualTips.VisualTipProvider.GetExtender(component.GetType()); if (ivisualTipExtender != null) { tip.SetTarget(ivisualTipExtender.GetParent(component) as System.Windows.Forms.Control, component); return; } tip.SetTarget(null, component); } [System.Runtime.InteropServices.PreserveSig] [System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern System.IntPtr SendMessage(System.IntPtr hWnd, int wMsg, System.IntPtr wParam, System.IntPtr lParam); } // class VisualTipProvider }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Contract ///<para>SObject Name: Contract</para> ///<para>Custom Object: False</para> ///</summary> public class SfContract : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "Contract"; } } ///<summary> /// Contract ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Account ID /// <para>Name: AccountId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "accountId")] public string AccountId { get; set; } ///<summary> /// ReferenceTo: Account /// <para>RelationshipName: Account</para> ///</summary> [JsonProperty(PropertyName = "account")] [Updateable(false), Createable(false)] public SfAccount Account { get; set; } ///<summary> /// Price Book ID /// <para>Name: Pricebook2Id</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "pricebook2Id")] public string Pricebook2Id { get; set; } ///<summary> /// ReferenceTo: Pricebook2 /// <para>RelationshipName: Pricebook2</para> ///</summary> [JsonProperty(PropertyName = "pricebook2")] [Updateable(false), Createable(false)] public SfPricebook2 Pricebook2 { get; set; } ///<summary> /// Owner Expiration Notice /// <para>Name: OwnerExpirationNotice</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "ownerExpirationNotice")] public string OwnerExpirationNotice { get; set; } ///<summary> /// Contract Start Date /// <para>Name: StartDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "startDate")] public DateTime? StartDate { get; set; } ///<summary> /// Contract End Date /// <para>Name: EndDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "endDate")] [Updateable(false), Createable(false)] public DateTime? EndDate { get; set; } ///<summary> /// Billing Street /// <para>Name: BillingStreet</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingStreet")] public string BillingStreet { get; set; } ///<summary> /// Billing City /// <para>Name: BillingCity</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingCity")] public string BillingCity { get; set; } ///<summary> /// Billing State/Province /// <para>Name: BillingState</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingState")] public string BillingState { get; set; } ///<summary> /// Billing Zip/Postal Code /// <para>Name: BillingPostalCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingPostalCode")] public string BillingPostalCode { get; set; } ///<summary> /// Billing Country /// <para>Name: BillingCountry</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingCountry")] public string BillingCountry { get; set; } ///<summary> /// Billing Latitude /// <para>Name: BillingLatitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingLatitude")] public double? BillingLatitude { get; set; } ///<summary> /// Billing Longitude /// <para>Name: BillingLongitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingLongitude")] public double? BillingLongitude { get; set; } ///<summary> /// Billing Geocode Accuracy /// <para>Name: BillingGeocodeAccuracy</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingGeocodeAccuracy")] public string BillingGeocodeAccuracy { get; set; } ///<summary> /// Billing Address /// <para>Name: BillingAddress</para> /// <para>SF Type: address</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingAddress")] [Updateable(false), Createable(false)] public Address BillingAddress { get; set; } ///<summary> /// Contract Term /// <para>Name: ContractTerm</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "contractTerm")] public int? ContractTerm { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: Owner</para> ///</summary> [JsonProperty(PropertyName = "owner")] [Updateable(false), Createable(false)] public SfUser Owner { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } ///<summary> /// Company Signed By ID /// <para>Name: CompanySignedId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "companySignedId")] public string CompanySignedId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CompanySigned</para> ///</summary> [JsonProperty(PropertyName = "companySigned")] [Updateable(false), Createable(false)] public SfUser CompanySigned { get; set; } ///<summary> /// Company Signed Date /// <para>Name: CompanySignedDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "companySignedDate")] public DateTime? CompanySignedDate { get; set; } ///<summary> /// Customer Signed By ID /// <para>Name: CustomerSignedId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "customerSignedId")] public string CustomerSignedId { get; set; } ///<summary> /// ReferenceTo: Contact /// <para>RelationshipName: CustomerSigned</para> ///</summary> [JsonProperty(PropertyName = "customerSigned")] [Updateable(false), Createable(false)] public SfContact CustomerSigned { get; set; } ///<summary> /// Customer Signed Title /// <para>Name: CustomerSignedTitle</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "customerSignedTitle")] public string CustomerSignedTitle { get; set; } ///<summary> /// Customer Signed Date /// <para>Name: CustomerSignedDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "customerSignedDate")] public DateTime? CustomerSignedDate { get; set; } ///<summary> /// Special Terms /// <para>Name: SpecialTerms</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "specialTerms")] public string SpecialTerms { get; set; } ///<summary> /// Activated By ID /// <para>Name: ActivatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "activatedById")] [Updateable(true), Createable(false)] public string ActivatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: ActivatedBy</para> ///</summary> [JsonProperty(PropertyName = "activatedBy")] [Updateable(false), Createable(false)] public SfUser ActivatedBy { get; set; } ///<summary> /// Activated Date /// <para>Name: ActivatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "activatedDate")] [Updateable(true), Createable(false)] public DateTimeOffset? ActivatedDate { get; set; } ///<summary> /// Status Category /// <para>Name: StatusCode</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "statusCode")] [Updateable(false), Createable(false)] public string StatusCode { get; set; } ///<summary> /// Description /// <para>Name: Description</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Contract Number /// <para>Name: ContractNumber</para> /// <para>SF Type: string</para> /// <para>AutoNumber field</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "contractNumber")] [Updateable(false), Createable(false)] public string ContractNumber { get; set; } ///<summary> /// Last Approved Date /// <para>Name: LastApprovedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastApprovedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastApprovedDate { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Last Activity /// <para>Name: LastActivityDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastActivityDate")] [Updateable(false), Createable(false)] public DateTime? LastActivityDate { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } } }
//--------------------------------------------------------------------------- // // <copyright file="XpsFilter.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implements indexing filter for XPS documents, // which could be Package or EncryptedPackageEnvelope. // Uses PackageFilter or EncryptedPackageFilter accordingly. // // History: // 07/18/2005: ArindamB: Initial implementation, which also has relevant // code moved from previous implementation of // ContainerFilterImpl and IndexingFilterMarshaler. //--------------------------------------------------------------------------- using System; using System.IO; using System.IO.Packaging; using System.Diagnostics; // For Assert using System.Runtime.InteropServices; // For Marshal.ThrowExceptionForHR using System.Globalization; // For CultureInfo using System.Windows; // for ExceptionStringTable using System.Security; // For SecurityCritical using MS.Win32; using MS.Internal.Interop; // For STAT_CHUNK, etc. using MS.Internal.IO.Packaging; // For ManagedIStream using MS.Internal; namespace MS.Internal.IO.Packaging { #region XpsFilter /// <summary> /// Implements IFilter, IPersistFile and IPersistStream methods /// to support indexing on XPS files. /// </summary> [ComVisible(true)] [StructLayout(LayoutKind.Sequential, Pack = 0)] [Guid("0B8732A6-AF74-498c-A251-9DC86B0538B0")] internal sealed class XpsFilter : IFilter, IPersistFile, IPersistStream { #region IFilter methods /// <summary> /// Initialzes the session for this filter. /// </summary> /// <param name="grfFlags">usage flags</param> /// <param name="cAttributes">number of elements in aAttributes array</param> /// <param name="aAttributes">array of FULLPROPSPEC structs to restrict responses</param> /// <returns> /// IFILTER_FLAGS_NONE to indicate that the caller should not use the IPropertySetStorage /// and IPropertyStorage interfaces to locate additional properties. /// </returns> IFILTER_FLAGS IFilter.Init( [In] IFILTER_INIT grfFlags, [In] uint cAttributes, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] FULLPROPSPEC[] aAttributes) { if (_filter == null) { throw new COMException(SR.Get(SRID.FileToFilterNotLoaded), (int)NativeMethods.E_FAIL); } if (cAttributes > 0 && aAttributes == null) { // Attributes count and array do not match. throw new COMException(SR.Get(SRID.FilterInitInvalidAttributes), (int)NativeMethods.E_INVALIDARG); } return _filter.Init(grfFlags, cAttributes, aAttributes); } /// <summary> /// Returns description of the next chunk. /// </summary> /// <returns>Chunk descriptor</returns> STAT_CHUNK IFilter.GetChunk() { if (_filter == null) { throw new COMException(SR.Get(SRID.FileToFilterNotLoaded), (int)FilterErrorCode.FILTER_E_ACCESS); } try { return _filter.GetChunk(); } catch (COMException ex) { // End-of-data? If so, release the package. if (ex.ErrorCode == (int)FilterErrorCode.FILTER_E_END_OF_CHUNKS) ReleaseResources(); throw ex; } } /// <summary> /// Gets text content corresponding to current chunk. /// </summary> /// <param name="bufCharacterCount">size of buffer in characters</param> /// <param name="pBuffer">buffer pointer</param> /// <remarks>Supported for indexing content of Package.</remarks> /// <SecurityNote> /// Critical - Calling Marshal.WriteInt16, which has a LinkDemand. It takes an input /// pointer to write to. To be safe, the caller cannot be in Partial Trust. /// This method is Internal. Not to be called from PT code. /// Not designed to be accessible from public surface at all. Invoked (indirectly) by unmanaged client code. /// </SecurityNote> [SecurityCritical] void IFilter.GetText(ref uint bufCharacterCount, IntPtr pBuffer) { if (_filter == null) { throw new COMException(SR.Get(SRID.FileToFilterNotLoaded), (int)FilterErrorCode.FILTER_E_ACCESS); } // NULL is not an acceptable value for pBuffer if (pBuffer == IntPtr.Zero) { throw new NullReferenceException(SR.Get(SRID.FilterNullGetTextBufferPointer)); } // If there is 0 byte to write, this is a no-op. if (bufCharacterCount == 0) { return; } // Because we should always return the string with null terminator, a buffer size // of one character can hold the null terminator only, we can always write the // terminator to the buffer and return directly. if (bufCharacterCount == 1) { Marshal.WriteInt16(pBuffer, 0); return; } // Record the original buffer size. bufCharacterCount may be changed later. // The original buffer size will be used to identify a special // case later. uint origianlBufferSize = bufCharacterCount; // Normalize the buffer size, for a very large size could be due to a bug or an attempted attack. if (bufCharacterCount > _maxTextBufferSizeInCharacters) { bufCharacterCount = _maxTextBufferSizeInCharacters; } // Memorize the buffer size. // We need to reserve a character for the terminator because we don't know // whether the underlying layer will take care of it. uint maxSpaceForContent = --bufCharacterCount; // Retrieve the result and its size. _filter.GetText(ref bufCharacterCount, pBuffer); // An increase in the in/out size parameter would be anomalous, and could be ill-intentioned. if (bufCharacterCount > maxSpaceForContent) { throw new COMException(SR.Get(SRID.AuxiliaryFilterReturnedAnomalousCountOfCharacters), (int)FilterErrorCode.FILTER_E_ACCESS); } // We need to handle a tricky case if the input buffer size is 2 characters. // // In this case, we actually request 1 character from the underlying layer // because we always reserve one character for the terminator. // // There are two possible scenarios for the returned character in the buffer: // 1. If the underlying layer will pad the returning string // with the null terminator, then the returned character in the buffer is null. // In this case we cannot return anything useful to the user, which is not expected. // What the users would expect is getting a string with one character // and one null terminator when passing a buffer with size of 2 characters to us. // 2. If the underlying layer will NOT pad the returning string // with the null terminator, then we have a useful character returned. // Then we pad the buffer with string terminator null, and give back to the user. // This case meets the users' expectation. // // So we need to discover the behavior of the underlying layer and act properly. // Following is a solution: // 1. Check the returned character in the buffer. // If it's a null, then we have scenario 1. Goto step 2. // If it's not a null, then we have scenario 2. Goto step 3. // 2. Call the underlying layer's GetText() again, but passing buffer size of 2. // 3. Pad the buffer with null string terminator and return. if (origianlBufferSize == 2) { short shCharacter = Marshal.ReadInt16(pBuffer); if (shCharacter == '\0') { // Scenario 1. Call underlying layer again with the actual buffer size. bufCharacterCount = 2; _filter.GetText(ref bufCharacterCount, pBuffer); // An increase in the in/out size parameter would be anomalous, and could be ill-intentioned. if (bufCharacterCount > 2) { throw new COMException(SR.Get(SRID.AuxiliaryFilterReturnedAnomalousCountOfCharacters), (int)FilterErrorCode.FILTER_E_ACCESS); } if (bufCharacterCount == 2) { // If the underlying layer GetText() returns 2 characters, we need to check // whether the second character is null. If it's not, then its behavior // does not match the scenario 1, we cannot handle it. shCharacter = Marshal.ReadInt16(pBuffer, _int16Size); // We don't throw exception because such a behavior violation is not acceptable. // We'd better terminate the entire process. Invariant.Assert(shCharacter == '\0'); // Then we adjust the point where we should put our null terminator. bufCharacterCount = 1; } // If the underlying layer GetText() returns 0 or 1 character, we // don't need to do anything. } } // If the buffer size is bigger than 2, then we don't care the behavior of the // underlying layer. The string buffer we return may contain 2 null terminators // if the underlying layer also pads the terminator. But there will be at least one // non-null character in the buffer if there is any text to get. So the users will get // something useful. // // One possible proposal is to generalize the special case: why not make the returned // string more uniform, in which there is only one terminator always? We discussed this // proposal. To achieve this, we must know the behavior of the underlying layer. // We need to call the underlying layer twice. // The first call is to request for one character to test the behavior. // If the returned character is null, then the underlying // layer is a conforming filter, which will pad a null terminator for the string it // returns. Otherwise, the underlying layer is non-conforming. // // Suppose the input buffer size is N, then if underlying layer is conforming, we make // a second call to it requesting for N characters. Then we can return. // // If the underlying layer is non-conforming, things are tricky. // First, the character returned // by the first call is useful and we cannot discard it. We should let it sit at the // beginning of the input buffer. So when we make the second call requesting for (N-2) // charaters, we have to use a temporary buffer. The reason is: the input buffer is // specified as an IntPtr. We cannot change its offset like a pointer without using // unsafe context, which we want to avoid. So we need to copy the characters in the // temporary buffer to the input buffer when the call returns, which might be expensive. // // Second, a side effect of making 2 calls to the underlying layer // is the second call may trigger a FILTER_E_NO_MORE_TEXT exception if the first call // exhausts all texts in the stream. We need to catch this exception, otherwise the COM // will catch it and return an error HRESULT to the user, which sould not happen. So, // we need to add a try-catch block for the second call to the non-conforming underlying // layer, which is expensive. // // Given the overheads that can incur, we dropped this idea eventhough it provides a // cleaner string format returned to the user. If the filter interface requires // the underlying filter to provide a property field indicating its behavior, then // we can implement this idea much cheaper. // Make sure the returned buffer always contains a terminating zero. // Note the conversion of uint to int involves no risk of an arithmetic overflow thanks // to the truncations performed above. // Provided pBuffer points to a buffer of size the minimum of _maxTextBufferSizeInCharacters // and the initial value of bufCharacterCount, the following write occurs within range. Marshal.WriteInt16(pBuffer, (int)bufCharacterCount * _int16Size, 0); // Count the terminator in the size that is returned. bufCharacterCount++; } /// <summary> /// Gets the property value corresponding to current chunk. /// </summary> /// <returns>property value</returns> /// <remarks> /// Supported for indexing core properties /// for Package and EncryptedPackageEnvelope. /// </remarks> IntPtr IFilter.GetValue() { if (_filter == null) { throw new COMException(SR.Get(SRID.FileToFilterNotLoaded), (int)FilterErrorCode.FILTER_E_ACCESS); } return _filter.GetValue(); } /// <summary> /// Retrieves an interface representing the specified portion of the object. /// </summary> /// <param name="origPos"></param> /// <param name="riid"></param> /// <returns>Not implemented. Reserved for future use.</returns> IntPtr IFilter.BindRegion([In] FILTERREGION origPos, [In] ref Guid riid) { // The following exception maps to E_NOTIMPL. throw new NotImplementedException(SR.Get(SRID.FilterBindRegionNotImplemented)); } #endregion IFilter methods #region IPersistFile methods /// <summary> /// Return the CLSID for the XAML filtering component. /// </summary> /// <param name="pClassID">On successful return, a reference to the CLSID.</param> void IPersistFile.GetClassID(out Guid pClassID) { pClassID = _filterClsid; } /// <summary> /// Return the path to the current working file or the file prompt ("*.xps"). /// </summary> [PreserveSig] int IPersistFile.GetCurFile(out string ppszFileName) { ppszFileName = null; if (_filter == null || _xpsFileName == null) { ppszFileName = "*." + PackagingUtilities.ContainerFileExtension; return NativeMethods.S_FALSE; } ppszFileName = _xpsFileName; return NativeMethods.S_OK; } /// <summary> /// Checks an object for changes since it was last saved to its current file. /// </summary> /// <returns> /// S_OK if the file has changed since it was last saved; /// S_FALSE if the file has not changed since it was last saved. /// </returns> /// <remarks> /// Since the file is accessed only for reading, this function always returns S_FALSE. /// </remarks> [PreserveSig] int IPersistFile.IsDirty() { return NativeMethods.S_FALSE; } /// <summary> /// Opens the specified file with the specified mode.. /// This can return any of the STG_E_* error codes, along /// with S_OK, E_OUTOFMEMORY, and E_FAIL. /// </summary> /// <param name="pszFileName"> /// A zero-terminated string containing the absolute path of the file to open. /// </param> /// <param name="dwMode">The mode in which to open pszFileName. </param> void IPersistFile.Load(string pszFileName, int dwMode) { FileMode fileMode; FileAccess fileAccess; FileShare fileSharing; // Check argument. if (pszFileName == null || pszFileName == String.Empty) { throw new ArgumentException(SR.Get(SRID.FileNameNullOrEmpty), "pszFileName"); } // Convert mode information in flag. switch ((STGM_FLAGS)(dwMode & (int)STGM_FLAGS.MODE)) { case STGM_FLAGS.CREATE: throw new ArgumentException(SR.Get(SRID.FilterLoadInvalidModeFlag), "dwMode"); default: fileMode = FileMode.Open; break; } // Convert access flag. switch ((STGM_FLAGS)(dwMode & (int)STGM_FLAGS.ACCESS)) { case STGM_FLAGS.READ: case STGM_FLAGS.READWRITE: fileAccess = FileAccess.Read; break; default: throw new ArgumentException(SR.Get(SRID.FilterLoadInvalidModeFlag), "dwMode"); } // Sharing flags are ignored. Since managed filters do not have the equivalent // of a destructor to release locks on files as soon as they get disposed of from // unmanaged code, the option taken is not to lock at all while filtering. // (See call to FileToStream further down.) fileSharing = FileShare.ReadWrite; // Only one of _package and _encryptedPackage can be non-null at a time. Invariant.Assert(_package == null || _encryptedPackage == null); // If there has been a previous call to Load, reinitialize everything. // Note closing a closed stream does not cause any exception. ReleaseResources(); _filter = null; _xpsFileName = null; bool encrypted = EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(pszFileName); try { // opens to MemoryStream or just returns FileStream if file exceeds _maxMemoryStreamBuffer _packageStream = FileToStream(pszFileName, fileMode, fileAccess, fileSharing, _maxMemoryStreamBuffer); if (encrypted) { // Open the encrypted package. _encryptedPackage = EncryptedPackageEnvelope.Open(_packageStream); _filter = new EncryptedPackageFilter(_encryptedPackage); } else { // Open the package. _package = Package.Open(_packageStream); _filter = new PackageFilter(_package); } } catch (IOException ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_ACCESS); } catch (FileFormatException ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_UNKNOWNFORMAT); } finally { // failure? if (_filter == null) { // clean up ReleaseResources(); } } _xpsFileName = pszFileName; } /// <summary> /// Saves a copy of the object into the specified file. /// </summary> /// <param name="pszFileName"> /// A zero-terminated string containing the absolute path /// of the file to which the object is saved. /// </param> /// <param name="fRemember"> /// Indicates whether pszFileName is to be used as the current working file. /// </param> /// <remarks> /// On the odd chance that this link is still valid when it's needed, /// expected error codes are described at /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/da9581e8-98c7-4592-8ee1-a1bc8232635b.asp /// </remarks> void IPersistFile.Save(string pszFileName, bool fRemember) { throw new COMException(SR.Get(SRID.FilterIPersistFileIsReadOnly), NativeMethods.STG_E_CANTSAVE); } /// <summary> /// Notifies the object that it can write to its file. /// </summary> /// <param name="pszFileName"> /// The absolute path of the file where the object was previously saved. /// </param> /// <remarks> /// On the odd chance that this link is still valid when it's needed, /// expected error codes are described at /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/da9581e8-98c7-4592-8ee1-a1bc8232635b.asp /// This function should always return S_OK when Save is not supported. /// </remarks> void IPersistFile.SaveCompleted(string pszFileName) { return; // return S_OK } #endregion IPersistFile methods #region IPersistStream methods /// <summary> /// Return the CLSID for the XAML filtering component. /// </summary> /// <param name="pClassID">On successful return, a reference to the CLSID.</param> void IPersistStream.GetClassID(out Guid pClassID) { pClassID = _filterClsid; } /// <summary> /// Checks an object for changes since it was last saved to its current file. /// </summary> /// <returns> /// S_OK if the file has changed since it was last saved; /// S_FALSE if the file has not changed since it was last saved. /// </returns> /// <remarks> /// Since the file is accessed only for reading, this function always returns S_FALSE. /// </remarks> [PreserveSig] int IPersistStream.IsDirty() { return NativeMethods.S_FALSE; } /// <summary> /// Retrieve the container on the specified IStream. /// </summary> /// <param name="stream">The OLE stream from which the container's contents are to be read.</param> /// <remarks> /// The interface implemented by 'stream' is defined in /// MS.Internal.Interop.IStream rather than the standard /// managed so as to allow optimized marshaling in UnsafeIndexingFilterStream. /// </remarks> /// <SecurityNote> /// Critical: This method accesses a class - UnsafeIndexingFilterStream which calls into /// unmanaged code which provides a managed Stream like interface for an /// unmanaged OLE IStream. /// This method is only called by unmanaged callers. /// There is no elevation of privilege in this method. /// </SecurityNote> [SecurityCritical] void IPersistStream.Load(MS.Internal.Interop.IStream stream) { // Check argument. if (stream == null) { throw new ArgumentNullException("stream"); } // Only one of _package and _encryptedPackage can be non-null at a time. Invariant.Assert(_package == null || _encryptedPackage == null); // If there has been a previous call to Load, reinitialize everything. // Note closing a closed stream does not cause any exception. ReleaseResources(); _filter = null; _xpsFileName = null; try { _packageStream = new UnsafeIndexingFilterStream(stream); // different filter for encrypted package if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(_packageStream)) { // Open the encrypted package. _encryptedPackage = EncryptedPackageEnvelope.Open(_packageStream); _filter = new EncryptedPackageFilter(_encryptedPackage); } else { // Open the package. _package = Package.Open(_packageStream); _filter = new PackageFilter(_package); } } catch (IOException ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_ACCESS); } catch (Exception ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_UNKNOWNFORMAT); } finally { // clean-up if we failed if (_filter == null) { ReleaseResources(); } } } /// <summary> /// Saves a copy of the object into the specified stream. /// </summary> /// <param name="stream">The stream to which the object is saved. </param> /// <param name="fClearDirty">Indicates whether the dirty state is to be cleared. </param> /// <remarks> /// Expected error codes are described at /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/b748b4f9-ef9c-486b-bdc4-4d23c4640ff7.asp /// </remarks> void IPersistStream.Save(MS.Internal.Interop.IStream stream, bool fClearDirty) { throw new COMException(SR.Get(SRID.FilterIPersistStreamIsReadOnly), NativeMethods.STG_E_CANTSAVE); } /// <summary> /// The purpose of this function when implemented by a persistent object is to return /// the size in bytes of the stream needed to save the object. /// Always returns COR_E_NOTSUPPORTED insofar as the filter does not use this interface for persistence. /// </summary> void IPersistStream.GetSizeMax(out Int64 pcbSize) { throw new NotSupportedException(SR.Get(SRID.FilterIPersistFileIsReadOnly)); } #endregion IPersistStream methods #region Private methods /// <summary> /// Shared implementation for releasing package/encryptedPackage and underlying stream /// </summary> private void ReleaseResources() { if (_encryptedPackage != null) { _encryptedPackage.Close(); _encryptedPackage = null; } else if (_package != null) { _package.Close(); _package = null; } if (_packageStream != null) { _packageStream.Close(); _packageStream = null; } } /// <summary> /// Auxiliary function of IPersistFile.Load. /// </summary> /// <returns> /// <value>A MemoryStream of the package file or a FileStream if the file is too big.</value> /// </returns> /// <remarks> /// <para>Use this method to load a package file completely to a memory buffer. /// After loading the file we can close the file, thus we can release the file /// lock quickly. However, there is a size limit on the file. If the /// file is too big (greater than _maxMemoryStreamBuffer), we cannot allow /// this method to consume too much memory. So we simply return the fileStream.</para> /// <para>Mode, access and sharing have already been checked or adjusted and can be assumed /// to be compatible with the goal of reading from the file.</para> /// </remarks> private static Stream FileToStream( string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileSharing, long maxMemoryStream) { FileInfo fi = new FileInfo(filePath); long byteCount = fi.Length; Stream s = new FileStream(filePath, fileMode, fileAccess, fileSharing); // There is a size limit of the file that we allow to be uploaded to a // memory stream. If the file size is bigger than the limit, simply return the fileStream. if (byteCount < maxMemoryStream) { // unchecked cast is safe because _maxMemoryStreamBuffer is less than Int32.Max MemoryStream ms = new MemoryStream(unchecked((int)byteCount)); using (s) { PackagingUtilities.CopyStream(s, ms, byteCount, 0x1000); } s = ms; } return s; } #endregion Private methods #region Fields /// <summary> /// CLSID for the XPS filter. /// </summary> [ComVisible(false)] private static readonly Guid _filterClsid = new Guid(0x0B8732A6, 0xAF74, 0x498c, 0xA2 , 0x51 , 0x9D , 0xC8 , 0x6B , 0x05 , 0x38 , 0xB0); /// <summary> /// Internal IFilter implementation being used by XpsFilter. /// This could be PackageFilter or EncryptedPackageFilter. /// </summary> [ComVisible(false)] private IFilter _filter; /// <summary> /// If the XPS file/stream is a Package, reference to the Package. /// </summary> [ComVisible(false)] private Package _package; /// <summary> /// If the XPS file/stream is a EncryptedPackageEnvelope, reference to the EncryptedPackageEnvelope. /// </summary> [ComVisible(false)] private EncryptedPackageEnvelope _encryptedPackage; /// <summary> /// If an XPS file is being filtered, refers to the file name. /// </summary> [ComVisible(false)] private string _xpsFileName; /// <summary> /// Stream wrapper we have opened our Package or EncryptedPackage on /// </summary> [ComVisible(false)] private Stream _packageStream; /// <summary> /// Cache frequently used size values to incur reflection cost just once. /// </summary> [ComVisible(false)] private const Int32 _int16Size = 2; #region Constants /// <summary> /// The number of characters to copy in a chunk buffer is limited as a /// defense-in-depth device without any expected performance deterioration. /// </summary> [ComVisible(false)] private const uint _maxTextBufferSizeInCharacters = 4096; /// <summary> /// The size of memory stream buffer used in FileToStream() /// should be limited. If the package file size is bigger than the limit, /// we cannot allow the buffer allocation, and return the fileStream itself. /// </summary> [ComVisible(false)] private const Int32 _maxMemoryStreamBuffer = 1024 * 1024; #endregion Constants #endregion Fields } #endregion XpsFilter }
namespace Code.Controllers { using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Models.AlbumVIewModels; using Data; using System; using Models; using System.Linq; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Http; using System.IO; using Microsoft.AspNetCore.Hosting; using System.Threading.Tasks; using System.Collections.Generic; using Models.SearchViewModels; using Models.AlbumVIewModels.EditAlbumViewModels; using Models.AlbumVIewModels.DeleteAlbumViewModels; public class AlbumsController : Controller { private readonly ApplicationDbContext db; private readonly UserManager<ApplicationUser> userManager; private IHostingEnvironment environment; public AlbumsController(ApplicationDbContext db, UserManager<ApplicationUser> userManager, IHostingEnvironment environment) { this.db = db; this.userManager = userManager; this.environment = environment; } //GET: Albums/Create [Authorize] [HttpGet] public IActionResult Create() { return View(); } //POST: Albums/Create //Redirect: Albums/Details/{id} [Authorize] [HttpPost] public async Task<IActionResult> Create(CreateAlbumViewModel model, List<IFormFile> Files) { var currentUser = userManager.GetUserAsync(User).Result; if (ModelState.IsValid) { var album = new Album() { Name = model.Name, Description = model.Description, CreatedOn = DateTime.UtcNow, User = currentUser, Category = model.Category }; db.Album.Add(album); db.SaveChanges(); if (Files.Capacity > 0) { foreach (var image in Files) { string filename = image.FileName.Split('\\').Last(); var img = new Image() { Name = filename, Album = album, User = currentUser }; db.Images.Add(img); string path = Path.Combine(environment.WebRootPath, "uploads", currentUser.Id, album.Id.ToString()); Directory.CreateDirectory(Path.Combine(path)); using (FileStream fs = new FileStream(Path.Combine(path, filename), FileMode.Create)) { await image.CopyToAsync(fs); } currentUser.ImagesCount++; } currentUser.AlbumsCount++; } db.Update(currentUser); db.SaveChanges(); return RedirectToAction("Index", "MyProfile"); } return RedirectToAction("Index", "MyProfile"); } // Albums/Details/{id} public IActionResult Details(int albumId, string userId) { var album = this.db.Album .Where(a => a.Id == albumId) .Select(a => new AlbumDetailsViewModel() { Id = a.Id, Name = a.Name, Category = a.Category, CreatedOn = a.CreatedOn, Description = a.Description, Creator = this.db.Users .Where(u => u.Id == userId) .FirstOrDefault(), Images = this.db.Images .Where(img => img.Album.Id == a.Id) .Select(img => new AlbumImageDetailsViewModel() { Id = img.Id, Name = img.Name, Rating = img.Rating, Path = userId + "/" + albumId + "/" + img.Name , Album = a }).ToList(), Comments = this.db.Comments .Where(c => c.Album.Id == a.Id) .Select(c => new CommentDetailsViewModel() { Id = c.Id, Author = c.User, Content = c.Content, CreatedOn = c.CreatedOn }).ToList() }) .FirstOrDefault(); if(album == null) { return NotFound(); } return View(album); } //GET: Albums/Edit?albumId={id} [Authorize] [HttpGet] public IActionResult Edit(int albumId, string userId) { var currentUser = userManager.GetUserAsync(User).Result; var album = this.db.Album .Where(al => al.Id == albumId) .Select(al => new AlbumEditViewModel() { Id = al.Id, Name = al.Name, Description = al.Description, User = this.db.Users .Where(u => u.Id == userId) .FirstOrDefault(), Comments = this.db.Comments .Where(c => c.Album.Id == albumId) .Select(c => new AlbumCommentsEditViewModel() { Id = c.Id, Content = c.Content, CreatedOn = c.CreatedOn, Creator = c.User }).ToList(), Images = this.db.Images .Where(img => img.Album.Id == albumId) .Select(img => new AlbumImageEditViewModel() { Id = img.Id, Name = img.Name, Rating = img.Rating, Path = userId + "/" + albumId + "/" + img.Name }) .ToList() }) .FirstOrDefault(); if(album.User != currentUser) { return BadRequest(); } return View(album); } //POST: Albums/Edit?albumId={id} [Authorize] [HttpPost] public async Task<IActionResult> Edit(AlbumDetailsViewModel model, List<IFormFile> pictures, string userId) { var user = this.db.Users .Where(u => u.Id == userId) .FirstOrDefault(); if (ModelState.IsValid) { var album = this.db.Album .Where(al => al.Id == model.Id) .FirstOrDefault(); album.Name = model.Name; album.Description = model.Description; db.Update(album); if (pictures.Capacity > 0) { foreach (var image in pictures) { string filename = image.FileName.Split('\\').Last(); var img = new Image() { Name = filename, Album = album, User = this.db.Users .Where(u => u.Id == userId) .FirstOrDefault() }; db.Images.Add(img); string path = Path.Combine(environment.WebRootPath, "uploads", userId, album.Id.ToString()); Directory.CreateDirectory(Path.Combine(path)); using (FileStream fs = new FileStream(Path.Combine(path, filename), FileMode.Create)) { await image.CopyToAsync(fs); } user.ImagesCount++; } } db.SaveChanges(); } return RedirectToAction("Details", "Albums", new { @albumId = model.Id, @userId = userId}); } //GET: Albums/Comment?albumId={id} [Authorize] [HttpGet] public IActionResult Comment() { return View(); } //POST: Albums/Comment?albumId={id} [Authorize] [HttpPost] public IActionResult Comment(AlbumDetailsViewModel model) { if(ModelState.IsValid) { var author = userManager.GetUserAsync(User).Result; var comment = new Comment() { Album = this.db.Album .Where(al => al.Id == model.Id) .FirstOrDefault(), Content = model.PostComment.Content, User = author, CreatedOn = DateTime.UtcNow.AddHours(3) }; db.Comments.Add(comment); author.CommentsCount++; db.SaveChanges(); return RedirectToAction("Details", "Albums", new { @albumId = model.Id, @userId = comment.Album.UserId }); } return RedirectToAction("Details", "Albums", new { @albumId = model.Id, @userId = model.Creator.Id }); } // in Albums/Edit?albumId{id}/userId={id} // Albums/DeleteComment?commentId={id}/albumId={id}/userId={id} public IActionResult DeleteComment(int commentId, int albumId, string userId) { var currentUser = userManager.GetUserAsync(User).Result; // finds the author of the comment var user = this.db.Comments .Where(c => c.Id == commentId) .Select(c => new DeleteAlbumCommentsViewModel() { User = c.User }) .FirstOrDefault(); if(user.User.Id != currentUser.Id) { return BadRequest(); } var comment = this.db.Comments .Where(c => c.Id == commentId) .FirstOrDefault(); db.Comments.Remove(comment); user.User.CommentsCount--; db.Users.Update(user.User); db.SaveChanges(); return RedirectToAction("Edit", "Albums", new { @albumId = albumId, @userId = userId}); } // in Albums/Edit?albumId{id}/userId={id} // Albums/DeleteImage?imageId={id}/albumId={id}/userId={id} public IActionResult DeleteImage (int imageId, int albumId, string userId) { var currnetUser = userManager.GetUserAsync(User).Result; var image = this.db.Images .Where(img => img.Id == imageId) .FirstOrDefault(); if(image == null) { return NotFound(); } var user = this.db.Users .Where(u => u.Id == userId) .FirstOrDefault(); if(user.Id != currnetUser.Id) { return BadRequest(); } var likes = this.db.Likes .Where(l => l.Image.Id == imageId) .ToList(); if(likes.Count > 0) { foreach(var like in likes) { if(like.UserId == userId) { user.LikesCount--; } } db.Likes.RemoveRange(likes); } db.Images.Remove(image); user.ImagesCount--; db.Update(user); db.SaveChanges(); return RedirectToAction("Edit", "Albums", new { @albumId = albumId, @userId = userId }); } // in Albums/Edit?albumId{id}/userId={id} // Albums/Delete?albumId={id} public IActionResult Delete(int albumId, string userId) { var currentUser = userManager.GetUserAsync(User).Result; var album = this.db.Album .Where(al => al.Id == albumId) .FirstOrDefault(); var user = this.db.Users .Where(u => u.Id == userId) .FirstOrDefault(); if(user.Id != currentUser.Id) { return BadRequest(); } var images = this.db.Images .Where(img => img.Album.Id == albumId) .ToList(); if(images.Count > 0) { foreach(var image in images) { var likes = this.db.Likes .Where(l => l.Image.Id == image.Id) .Select(l => new Like() { Id = l.Id, Image = l.Image, UserId = l.UserId }) .ToList(); if(likes.Count > 0) { foreach (var like in likes) { var author = this.db.Users .Where(u => u.Id == like.UserId) .FirstOrDefault(); author.LikesCount--; db.Update(author); } db.Likes.RemoveRange(likes); } user.ImagesCount--; } db.Images.RemoveRange(images); } var comments = this.db.Comments .Where(c => c.Album.Id == albumId) .ToList(); var commentsUsers = this.db.Comments .Where(c => c.Album.Id == albumId) .Select(c => new CommentDetailsViewModel() { Author = c.User }).ToList(); if(comments.Count > 0) { foreach(var comment in commentsUsers) { var author = this.db.Users .Where(u => u.Id == comment.Author.Id) .FirstOrDefault(); author.CommentsCount--; db.Update(author); } db.Comments.RemoveRange(comments); } db.SaveChanges(); db.Album.Remove(album); user.AlbumsCount--; db.Update(user); db.SaveChanges(); string path = Path.Combine(environment.WebRootPath, "uploads", userId, albumId.ToString()); if (System.IO.Directory.Exists(path)) { System.IO.Directory.Delete(path, true); } return RedirectToAction("Index", "MyProfile"); } } }
using System.Collections.Generic; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Support; using NUnit.Framework; namespace Lucene.Net.Search.Spans { using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using ReaderUtil = Lucene.Net.Index.ReaderUtil; using Similarity = Lucene.Net.Search.Similarities.Similarity; using Term = Lucene.Net.Index.Term; [TestFixture] public class TestSpans : LuceneTestCase { private IndexSearcher Searcher; private IndexReader Reader; private Directory Directory; public const string field = "field"; [SetUp] public override void SetUp() { base.SetUp(); Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); for (int i = 0; i < DocFields.Length; i++) { Document doc = new Document(); doc.Add(NewTextField(field, DocFields[i], Field.Store.YES)); writer.AddDocument(doc); } Reader = writer.Reader; writer.Dispose(); Searcher = NewSearcher(Reader); } [TearDown] public override void TearDown() { Reader.Dispose(); Directory.Dispose(); base.TearDown(); } private string[] DocFields = new string[] { "w1 w2 w3 w4 w5", "w1 w3 w2 w3", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3", "u2 u2 u1", "u2 xx u2 u1", "u2 u2 xx u1", "u2 xx u2 yy u1", "u2 xx u1 u2", "u2 u1 xx u2", "u1 u2 xx u2", "t1 t2 t1 t3 t2 t3", "s2 s1 s1 xx xx s2 xx s2 xx s1 xx xx xx xx xx s2 xx" }; public virtual SpanTermQuery MakeSpanTermQuery(string text) { return new SpanTermQuery(new Term(field, text)); } private void CheckHits(Query query, int[] results) { Search.CheckHits.DoCheckHits(Random(), query, field, Searcher, results, Similarity); } private void OrderedSlopTest3SQ(SpanQuery q1, SpanQuery q2, SpanQuery q3, int slop, int[] expectedDocs) { bool ordered = true; SpanNearQuery snq = new SpanNearQuery(new SpanQuery[] { q1, q2, q3 }, slop, ordered); CheckHits(snq, expectedDocs); } public virtual void OrderedSlopTest3(int slop, int[] expectedDocs) { OrderedSlopTest3SQ(MakeSpanTermQuery("w1"), MakeSpanTermQuery("w2"), MakeSpanTermQuery("w3"), slop, expectedDocs); } public virtual void OrderedSlopTest3Equal(int slop, int[] expectedDocs) { OrderedSlopTest3SQ(MakeSpanTermQuery("w1"), MakeSpanTermQuery("w3"), MakeSpanTermQuery("w3"), slop, expectedDocs); } public virtual void OrderedSlopTest1Equal(int slop, int[] expectedDocs) { OrderedSlopTest3SQ(MakeSpanTermQuery("u2"), MakeSpanTermQuery("u2"), MakeSpanTermQuery("u1"), slop, expectedDocs); } [Test] public virtual void TestSpanNearOrdered01() { OrderedSlopTest3(0, new int[] { 0 }); } [Test] public virtual void TestSpanNearOrdered02() { OrderedSlopTest3(1, new int[] { 0, 1 }); } [Test] public virtual void TestSpanNearOrdered03() { OrderedSlopTest3(2, new int[] { 0, 1, 2 }); } [Test] public virtual void TestSpanNearOrdered04() { OrderedSlopTest3(3, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestSpanNearOrdered05() { OrderedSlopTest3(4, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestSpanNearOrderedEqual01() { OrderedSlopTest3Equal(0, new int[] { }); } [Test] public virtual void TestSpanNearOrderedEqual02() { OrderedSlopTest3Equal(1, new int[] { 1 }); } [Test] public virtual void TestSpanNearOrderedEqual03() { OrderedSlopTest3Equal(2, new int[] { 1 }); } [Test] public virtual void TestSpanNearOrderedEqual04() { OrderedSlopTest3Equal(3, new int[] { 1, 3 }); } [Test] public virtual void TestSpanNearOrderedEqual11() { OrderedSlopTest1Equal(0, new int[] { 4 }); } [Test] public virtual void TestSpanNearOrderedEqual12() { OrderedSlopTest1Equal(0, new int[] { 4 }); } [Test] public virtual void TestSpanNearOrderedEqual13() { OrderedSlopTest1Equal(1, new int[] { 4, 5, 6 }); } [Test] public virtual void TestSpanNearOrderedEqual14() { OrderedSlopTest1Equal(2, new int[] { 4, 5, 6, 7 }); } [Test] public virtual void TestSpanNearOrderedEqual15() { OrderedSlopTest1Equal(3, new int[] { 4, 5, 6, 7 }); } [Test] public virtual void TestSpanNearOrderedOverlap() { bool ordered = true; int slop = 1; SpanNearQuery snq = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("t1"), MakeSpanTermQuery("t2"), MakeSpanTermQuery("t3") }, slop, ordered); Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq); Assert.IsTrue(spans.Next(), "first range"); Assert.AreEqual(11, spans.Doc, "first doc"); Assert.AreEqual(0, spans.Start, "first start"); Assert.AreEqual(4, spans.End, "first end"); Assert.IsTrue(spans.Next(), "second range"); Assert.AreEqual(11, spans.Doc, "second doc"); Assert.AreEqual(2, spans.Start, "second start"); Assert.AreEqual(6, spans.End, "second end"); Assert.IsFalse(spans.Next(), "third range"); } [Test] public virtual void TestSpanNearUnOrdered() { //See http://www.gossamer-threads.com/lists/lucene/java-dev/52270 for discussion about this test SpanNearQuery snq; snq = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("u1"), MakeSpanTermQuery("u2") }, 0, false); Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(4, spans.Doc, "doc"); Assert.AreEqual(1, spans.Start, "start"); Assert.AreEqual(3, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(5, spans.Doc, "doc"); Assert.AreEqual(2, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(8, spans.Doc, "doc"); Assert.AreEqual(2, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(9, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(2, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(10, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(2, spans.End, "end"); Assert.IsTrue(spans.Next() == false, "Has next and it shouldn't: " + spans.Doc); SpanNearQuery u1u2 = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("u1"), MakeSpanTermQuery("u2") }, 0, false); snq = new SpanNearQuery(new SpanQuery[] { u1u2, MakeSpanTermQuery("u2") }, 1, false); spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(4, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(3, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); //unordered spans can be subsets Assert.AreEqual(4, spans.Doc, "doc"); Assert.AreEqual(1, spans.Start, "start"); Assert.AreEqual(3, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(5, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(5, spans.Doc, "doc"); Assert.AreEqual(2, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(8, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(8, spans.Doc, "doc"); Assert.AreEqual(2, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(9, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(2, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(9, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(4, spans.End, "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(10, spans.Doc, "doc"); Assert.AreEqual(0, spans.Start, "start"); Assert.AreEqual(2, spans.End, "end"); Assert.IsTrue(spans.Next() == false, "Has next and it shouldn't"); } private Spans OrSpans(string[] terms) { SpanQuery[] sqa = new SpanQuery[terms.Length]; for (int i = 0; i < terms.Length; i++) { sqa[i] = MakeSpanTermQuery(terms[i]); } return MultiSpansWrapper.Wrap(Searcher.TopReaderContext, new SpanOrQuery(sqa)); } private void TstNextSpans(Spans spans, int doc, int start, int end) { Assert.IsTrue(spans.Next(), "next"); Assert.AreEqual(doc, spans.Doc, "doc"); Assert.AreEqual(start, spans.Start, "start"); Assert.AreEqual(end, spans.End, "end"); } [Test] public virtual void TestSpanOrEmpty() { Spans spans = OrSpans(new string[0]); Assert.IsFalse(spans.Next(), "empty next"); SpanOrQuery a = new SpanOrQuery(); SpanOrQuery b = new SpanOrQuery(); Assert.IsTrue(a.Equals(b), "empty should equal"); } [Test] public virtual void TestSpanOrSingle() { Spans spans = OrSpans(new string[] { "w5" }); TstNextSpans(spans, 0, 4, 5); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrMovesForward() { Spans spans = OrSpans(new string[] { "w1", "xx" }); spans.Next(); int doc = spans.Doc; Assert.AreEqual(0, doc); spans.SkipTo(0); doc = spans.Doc; // LUCENE-1583: // according to Spans, a skipTo to the same doc or less // should still call next() on the underlying Spans Assert.AreEqual(1, doc); } [Test] public virtual void TestSpanOrDouble() { Spans spans = OrSpans(new string[] { "w5", "yy" }); TstNextSpans(spans, 0, 4, 5); TstNextSpans(spans, 2, 3, 4); TstNextSpans(spans, 3, 4, 5); TstNextSpans(spans, 7, 3, 4); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrDoubleSkip() { Spans spans = OrSpans(new string[] { "w5", "yy" }); Assert.IsTrue(spans.SkipTo(3), "initial skipTo"); Assert.AreEqual(3, spans.Doc, "doc"); Assert.AreEqual(4, spans.Start, "start"); Assert.AreEqual(5, spans.End, "end"); TstNextSpans(spans, 7, 3, 4); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrUnused() { Spans spans = OrSpans(new string[] { "w5", "unusedTerm", "yy" }); TstNextSpans(spans, 0, 4, 5); TstNextSpans(spans, 2, 3, 4); TstNextSpans(spans, 3, 4, 5); TstNextSpans(spans, 7, 3, 4); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrTripleSameDoc() { Spans spans = OrSpans(new string[] { "t1", "t2", "t3" }); TstNextSpans(spans, 11, 0, 1); TstNextSpans(spans, 11, 1, 2); TstNextSpans(spans, 11, 2, 3); TstNextSpans(spans, 11, 3, 4); TstNextSpans(spans, 11, 4, 5); TstNextSpans(spans, 11, 5, 6); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanScorerZeroSloppyFreq() { bool ordered = true; int slop = 1; IndexReaderContext topReaderContext = Searcher.TopReaderContext; IList<AtomicReaderContext> leaves = topReaderContext.Leaves; int subIndex = ReaderUtil.SubIndex(11, leaves); for (int i = 0, c = leaves.Count; i < c; i++) { AtomicReaderContext ctx = leaves[i]; Similarity sim = new DefaultSimilarityAnonymousInnerClassHelper(this); Similarity oldSim = Searcher.Similarity; Scorer spanScorer; try { Searcher.Similarity = sim; SpanNearQuery snq = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("t1"), MakeSpanTermQuery("t2") }, slop, ordered); spanScorer = Searcher.CreateNormalizedWeight(snq).GetScorer(ctx, ((AtomicReader)ctx.Reader).LiveDocs); } finally { Searcher.Similarity = oldSim; } if (i == subIndex) { Assert.IsTrue(spanScorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS, "first doc"); Assert.AreEqual(spanScorer.DocID + ctx.DocBase, 11, "first doc number"); float score = spanScorer.GetScore(); Assert.IsTrue(score == 0.0f, "first doc score should be zero, " + score); } else { Assert.IsTrue(spanScorer.NextDoc() == DocIdSetIterator.NO_MORE_DOCS, "no second doc"); } } } private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity { private readonly TestSpans OuterInstance; public DefaultSimilarityAnonymousInnerClassHelper(TestSpans outerInstance) { this.OuterInstance = outerInstance; } public override float SloppyFreq(int distance) { return 0.0f; } } // LUCENE-1404 private void AddDoc(IndexWriter writer, string id, string text) { Document doc = new Document(); doc.Add(NewStringField("id", id, Field.Store.YES)); doc.Add(NewTextField("text", text, Field.Store.YES)); writer.AddDocument(doc); } // LUCENE-1404 private int HitCount(IndexSearcher searcher, string word) { return searcher.Search(new TermQuery(new Term("text", word)), 10).TotalHits; } // LUCENE-1404 private SpanQuery CreateSpan(string value) { return new SpanTermQuery(new Term("text", value)); } // LUCENE-1404 private SpanQuery CreateSpan(int slop, bool ordered, SpanQuery[] clauses) { return new SpanNearQuery(clauses, slop, ordered); } // LUCENE-1404 private SpanQuery CreateSpan(int slop, bool ordered, string term1, string term2) { return CreateSpan(slop, ordered, new SpanQuery[] { CreateSpan(term1), CreateSpan(term2) }); } // LUCENE-1404 [Test] public virtual void TestNPESpanQuery() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); // Add documents AddDoc(writer, "1", "the big dogs went running to the market"); AddDoc(writer, "2", "the cat chased the mouse, then the cat ate the mouse quickly"); // Commit writer.Dispose(); // Get searcher IndexReader reader = DirectoryReader.Open(dir); IndexSearcher searcher = NewSearcher(reader); // Control (make sure docs indexed) Assert.AreEqual(2, HitCount(searcher, "the")); Assert.AreEqual(1, HitCount(searcher, "cat")); Assert.AreEqual(1, HitCount(searcher, "dogs")); Assert.AreEqual(0, HitCount(searcher, "rabbit")); // this throws exception (it shouldn't) Assert.AreEqual(1, searcher.Search(CreateSpan(0, true, new SpanQuery[] { CreateSpan(4, false, "chased", "cat"), CreateSpan("ate") }), 10).TotalHits); reader.Dispose(); dir.Dispose(); } [Test] public virtual void TestSpanNots() { Assert.AreEqual(0, SpanCount("s2", "s2", 0, 0), 0, "SpanNotIncludeExcludeSame1"); Assert.AreEqual(0, SpanCount("s2", "s2", 10, 10), 0, "SpanNotIncludeExcludeSame2"); //focus on behind Assert.AreEqual(1, SpanCount("s2", "s1", 6, 0), "SpanNotS2NotS1_6_0"); Assert.AreEqual(2, SpanCount("s2", "s1", 5, 0), "SpanNotS2NotS1_5_0"); Assert.AreEqual(3, SpanCount("s2", "s1", 3, 0), "SpanNotS2NotS1_3_0"); Assert.AreEqual(4, SpanCount("s2", "s1", 2, 0), "SpanNotS2NotS1_2_0"); Assert.AreEqual(4, SpanCount("s2", "s1", 0, 0), "SpanNotS2NotS1_0_0"); //focus on both Assert.AreEqual(2, SpanCount("s2", "s1", 3, 1), "SpanNotS2NotS1_3_1"); Assert.AreEqual(3, SpanCount("s2", "s1", 2, 1), "SpanNotS2NotS1_2_1"); Assert.AreEqual(3, SpanCount("s2", "s1", 1, 1), "SpanNotS2NotS1_1_1"); Assert.AreEqual(0, SpanCount("s2", "s1", 10, 10), "SpanNotS2NotS1_10_10"); //focus on ahead Assert.AreEqual(0, SpanCount("s1", "s2", 10, 10), "SpanNotS1NotS2_10_10"); Assert.AreEqual(3, SpanCount("s1", "s2", 0, 1), "SpanNotS1NotS2_0_1"); Assert.AreEqual(3, SpanCount("s1", "s2", 0, 2), "SpanNotS1NotS2_0_2"); Assert.AreEqual(2, SpanCount("s1", "s2", 0, 3), "SpanNotS1NotS2_0_3"); Assert.AreEqual(1, SpanCount("s1", "s2", 0, 4), "SpanNotS1NotS2_0_4"); Assert.AreEqual(0, SpanCount("s1", "s2", 0, 8), "SpanNotS1NotS2_0_8"); //exclude doesn't exist Assert.AreEqual(3, SpanCount("s1", "s3", 8, 8), "SpanNotS1NotS3_8_8"); //include doesn't exist Assert.AreEqual(0, SpanCount("s3", "s1", 8, 8), "SpanNotS3NotS1_8_8"); } [Test] [Description("LUCENENET-597")] public void TestToString_LUCENENET_597() { var clauses = new[] { new SpanTermQuery(new Term("f", "lucene")), new SpanTermQuery(new Term("f", "net")), new SpanTermQuery(new Term("f", "solr")) }; var query = new SpanNearQuery(clauses, 0, true); var queryString = query.ToString(); Assert.AreEqual("SpanNear([f:lucene, f:net, f:solr], 0, True)", queryString); } private int SpanCount(string include, string exclude, int pre, int post) { SpanTermQuery iq = new SpanTermQuery(new Term(field, include)); SpanTermQuery eq = new SpanTermQuery(new Term(field, exclude)); SpanNotQuery snq = new SpanNotQuery(iq, eq, pre, post); Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq); int i = 0; while (spans.Next()) { i++; } return i; } } }
// 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> /// System.Type.Equals(System.Object) /// </summary> public class TypeEquals1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Compare two Types of the same class"); try { Type t1 = typeof(TypeEquals1); Type t2 = typeof(TypeEquals1); if (!t1.Equals((Object)t2)) { TestLibrary.TestFramework.LogError("001", "Two Types of the same class are not equals"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Compare Type and instance are not equal"); try { Type t = typeof(Object); Object o = new Object(); if (t.Equals(o)) { TestLibrary.TestFramework.LogError("003", "Compare Type and instance are equal"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Compare Type and different instance are not equal"); try { Type t = typeof(TypeEquals1); Object o = new Object(); if (t.Equals(o)) { TestLibrary.TestFramework.LogError("005", "Type and different instance are equal"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Compare different types"); try { Type t1 = typeof(TypeEquals1); Type t2 = typeof(Object); if (t1.Equals(t2)) { TestLibrary.TestFramework.LogError("007", "Type.Equals returns true for different types"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Compare a type with itself"); try { Type t1 = typeof(TypeEquals1); if (!t1.Equals((Object)t1)) { TestLibrary.TestFramework.LogError("009", "Type.Equals returns false when comparing a type with itself"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Compare type with null reference"); try { if (typeof(Object).Equals(null)) { TestLibrary.TestFramework.LogError("101", "Compare type with null reference"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { TypeEquals1 test = new TypeEquals1(); TestLibrary.TestFramework.BeginTestCase("TypeEquals1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
namespace Alchemi.Console.PropertiesDialogs { partial class GroupProperties { /// <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 Windows Form 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GroupProperties)); this.lvMembers = new System.Windows.Forms.ListView(); this.label1 = new System.Windows.Forms.Label(); this.btnRemove = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.tabPermissions = new System.Windows.Forms.TabPage(); this.lvPrm = new System.Windows.Forms.ListView(); this.label2 = new System.Windows.Forms.Label(); this.btnRemovePrm = new System.Windows.Forms.Button(); this.btnAddPrm = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.tabGeneral.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconBox)).BeginInit(); this.tabs.SuspendLayout(); this.tabPermissions.SuspendLayout(); this.SuspendLayout(); // // btnOK // this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // imgListSmall // this.imgListSmall.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgListSmall.ImageStream"))); this.imgListSmall.Images.SetKeyName(0, ""); this.imgListSmall.Images.SetKeyName(1, ""); this.imgListSmall.Images.SetKeyName(2, ""); this.imgListSmall.Images.SetKeyName(3, ""); this.imgListSmall.Images.SetKeyName(4, ""); this.imgListSmall.Images.SetKeyName(5, ""); this.imgListSmall.Images.SetKeyName(6, ""); this.imgListSmall.Images.SetKeyName(7, ""); this.imgListSmall.Images.SetKeyName(8, ""); this.imgListSmall.Images.SetKeyName(9, ""); this.imgListSmall.Images.SetKeyName(10, ""); this.imgListSmall.Images.SetKeyName(11, ""); this.imgListSmall.Images.SetKeyName(12, ""); // // tabGeneral // this.tabGeneral.Controls.Add(this.lvMembers); this.tabGeneral.Controls.Add(this.label1); this.tabGeneral.Controls.Add(this.btnRemove); this.tabGeneral.Controls.Add(this.btnAdd); this.tabGeneral.Controls.SetChildIndex(this.iconBox, 0); this.tabGeneral.Controls.SetChildIndex(this.lbName, 0); this.tabGeneral.Controls.SetChildIndex(this.lineLabel, 0); this.tabGeneral.Controls.SetChildIndex(this.btnAdd, 0); this.tabGeneral.Controls.SetChildIndex(this.btnRemove, 0); this.tabGeneral.Controls.SetChildIndex(this.label1, 0); this.tabGeneral.Controls.SetChildIndex(this.lvMembers, 0); // // iconBox // this.iconBox.Image = ((System.Drawing.Image)(resources.GetObject("iconBox.Image"))); // // tabs // this.tabs.Controls.Add(this.tabPermissions); this.tabs.Controls.SetChildIndex(this.tabPermissions, 0); this.tabs.Controls.SetChildIndex(this.tabGeneral, 0); // // lvMembers // this.lvMembers.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.lvMembers.HideSelection = false; this.lvMembers.Location = new System.Drawing.Point(16, 96); this.lvMembers.MultiSelect = false; this.lvMembers.Name = "lvMembers"; this.lvMembers.Size = new System.Drawing.Size(296, 176); this.lvMembers.SmallImageList = this.imgListSmall; this.lvMembers.TabIndex = 24; this.lvMembers.UseCompatibleStateImageBehavior = false; this.lvMembers.View = System.Windows.Forms.View.List; this.lvMembers.SelectedIndexChanged += new System.EventHandler(this.lvMembers_SelectedIndexChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(16, 72); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(53, 13); this.label1.TabIndex = 23; this.label1.Text = "&Members:"; // // btnRemove // this.btnRemove.Enabled = false; this.btnRemove.Location = new System.Drawing.Point(96, 280); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(72, 23); this.btnRemove.TabIndex = 22; this.btnRemove.Text = "&Remove"; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(16, 280); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(72, 23); this.btnAdd.TabIndex = 21; this.btnAdd.Tag = ""; this.btnAdd.Text = "&Add..."; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // tabPermissions // this.tabPermissions.Controls.Add(this.lvPrm); this.tabPermissions.Controls.Add(this.label2); this.tabPermissions.Controls.Add(this.btnRemovePrm); this.tabPermissions.Controls.Add(this.btnAddPrm); this.tabPermissions.Location = new System.Drawing.Point(4, 22); this.tabPermissions.Name = "tabPermissions"; this.tabPermissions.Size = new System.Drawing.Size(328, 318); this.tabPermissions.TabIndex = 2; this.tabPermissions.Text = "Permissions"; // // lvPrm // this.lvPrm.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.lvPrm.HideSelection = false; this.lvPrm.Location = new System.Drawing.Point(16, 40); this.lvPrm.MultiSelect = false; this.lvPrm.Name = "lvPrm"; this.lvPrm.Size = new System.Drawing.Size(296, 224); this.lvPrm.SmallImageList = this.imgListSmall; this.lvPrm.TabIndex = 24; this.lvPrm.UseCompatibleStateImageBehavior = false; this.lvPrm.View = System.Windows.Forms.View.List; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(16, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(171, 13); this.label2.TabIndex = 23; this.label2.Text = "Permissions assigned to this group:"; // // btnRemovePrm // this.btnRemovePrm.Enabled = false; this.btnRemovePrm.Location = new System.Drawing.Point(96, 280); this.btnRemovePrm.Name = "btnRemovePrm"; this.btnRemovePrm.Size = new System.Drawing.Size(72, 23); this.btnRemovePrm.TabIndex = 22; this.btnRemovePrm.Text = "&Remove"; this.btnRemovePrm.Click += new System.EventHandler(this.btnRemovePrm_Click); // // btnAddPrm // this.btnAddPrm.Location = new System.Drawing.Point(16, 280); this.btnAddPrm.Name = "btnAddPrm"; this.btnAddPrm.Size = new System.Drawing.Size(72, 23); this.btnAddPrm.TabIndex = 21; this.btnAddPrm.Tag = ""; this.btnAddPrm.Text = "&Add..."; this.btnAddPrm.Click += new System.EventHandler(this.btnAddPrm_Click); // // GroupProperties2 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(352, 389); this.Name = "GroupProperties2"; this.Text = "Group Properties"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.tabGeneral.ResumeLayout(false); this.tabGeneral.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconBox)).EndInit(); this.tabs.ResumeLayout(false); this.tabPermissions.ResumeLayout(false); this.tabPermissions.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListView lvMembers; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.TabPage tabPermissions; private System.Windows.Forms.ListView lvPrm; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnRemovePrm; private System.Windows.Forms.Button btnAddPrm; } }
namespace AutoMapper { using System; public class Mapper : IMapper { #region Static API private static IConfigurationProvider _configuration; private static IMapper _instance; /// <summary> /// Configuration provider for performing maps /// </summary> public static IConfigurationProvider Configuration { get { if (_configuration == null) throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); return _configuration; } private set { _configuration = value; } } /// <summary> /// Static mapper instance. You can also create a <see cref="Mapper"/> instance directly using the <see cref="Configuration"/> instance. /// </summary> public static IMapper Instance { get { if (_instance == null) throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); return _instance; } private set { _instance = value; } } /// <summary> /// Initialize static configuration instance /// </summary> /// <param name="config">Configuration action</param> public static void Initialize(Action<IMapperConfiguration> config) { Configuration = new MapperConfiguration(config); Instance = new Mapper(Configuration); } /// <summary> /// Execute a mapping from the source object to a new destination object. /// The source type is inferred from the source object. /// </summary> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TDestination>(object source) => Instance.Map<TDestination>(source); /// <summary> /// Execute a mapping from the source object to a new destination object with supplied mapping options. /// </summary> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts) => Instance.Map<TDestination>(source, opts); /// <summary> /// Execute a mapping from the source object to a new destination object. /// </summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TSource, TDestination>(TSource source) => Instance.Map<TSource, TDestination>(source); /// <summary> /// Execute a mapping from the source object to a new destination object with supplied mapping options. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts) => Instance.Map(source, opts); /// <summary> /// Execute a mapping from the source object to the existing destination object. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Dsetination type</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination) => Instance.Map(source, destination); /// <summary> /// Execute a mapping from the source object to the existing destination object with supplied mapping options. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="opts">Mapping options</param> /// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts) => Instance.Map(source, destination, opts); /// <summary> /// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to create</param> /// <returns>Mapped destination object</returns> public static object Map(object source, Type sourceType, Type destinationType) => Instance.Map(source, sourceType, destinationType); /// <summary> /// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects and supplied mapping options. /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to create</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) => Instance.Map(source, sourceType, destinationType, opts); /// <summary> /// Execute a mapping from the source object to existing destination object with explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static object Map(object source, object destination, Type sourceType, Type destinationType) => Instance.Map(source, destination, sourceType, destinationType); /// <summary> /// Execute a mapping from the source object to existing destination object with supplied mapping options and explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) => Instance.Map(source, destination, sourceType, destinationType, opts); #endregion private readonly IMappingEngine _engine; private readonly IConfigurationProvider _configurationProvider; private readonly Func<Type, object> _serviceCtor; public Mapper(IConfigurationProvider configurationProvider) : this(configurationProvider, configurationProvider.ServiceCtor) { } public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor) { _configurationProvider = configurationProvider; _serviceCtor = serviceCtor; _engine = new MappingEngine(configurationProvider, this); } Func<Type, object> IMapper.ServiceCtor => _serviceCtor; IConfigurationProvider IMapper.ConfigurationProvider => _configurationProvider; TDestination IMapper.Map<TDestination>(object source) => ((IMapper)this).Map<TDestination>(source, _ => { }); TDestination IMapper.Map<TDestination>(object source, Action<IMappingOperationOptions> opts) { var mappedObject = default(TDestination); if (source == null) return mappedObject; var sourceType = source.GetType(); var destinationType = typeof(TDestination); mappedObject = (TDestination)((IMapper)this).Map(source, sourceType, destinationType, opts); return mappedObject; } TDestination IMapper.Map<TSource, TDestination>(TSource source) { Type modelType = typeof(TSource); Type destinationType = typeof(TDestination); return (TDestination)((IMapper)this).Map(source, modelType, destinationType, _ => { }); } TDestination IMapper.Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts) { Type modelType = typeof(TSource); Type destinationType = typeof(TDestination); var options = new MappingOperationOptions<TSource, TDestination>(_serviceCtor); opts(options); return (TDestination)MapCore(source, modelType, destinationType, options); } TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination) => ((IMapper)this).Map(source, destination, _ => { }); TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts) { Type modelType = typeof(TSource); Type destinationType = typeof(TDestination); var options = new MappingOperationOptions<TSource, TDestination>(_serviceCtor); opts(options); return (TDestination)MapCore(source, destination, modelType, destinationType, options); } object IMapper.Map(object source, Type sourceType, Type destinationType) => ((IMapper)this).Map(source, sourceType, destinationType, _ => { }); object IMapper.Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { var options = new MappingOperationOptions(_serviceCtor); opts(options); return MapCore(source, sourceType, destinationType, options); } object IMapper.Map(object source, object destination, Type sourceType, Type destinationType) => ((IMapper)this).Map(source, destination, sourceType, destinationType, _ => { }); object IMapper.Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { var options = new MappingOperationOptions(_serviceCtor); opts(options); return MapCore(source, destination, sourceType, destinationType, options); } private object MapCore(object source, Type sourceType, Type destinationType, MappingOperationOptions options) { TypeMap typeMap = _configurationProvider.ResolveTypeMap(source, null, sourceType, destinationType); var context = new ResolutionContext(typeMap, source, sourceType, destinationType, options, _engine); return _engine.Map(context); } private object MapCore(object source, object destination, Type sourceType, Type destinationType, MappingOperationOptions options) { TypeMap typeMap = _configurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType); var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType, options, _engine); return _engine.Map(context); } } }
namespace Ioke.Lang { using System; using System.Collections; using System.Text; using Ioke.Lang.Util; public class IokeList : IokeData { IList list; public IokeList() : this(new SaneArrayList()) { } public IokeList(IList l) { this.list = l; } public static IList GetList(object on) { return ((IokeList)(IokeObject.dataOf(on))).list; } public IList List { get { return list; } set { this.list = value; } } public static void Add(object list, object obj) { ((IokeList)IokeObject.dataOf(list)).list.Add(obj); } public static void Add(object list, int index, object obj) { ((IokeList)IokeObject.dataOf(list)).list.Insert(index, obj); } public override void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "List"; obj.Mimics(IokeObject.As(runtime.Mixins.GetCell(null, null, "Sequenced"), null), runtime.nul, runtime.nul); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns a hash for the list", new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); return context.runtime.NewNumber(((IokeList)IokeObject.dataOf(on)).list.GetHashCode()); }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side list is equal to the right hand side list.", new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(runtime.List) .WithRequiredPositional("other") .Arguments, (method, on, args, keywords, context, message) => { IokeList d = (IokeList)IokeObject.dataOf(on); object other = args[0]; return ((other is IokeObject) && (IokeObject.dataOf(other) is IokeList) && d.list.Equals(((IokeList)IokeObject.dataOf(other)).list)) ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns a new sequence to iterate over this list", new TypeCheckingNativeMethod.WithNoArguments("seq", runtime.List, (method, on, args, keywords, context, message) => { IokeObject ob = method.runtime.IteratorSequence.AllocateCopy(null, null); ob.MimicsWithoutCheck(method.runtime.IteratorSequence); ob.Data = new Sequence.IteratorSequence(IokeList.GetList(on).GetEnumerator()); return ob; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes either one or two or three arguments. if one argument is given, it should be a message chain that will be sent to each object in the list. the result will be thrown away. if two arguments are given, the first is an unevaluated name that will be set to each of the values in the list in succession, and then the second argument will be evaluated in a scope with that argument in it. if three arguments is given, the first one is an unevaluated name that will be set to the index of each element, and the other two arguments are the name of the argument for the value, and the actual code. the code will evaluate in a lexical context, and if the argument name is available outside the context, it will be shadowed. the method will return the list.", new NativeMethod("each", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("indexOrArgOrCode") .WithOptionalPositionalUnevaluated("argOrCode") .WithOptionalPositionalUnevaluated("code") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object onAsList = context.runtime.List.ConvertToThis(on, message, context); var ls = ((IokeList)IokeObject.dataOf(onAsList)).list; switch(message.Arguments.Count) { case 0: { return ((Message)IokeObject.dataOf(runtime.seqMessage)).SendTo(runtime.seqMessage, context, on); } case 1: { IokeObject code = IokeObject.As(message.Arguments[0], context); foreach(object o in ls) { ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithReceiver(code, context, context.RealContext, o); } break; } case 2: { LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#each", message, context); string name = IokeObject.As(message.Arguments[0], context).Name; IokeObject code = IokeObject.As(message.Arguments[1], context); foreach(object o in ls) { c.SetCell(name, o); ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); } break; } case 3: { LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#each", message, context); string iname = IokeObject.As(message.Arguments[0], context).Name; string name = IokeObject.As(message.Arguments[1], context).Name; IokeObject code = IokeObject.As(message.Arguments[2], context); int index = 0; foreach(object o in ls) { c.SetCell(name, o); c.SetCell(iname, runtime.NewNumber(index++)); ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); } break; } } return onAsList; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes one argument, the index of the element to be returned. can be negative, and will in that case return indexed from the back of the list. if the index is outside the bounds of the list, will return nil. the argument can also be a range, and will in that case interpret the first index as where to start, and the second the end. the end can be negative and will in that case be from the end. if the first argument is negative, or after the second, an empty list will be returned. if the end point is larger than the list, the size of the list will be used as the end point.", new TypeCheckingNativeMethod("at", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(runtime.List) .WithRequiredPositional("index") .Arguments, (method, on, args, keywords, context, message) => { object arg = args[0]; if(IokeObject.dataOf(arg) is Range) { int first = Number.ExtractInt(Range.GetFrom(arg), message, context); if(first < 0) { return context.runtime.NewList(new SaneArrayList()); } int last = Number.ExtractInt(Range.GetTo(arg), message, context); bool inclusive = Range.IsInclusive(arg); var o = ((IokeList)IokeObject.dataOf(on)).List; int size = o.Count; if(last < 0) { last = size + last; } if(last < 0) { return context.runtime.NewList(new SaneArrayList()); } if(last >= size) { last = inclusive ? size-1 : size; } if(first > last || (!inclusive && first == last)) { return context.runtime.NewList(new SaneArrayList()); } if(!inclusive) { last--; } var l = new SaneArrayList(); for(int i = first; i<last+1; i++) { l.Add(o[i]); } return context.runtime.NewList(l); } if(!(IokeObject.dataOf(arg) is Number)) { arg = IokeObject.ConvertToNumber(arg, message, context); } int index = ((Number)IokeObject.dataOf(arg)).AsNativeInteger(); var o2 = ((IokeList)IokeObject.dataOf(on)).List; if(index < 0) { index = o2.Count + index; } if(index >= 0 && index < o2.Count) { return o2[index]; } else { return context.runtime.nil; } }))); obj.AliasMethod("at", "[]", null, null); obj.RegisterMethod(runtime.NewNativeMethod("returns the size of this list", new TypeCheckingNativeMethod.WithNoArguments("size", runtime.List, (method, on, args, keywords, context, message) => { return context.runtime.NewNumber(((IokeList)IokeObject.dataOf(on)).List.Count); }))); obj.AliasMethod("size", "length", null, null); obj.RegisterMethod(runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewText(IokeList.GetInspect(on)); }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewText(IokeList.GetNotice(on)); }))); obj.RegisterMethod(runtime.NewNativeMethod("Compares this object against the argument. The comparison is only based on the elements inside the lists, which are in turn compared using <=>.", new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("other") .Arguments, (method, on, args, keywords, context, message) => { var one = IokeList.GetList(on); object arg = args[0]; if(!(IokeObject.dataOf(arg) is IokeList)) { return context.runtime.nil; } var two = IokeList.GetList(arg); int len = Math.Min(one.Count, two.Count); SpaceshipComparator sc = new SpaceshipComparator(context, message); for(int i = 0; i < len; i++) { int v = sc.Compare(one[i], two[i]); if(v != 0) { return context.runtime.NewNumber(v); } } len = one.Count - two.Count; if(len == 0) return context.runtime.NewNumber(0); if(len > 0) return context.runtime.NewNumber(1); return context.runtime.NewNumber(-1); }))); obj.RegisterMethod(runtime.NewNativeMethod("takes one argument and adds it at the end of the list, and then returns the list", new TypeCheckingNativeMethod("<<", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("value") .Arguments, (method, on, args, keywords, context, message) => { IokeList.Add(on, args[0]); return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes one argument and adds it at the end of the list, and then returns the list", new TypeCheckingNativeMethod("append!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("value") .Arguments, (method, on, args, keywords, context, message) => { object value = args[0]; IokeList.Add(on, value); return on; }))); obj.AliasMethod("append!", "push!", null, null); obj.RegisterMethod(runtime.NewNativeMethod("takes one argument and adds it at the beginning of the list, and then returns the list", new TypeCheckingNativeMethod("prepend!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("value") .Arguments, (method, on, args, keywords, context, message) => { object value = args[0]; IokeList.Add(on, 0, value); return on; }))); obj.AliasMethod("prepend!", "unshift!", null, null); obj.RegisterMethod(runtime.NewNativeMethod("removes the last element from the list and returns it. returns nil if the list is empty.", new TypeCheckingNativeMethod.WithNoArguments("pop!", obj, (method, on, args, keywords, context, message) => { var l = ((IokeList)IokeObject.dataOf(on)).List; if(l.Count == 0) { return context.runtime.nil; } object result = l[l.Count-1]; l.RemoveAt(l.Count-1); return result; }))); obj.RegisterMethod(runtime.NewNativeMethod("removes the first element from the list and returns it. returns nil if the list is empty.", new TypeCheckingNativeMethod.WithNoArguments("shift!", obj, (method, on, args, keywords, context, message) => { var l = ((IokeList)IokeObject.dataOf(on)).List; if(l.Count == 0) { return context.runtime.nil; } object result = l[0]; l.RemoveAt(0); return result; }))); obj.RegisterMethod(runtime.NewNativeMethod("will remove all the entries from the list, and then returns the list", new TypeCheckingNativeMethod.WithNoArguments("clear!", obj, (method, on, args, keywords, context, message) => { ((IokeList)IokeObject.dataOf(on)).List.Clear(); return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if this list is empty, false otherwise", new TypeCheckingNativeMethod.WithNoArguments("empty?", obj, (method, on, args, keywords, context, message) => { return ((IokeList)IokeObject.dataOf(on)).List.Count == 0 ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the receiver includes the evaluated argument, otherwise false", new TypeCheckingNativeMethod("include?", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("object") .Arguments, (method, on, args, keywords, context, message) => { return ((IokeList)IokeObject.dataOf(on)).List.Contains(args[0]) ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("adds the elements in the argument list to the current list, and then returns that list", new TypeCheckingNativeMethod("concat!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("otherList").WhichMustMimic(obj) .Arguments, (method, on, args, keywords, context, message) => { var l = ((IokeList)IokeObject.dataOf(on)).List; var l2 = ((IokeList)IokeObject.dataOf(args[0])).List; foreach(object x in l2) l.Add(x); return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns a new list that contains the receivers elements and the elements of the list sent in as the argument.", new TypeCheckingNativeMethod("+", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("otherList").WhichMustMimic(obj) .Arguments, (method, on, args, keywords, context, message) => { var newList = new SaneArrayList(); newList.AddRange(((IokeList)IokeObject.dataOf(on)).List); newList.AddRange(((IokeList)IokeObject.dataOf(args[0])).List); return context.runtime.NewList(newList, IokeObject.As(on, context)); }))); obj.RegisterMethod(runtime.NewNativeMethod("returns a new list that contains all the elements from the receivers list, except for those that are in the argument list", new TypeCheckingNativeMethod("-", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("otherList").WhichMustMimic(obj) .Arguments, (method, on, args, keywords, context, message) => { var newList = new SaneArrayList(); var l = ((IokeList)IokeObject.dataOf(args[0])).List; foreach(object x in ((IokeList)IokeObject.dataOf(on)).List) { if(!l.Contains(x)) { newList.Add(x); } } return context.runtime.NewList(newList, IokeObject.As(on, context)); }))); obj.RegisterMethod(runtime.NewNativeMethod("returns a new sorted version of this list", new TypeCheckingNativeMethod.WithNoArguments("sort", obj, (method, on, args, keywords, context, message) => { object newList = IokeObject.Mimic(on, message, context); var ll = ((IokeList)IokeObject.dataOf(newList)).List; if(ll is ArrayList) { ((ArrayList)ll).Sort(new SpaceshipComparator(context, message)); } else { ArrayList second = new SaneArrayList(ll); ((ArrayList)second).Sort(new SpaceshipComparator(context, message)); ((IokeList)IokeObject.dataOf(newList)).List = second; } return newList; }))); obj.RegisterMethod(runtime.NewNativeMethod("sorts this list in place and then returns it", new TypeCheckingNativeMethod.WithNoArguments("sort!", obj, (method, on, args, keywords, context, message) => { var ll = ((IokeList)IokeObject.dataOf(on)).List; if(ll is ArrayList) { ((ArrayList)ll).Sort(new SpaceshipComparator(context, message)); } else { ArrayList second = new SaneArrayList(ll); ((ArrayList)second).Sort(new SpaceshipComparator(context, message)); ((IokeList)IokeObject.dataOf(on)).List = second; } return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes an index and zero or more objects to insert at that point. the index can be negative to index from the end of the list. if the index is positive and larger than the size of the list, the list will be filled with nils inbetween.", new TypeCheckingNativeMethod("insert!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("index").WhichMustMimic(runtime.Number) .WithRest("objects") .Arguments, (method, on, args, keywords, context, message) => { int index = ((Number)IokeObject.dataOf(args[0])).AsNativeInteger(); var l = ((IokeList)IokeObject.dataOf(on)).List; int size = l.Count; if(index < 0) { index = size + index + 1; } if(args.Count>1) { while(index < 0) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition, message, context, "Error", "Index"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("index", context.runtime.NewNumber(index)); object[] newCell = new object[]{context.runtime.NewNumber(index)}; context.runtime.WithRestartReturningArguments(()=>{context.runtime.ErrorCondition(condition);}, context, new IokeObject.UseValue("index", newCell)); index = Number.ExtractInt(newCell[0], message, context); if(index < 0) { index = size + index; } } for(int x = (index-size); x>0; x--) { l.Add(context.runtime.nil); } for(int i=1, j=args.Count; i<j; i++) l.Insert(index + i - 1, args[i]); } return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes two arguments, the index of the element to set, and the value to set. the index can be negative and will in that case set indexed from the end of the list. if the index is larger than the current size, the list will be expanded with nils. an exception will be raised if a abs(negative index) is larger than the size.", new TypeCheckingNativeMethod("at=", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("index") .WithRequiredPositional("value") .Arguments, (method, on, args, keywords, context, message) => { object arg = args[0]; object value = args[1]; if(!(IokeObject.dataOf(arg) is Number)) { arg = IokeObject.ConvertToNumber(arg, message, context); } int index = ((Number)IokeObject.dataOf(arg)).AsNativeInteger(); var o = ((IokeList)IokeObject.dataOf(on)).List; if(index < 0) { index = o.Count + index; } while(index < 0) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition, message, context, "Error", "Index"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("index", context.runtime.NewNumber(index)); object[] newCell = new object[]{context.runtime.NewNumber(index)}; context.runtime.WithRestartReturningArguments(()=>{context.runtime.ErrorCondition(condition);}, context, new IokeObject.UseValue("index", newCell)); index = Number.ExtractInt(newCell[0], message, context); if(index < 0) { index = o.Count + index; } } if(index >= o.Count) { int toAdd = (index-o.Count) + 1; for(int i=0;i<toAdd;i++) { o.Add(context.runtime.nil); } } o[(int)index] = value; return value; }))); obj.AliasMethod("at=", "[]=", null, null); obj.RegisterMethod(runtime.NewNativeMethod( "takes as argument the index of the element to be removed and returns it. can be " + "negative and will in that case index from the back of the list. if the index is " + "outside the bounds of the list, will return nil. the argument can also be a range, " + "and will in that case remove the sublist beginning at the first index and extending " + "to the position in the list specified by the second index (inclusive or exclusive " + "depending on the range). the end of the range can be negative and will in that case " + "index from the back of the list. if the start of the range is negative, or greater " + "than the end, an empty list will be returned. if the end index exceeds the bounds " + "of the list, its size will be used instead.", new TypeCheckingNativeMethod("removeAt!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("indexOrRange") .Arguments, (method, on, args, keywords, context, message) => { object arg = args[0]; if(IokeObject.dataOf(arg) is Range) { int first = Number.ExtractInt(Range.GetFrom(arg), message, context); if(first < 0) { return EmptyList(context); } int last = Number.ExtractInt(Range.GetTo(arg), message, context); var receiver = GetList(on); int size = receiver.Count; if(last < 0) { last = size + last; } if(last < 0) { return EmptyList(context); } bool inclusive = Range.IsInclusive(arg); if(last >= size) { last = inclusive ? size-1 : size; } if(first > last || (!inclusive && first == last)) { return EmptyList(context); } if(!inclusive) { last--; } var result = new SaneArrayList(); for(int i = 0; i <= last - first; i++) { result.Add(receiver[first]); receiver.RemoveAt(first); } return CopyList(context, result); } if(!(IokeObject.dataOf(arg) is Number)) { arg = IokeObject.ConvertToNumber(arg, message, context); } int index = ((Number)IokeObject.dataOf(arg)).AsNativeInteger(); var receiver2 = GetList(on); int size2 = receiver2.Count; if(index < 0) { index = size2 + index; } if(index >= 0 && index < size2) { object result = receiver2[(int)index]; receiver2.RemoveAt((int)index); return result; } else { return context.runtime.nil; } }))); obj.RegisterMethod(runtime.NewNativeMethod( "takes one or more arguments. removes all occurrences of the provided arguments from " + "the list and returns the updated list. if an argument is not contained, the list " + "remains unchanged. sending this method to an empty list has no effect.", new TypeCheckingNativeMethod("remove!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("element") .WithRest("elements") .Arguments, (method, on, args, keywords, context, message) => { var receiver = GetList(on); if(receiver.Count == 0) { return on; } foreach(object o in args) { for(int i = 0, j=receiver.Count; i<j; i++) { if(o.Equals(receiver[i])) { receiver.RemoveAt(i); i--; j--; } } } return on; }))); obj.RegisterMethod(runtime.NewNativeMethod( "takes one or more arguments. removes the first occurrence of the provided arguments " + "from the list and returns the updated list. if an argument is not contained, the list " + "remains unchanged. arguments that are provided multiple times are treated as distinct " + "elements. sending this message to an empty list has no effect.", new TypeCheckingNativeMethod("removeFirst!", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("element") .WithRest("elements") .Arguments, (method, on, args, keywords, context, message) => { var receiver = GetList(on); if(receiver.Count == 0) { return on; } foreach(object o in args) { receiver.Remove(o); } return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("removes all nils in this list, and then returns the list", new TypeCheckingNativeMethod.WithNoArguments("compact!", obj, (method, on, args, keywords, context, message) => { var list = GetList(on); var newList = new SaneArrayList(); object nil = context.runtime.nil; foreach(object o in list) { if(o != nil) { newList.Add(o); } } SetList(on, newList); return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("reverses the elements in this list, then returns it", new TypeCheckingNativeMethod.WithNoArguments("reverse!", obj, (method, on, args, keywords, context, message) => { var list = GetList(on); if(list is ArrayList) { ((ArrayList)list).Reverse(); } else { ArrayList list2 = new SaneArrayList(list); list2.Reverse(); SetList(on, list2); } return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("flattens all lists in this list recursively, then returns it", new TypeCheckingNativeMethod.WithNoArguments("flatten!", obj, (method, on, args, keywords, context, message) => { SetList(on, Flatten(GetList(on))); return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns a text composed of the asText representation of all elements in the list, separated by the separator. the separator defaults to an empty text.", new TypeCheckingNativeMethod("join", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithOptionalPositional("separator", "") .Arguments, (method, on, args, keywords, context, message) => { var list = GetList(on); string result; if(list.Count == 0) { result = ""; } else { string sep = args.Count > 0 ? Text.GetText(args[0]) : ""; StringBuilder sb = new StringBuilder(); Join(list, sb, sep, context.runtime.asText, context); result = sb.ToString(); } return context.runtime.NewText(result); }))); obj.RegisterMethod(runtime.NewNativeMethod("takes one or two arguments, and will then use these arguments as code to transform each element in this list. the transform happens in place. finally the method will return the receiver.", new NativeMethod("map!", DefaultArgumentsDefinition.builder() .WithRequiredPositionalUnevaluated("argOrCode") .WithOptionalPositionalUnevaluated("code") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object onAsList = context.runtime.List.ConvertToThis(on, message, context); var ls = ((IokeList)IokeObject.dataOf(onAsList)).list; int size = ls.Count; switch(message.Arguments.Count) { case 1: { IokeObject code = IokeObject.As(message.Arguments[0], context); for(int i = 0; i<size; i++) { ls[i] = ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithReceiver(code, context, context.RealContext, ls[i]); } break; } case 2: { LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#map!", message, context); string name = IokeObject.As(message.Arguments[0], context).Name; IokeObject code = IokeObject.As(message.Arguments[1], context); for(int i = 0; i<size; i++) { c.SetCell(name, ls[i]); ls[i] = ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); } break; } } return on; }))); obj.AliasMethod("map!", "collect!", null, null); obj.RegisterMethod(runtime.NewNativeMethod("takes one or two arguments, and will then use these arguments as code to decide what elements should be removed from the list. the method will return the receiver.", new NativeMethod("removeIf!", DefaultArgumentsDefinition.builder() .WithRequiredPositionalUnevaluated("argOrCode") .WithOptionalPositionalUnevaluated("code") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object onAsList = context.runtime.List.ConvertToThis(on, message, context); var ls = ((IokeList)IokeObject.dataOf(onAsList)).list; switch(message.Arguments.Count) { case 1: { IokeObject code = IokeObject.As(message.Arguments[0], context); int count = ls.Count; for(int i = 0; i<count; i++) { object o1 = ls[i]; if(IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(code)).EvaluateCompleteWithReceiver(code, context, context.RealContext, o1))) { ls.RemoveAt(i); i--; count--; } } break; } case 2: { LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#map!", message, context); string name = IokeObject.As(message.Arguments[0], context).Name; IokeObject code = IokeObject.As(message.Arguments[1], context); int count = ls.Count; for(int i = 0; i<count; i++) { object o2 = ls[i]; c.SetCell(name, o2); if(IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext))) { ls.RemoveAt(i); i--; count--; } } break; } } return on; }))); } private static IList Flatten(IList list) { var result = new SaneArrayList(list.Count*2); Flatten(list, result); return result; } private static void Flatten(IList list, IList result) { foreach(object l in list) { if(l is IokeObject && IokeObject.dataOf(l) is IokeList) { Flatten(GetList(l), result); } else { result.Add(l); } } } private static void Join(IList list, StringBuilder sb, string sep, IokeObject asText, IokeObject context) { string realSep = ""; foreach(object o in list) { sb.Append(realSep); if(o is IokeObject && IokeObject.dataOf(o) is IokeList) { Join(GetList(o), sb, sep, asText, context); } else { sb.Append(Text.GetText(((Message)IokeObject.dataOf(asText)).SendTo(asText, context, o))); } realSep = sep; } } public void Add(object obj) { list.Add(obj); } public static void SetList(object on, IList list) { ((IokeList)(IokeObject.dataOf(on))).List = list; } public static string GetInspect(object on) { return ((IokeList)(IokeObject.dataOf(on))).Inspect(on); } public static string GetNotice(object on) { return ((IokeList)(IokeObject.dataOf(on))).Notice(on); } public static IokeObject EmptyList(IokeObject context) { return context.runtime.NewList(new SaneArrayList()); } public static IokeObject CopyList(IokeObject context, IList orig) { return context.runtime.NewList(new SaneArrayList(orig)); } public override IokeData CloneData(IokeObject obj, IokeObject m, IokeObject context) { return new IokeList(new SaneArrayList(list)); } public override string ToString() { return list.ToString(); } public override string ToString(IokeObject obj) { return list.ToString(); } public string Inspect(object obj) { StringBuilder sb = new StringBuilder(); sb.Append("["); string sep = ""; foreach(object o in list) { sb.Append(sep).Append(IokeObject.Inspect(o)); sep = ", "; } sb.Append("]"); return sb.ToString(); } public string Notice(object obj) { StringBuilder sb = new StringBuilder(); sb.Append("["); string sep = ""; foreach(object o in list) { sb.Append(sep).Append(IokeObject.Notice(o)); sep = ", "; } sb.Append("]"); return sb.ToString(); } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { public TypeInferrerTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition) { var root = await document.GetSyntaxRootAsync(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); var inferredType = useNodeStartPosition ? typeInference.InferType(await document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None), node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None) : typeInference.InferType(await document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None); var typeSyntax = inferredType.GenerateTypeSyntax(); Assert.Equal(expectedType, typeSyntax.ToString()); } private async Task TestInClassAsync(string text, string expectedType) { text = @"class C { $ }".Replace("$", text); await TestAsync(text, expectedType); } private async Task TestInMethodAsync(string text, string expectedType, bool testNode = true, bool testPosition = true) { text = @"class C { void M() { $ } }".Replace("$", text); await TestAsync(text, expectedType, testNode: testNode, testPosition: testPosition); } private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { ExpressionSyntax result = currentNode as ExpressionSyntax; if (result != null && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. await TestInMethodAsync( @"var q = [|Foo()|] ? 1 : 2;", "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional2() { await TestInMethodAsync( @"var q = a ? [|Foo()|] : 2;", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional3() { await TestInMethodAsync( @"var q = a ? """" : [|Foo()|];", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator1() { await TestInMethodAsync( @"int q = [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator2() { await TestInMethodAsync( @"var q = [|Foo()|];", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce1() { await TestInMethodAsync( @"var q = [|Foo()|] ?? 1;", "global::System.Int32?", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce2() { await TestInMethodAsync( @"bool? b; var q = b ?? [|Foo()|];", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce3() { await TestInMethodAsync( @"string s; var q = s ?? [|Foo()|];", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce4() { await TestInMethodAsync( @"var q = [|Foo()|] ?? string.Empty;", "global::System.String", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression1() { await TestInMethodAsync( @"string s; var q = s + [|Foo()|];", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression2() { await TestInMethodAsync( @"var s; var q = s || [|Foo()|];", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator1() { await TestInMethodAsync( @"var q = x << [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator2() { await TestInMethodAsync( @"var q = x >> [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator3() { await TestInMethodAsync( @"var q <<= [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator4() { await TestInMethodAsync( @"var q >>= [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestOverloadedConditionalLogicalOperatorsInferBool() { await TestAsync( @"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Foo()|]; } }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn1() { await TestInClassAsync( @"int M() { return [|Foo()|]; }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn2() { await TestInMethodAsync( @"return [|Foo()|];", "void"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn3() { await TestInClassAsync( @"int Property { get { return [|Foo()|]; } }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestYieldReturn() { var markup = @"using System.Collections.Generic; class Program { IEnumerable<int> M() { yield return [|abc|] } }"; await TestAsync(markup, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLambda() { await TestInMethodAsync( @"System.Func<string, int> f = s => { return [|Foo()|]; };", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestLambda() { await TestInMethodAsync( @"System.Func<string, int> f = s => [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThrow() { await TestInMethodAsync( @"throw [|Foo()|];", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCatch() { await TestInMethodAsync("try { } catch ([|Foo|] ex) { }", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIf() { await TestInMethodAsync(@"if ([|Foo()|]) { }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhile() { await TestInMethodAsync(@"while ([|Foo()|]) { }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDo() { await TestInMethodAsync(@"do { } while ([|Foo()|])", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor1() { await TestInMethodAsync( @"for (int i = 0; [|Foo()|]; i++) { }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor2() { await TestInMethodAsync(@"for (string i = [|Foo()|]; ; ) { }", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor3() { await TestInMethodAsync(@"for (var i = [|Foo()|]; ; ) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing1() { await TestInMethodAsync(@"using ([|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing2() { await TestInMethodAsync(@"using (int i = [|Foo()|]) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing3() { await TestInMethodAsync(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEach() { await TestInMethodAsync(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<global::System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression1() { await TestInMethodAsync( @"var q = +[|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression2() { await TestInMethodAsync( @"var q = -[|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression3() { await TestInMethodAsync( @"var q = ~[|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression4() { await TestInMethodAsync( @"var q = ![|Foo()|];", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression5() { await TestInMethodAsync( @"var q = System.DayOfWeek.Monday & ~[|Foo()|];", "global::System.DayOfWeek"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayRankSpecifier() { await TestInMethodAsync( @"var q = new string[[|Foo()|]];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch1() { await TestInMethodAsync(@"switch ([|Foo()|]) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch2() { await TestInMethodAsync(@"switch ([|Foo()|]) { default: }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch3() { await TestInMethodAsync(@"switch ([|Foo()|]) { case ""a"": }", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall1() { await TestInMethodAsync( @"Bar([|Foo()|]);", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall2() { await TestInClassAsync( @"void M() { Bar([|Foo()|]); } void Bar(int i);", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall3() { await TestInClassAsync( @"void M() { Bar([|Foo()|]); } void Bar();", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall4() { await TestInClassAsync( @"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall5() { await TestInClassAsync( @"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall1() { await TestInMethodAsync( @"new C([|Foo()|]);", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall2() { await TestInClassAsync( @"void M() { new C([|Foo()|]); } C(int i) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall3() { await TestInClassAsync( @"void M() { new C([|Foo()|]); } C() { }", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall4() { await TestInClassAsync( @"void M() { new C([|Foo()|]); } C(int i, string s) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall5() { await TestInClassAsync( @"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "global::System.String"); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer1() { await TestAsync( @"class MyClass { public MyClass(int x) : this([|test|]) { } }", "global::System.Int32"); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer2() { await TestAsync( @"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "global::System.String"); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializer() { await TestAsync( @"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexAccess1() { await TestInMethodAsync( @"string[] i; i[[|Foo()|]];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall1() { await TestInMethodAsync(@"this[[|Foo()|]];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall2() { // Update this when binding of indexers is working. await TestInClassAsync( @"void M() { this[[|Foo()|]]; } int this[int i] { get; }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall3() { // Update this when binding of indexers is working. await TestInClassAsync( @"void M() { this[[|Foo()|]]; } int this[int i, string s] { get; }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall5() { await TestInClassAsync( @"void M() { this[s: [|Foo()|]]; } int this[int i, string s] { get; }", "global::System.String"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreationSimple() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreation1() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } int Foo() { return 2; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreation2() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreation3() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } }"; await TestAsync(text, "global::System.Object"); } [Fact] public async Task TestArrayInitializerInEqualsValueClauseSimple() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInEqualsValueClause() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer1() { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Foo()|] }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer2() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Foo()|], """" } }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer3() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Foo()|] } }; } }"; await TestAsync(text, "global::System.String"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod2() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Boolean"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod3() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1_Position() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference4() { var text = @" using System; class A { void Foo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; await TestAsync(text, "global::System.Func<global::System.Int32,global::System.Int32>"); } [WorkItem(538993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInsideLambda2() { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; await TestAsync(text, "global::System.Int32"); } [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPointer1() { var text = @"class C { void M(int* i) { var q = i[[|Foo()|]]; } }"; await TestAsync(text, "global::System.Int32"); } [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDynamic1() { var text = @"class C { void M(dynamic i) { var q = i[[|Foo()|]]; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestChecked1() { var text = @"class C { void M() { string q = checked([|Foo()|]); } }"; await TestAsync(text, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<global::System.Int32>>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTask() { var text = @"using System.Threading.Tasks; class C { void M() { await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestLockStatement() { var text = @"class C { void M() { lock([|Foo()|]) { } } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestAwaitExpressionInLockStatement() { var text = @"class C { async void M() { lock(await [|Foo()|]) { } } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestReturnFromAsyncTaskOfT() { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; await TestAsync(markup, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments1() { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.DayOfWeek"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments2() { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.Double"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments3() { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")] public async Task TestReturnStatementWithinDelegateWithinAMethodCall() { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; await TestAsync(text, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause() { var text = @" try { } catch (Exception) if ([|M()|]) }"; await TestInMethodAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause1() { var text = @" try { } catch (Exception) if ([|M|]) }"; await TestInMethodAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; await TestInMethodAsync(text, "global::System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Boolean>", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod2() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator1() { var text = @"class C { void M() { object z = [|a|]?? null; } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator2() { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator3() { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[||]) } }"; await TestAsync(text, "global::System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda2() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[|b|]) } }"; await TestAsync(text, "global::System.String", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(1903, "https://github.com/dotnet/roslyn/issues/1903")] public async Task TestSelectLambda3() { var text = @"using System.Collections.Generic; using System.Linq; class A { } class B { } class C { IEnumerable<B> GetB(IEnumerable<A> a) { return a.Select(i => [|Foo(i)|]); } }"; await TestAsync(text, "global::B"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public async Task TestReturnInAsyncLambda1() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async () => { return [|a|]; }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public async Task TestReturnInAsyncLambda2() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async delegate () { return [|a|]; }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement1() { var text = @"class C { static void Main(string[] args) { System.ConsoleModifiers c = default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement2() { var text = @"class C { static void Foo(System.ConsoleModifiers arg) { Foo(default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall() { var text = @" using System.Collections.Generic; class C { void Foo() { [|ints|].Where(i => i > 10); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Int32>", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall2() { var text = @" using System.Collections.Generic; class C { void Foo() { [|ints|].Where(i => null); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Object>", testPosition: false); } [WorkItem(12755, "https://github.com/dotnet/roslyn/issues/12755")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestObjectCreationBeforeArrayIndexing() { var text = @"using System; class C { void M() { int[] array; C p = new [||] array[4] = 4; } }"; await TestAsync(text, "global::C", testNode: false); } [WorkItem(15468, "https://github.com/dotnet/roslyn/issues/15468")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstruction() { await TestInMethodAsync( @"[|(int i, _)|] =", "global::System.Object"); } [WorkItem(13402, "https://github.com/dotnet/roslyn/issues/13402")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestObjectCreationBeforeBlock() { var text = @"class Program { static void Main(string[] args) { Program p = new [||] { } } }"; await TestAsync(text, "global::Program", testNode: false); } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <[email protected]> // Copyright (c) 2010, Nathan Brown // // 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. // #endregion using System; using System.Data; using System.Data.Common; using FluentMigrator.Builders.Execute; namespace FluentMigrator.Runner.Processors.SQLite { public class SqliteProcessor : GenericProcessorBase { public override string DatabaseType { get { return "Sqlite"; } } public SqliteProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { } public override bool SchemaExists(string schemaName) { return true; } public override bool TableExists(string schemaName, string tableName) { return Exists("select count(*) from sqlite_master where name=\"{0}\" and type='table'", tableName); } public override bool ColumnExists(string schemaName, string tableName, string columnName) { var dataSet = Read("PRAGMA table_info([{0}])", tableName); return dataSet.Tables.Count > 0 && dataSet.Tables[0].Select(string.Format("Name='{0}'", columnName.Replace("'", "''"))).Length > 0; } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { return false; } public override bool IndexExists(string schemaName, string tableName, string indexName) { return Exists("select count(*) from sqlite_master where name='{0}' and tbl_name='{1}' and type='index'", indexName, tableName); } public override bool SequenceExists(string schemaName, string sequenceName) { return false; } public override void Execute(string template, params object[] args) { Process(String.Format(template, args)); } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) using (var reader = command.ExecuteReader()) { try { if (!reader.Read()) return false; if (int.Parse(reader[0].ToString()) <= 0) return false; return true; } catch { return false; } } } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("select * from [{0}]", tableName); } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { return false; } public override void Process(PerformDBOperationExpression expression) { Announcer.Say("Performing DB Operation"); if (Options.PreviewOnly) return; EnsureConnectionIsOpen(); if (expression.Operation != null) expression.Operation(Connection, null); } protected override void Process(string sql) { Announcer.Sql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) return; EnsureConnectionIsOpen(); if (sql.IndexOf("GO", StringComparison.OrdinalIgnoreCase) >= 0) { ExecuteBatchNonQuery(sql); } else { ExecuteNonQuery(sql); } } private void ExecuteNonQuery(string sql) { using (var command = Factory.CreateCommand(sql, Connection)) { try { command.ExecuteNonQuery(); } catch (DbException ex) { throw new Exception(ex.Message + "\r\nWhile Processing:\r\n\"" + command.CommandText + "\"", ex); } } } private void ExecuteBatchNonQuery(string sql) { sql += "\nGO"; // make sure last batch is executed. string sqlBatch = string.Empty; using (var command = Factory.CreateCommand(sql, Connection)) { try { foreach (string line in sql.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.ToUpperInvariant().Trim() == "GO") { if (!string.IsNullOrEmpty(sqlBatch)) { command.CommandText = sqlBatch; command.ExecuteNonQuery(); sqlBatch = string.Empty; } } else { sqlBatch += line + "\n"; } } } catch (DbException ex) { throw new Exception(ex.Message + "\r\nWhile Processing:\r\n\"" + command.CommandText + "\"", ex); } } } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); var ds = new DataSet(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) { var adapter = Factory.CreateDataAdapter(command); adapter.Fill(ds); return ds; } } } }
/* * Copyright (c) 2009, Stefan Simek * * 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.Text; namespace TriAxis.RunSharp.Examples { static class _11_OperatorOverloading { // example based on the MSDN Operator Overloading Sample (complex.cs) public static void GenComplex(AssemblyGen ag) { TypeGen Complex = ag.Public.Struct("Complex"); { FieldGen real = Complex.Public.Field<int>("real"); FieldGen imaginary = Complex.Public.Field<int>("imaginary"); CodeGen g = Complex.Public.Constructor() .Parameter<int>("real") .Parameter<int>("imaginary"); { g.Assign(real, g.Arg("real")); g.Assign(imaginary, g.Arg("imaginary")); } // Declare which operator to overload (+), the types // that can be added (two Complex objects), and the // return type (Complex): g = Complex.Operator(Operator.Add, Complex, Complex, "c1", Complex, "c2"); { Operand c1 = g.Arg("c1"), c2 = g.Arg("c2"); g.Return(Exp.New(Complex, c1.Field("real") + c2.Field("real"), c1.Field("imaginary") + c2.Field("imaginary"))); } // Override the ToString method to display an complex number in the suitable format: g = Complex.Public.Override.Method<string>("ToString"); { g.Return(Static.Invoke<string>("Format", "{0} + {1}i", real, imaginary)); } g = Complex.Public.Static.Void("Main"); { Operand num1 = g.Local(Exp.New(Complex, 2, 3)); Operand num2 = g.Local(Exp.New(Complex, 3, 4)); // Add two Complex objects (num1 and num2) through the // overloaded plus operator: Operand sum = g.Local(num1 + num2); // Print the numbers and the sum using the overriden ToString method: g.WriteLine("First complex number: {0}", num1); g.WriteLine("Second complex number: {0}", num2); g.WriteLine("The sum of the two numbers: {0}", sum); } } } // example based on the MSDN Operator Overloading Sample (dbbool.cs) public static void GenDbBool(AssemblyGen ag) { TypeGen DBBool = ag.Public.Struct("DBBool"); { // Private field that stores -1, 0, 1 for dbFalse, dbNull, dbTrue: FieldGen value = DBBool.Field<int>("value"); // Private constructor. The value parameter must be -1, 0, or 1: CodeGen g = DBBool.Constructor().Parameter<int>("value"); { g.Assign(value, g.Arg("value")); } // The three possible DBBool values: FieldGen dbNull = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbNull", Exp.New(DBBool, 0)); FieldGen dbFalse = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbFalse", Exp.New(DBBool, -1)); FieldGen dbTrue = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbTrue", Exp.New(DBBool, 1)); // Implicit conversion from bool to DBBool. Maps true to // DBBool.dbTrue and false to DBBool.dbFalse: g = DBBool.ImplicitConversionFrom<bool>("x"); { Operand x = g.Arg("x"); g.Return(x.Conditional(dbTrue, dbFalse)); } // Explicit conversion from DBBool to bool. Throws an // exception if the given DBBool is dbNull, otherwise returns // true or false: g = DBBool.ExplicitConversionTo<bool>("x"); { Operand x = g.Arg("x"); g.If(x.Field("value") == 0); { g.Throw(Exp.New(typeof(InvalidOperationException))); } g.End(); g.Return(x.Field("value") > 0); } // Equality operator. Returns dbNull if either operand is dbNull, // otherwise returns dbTrue or dbFalse: g = DBBool.Operator(Operator.Equality, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.If(x.Field("value") == 0 || y.Field("value") == 0); { g.Return(dbNull); } g.End(); g.Return((x.Field("value") == y.Field("value")).Conditional(dbTrue, dbFalse)); } // Inequality operator. Returns dbNull if either operand is // dbNull, otherwise returns dbTrue or dbFalse: g = DBBool.Operator(Operator.Inequality, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.If(x.Field("value") == 0 || y.Field("value") == 0); { g.Return(dbNull); } g.End(); g.Return((x.Field("value") != y.Field("value")).Conditional(dbTrue, dbFalse)); } // Logical negation operator. Returns dbTrue if the operand is // dbFalse, dbNull if the operand is dbNull, or dbFalse if the // operand is dbTrue: g = DBBool.Operator(Operator.LogicalNot, DBBool, DBBool, "x"); { Operand x = g.Arg("x"); g.Return(Exp.New(DBBool, -x.Field("value"))); } // Logical AND operator. Returns dbFalse if either operand is // dbFalse, dbNull if either operand is dbNull, otherwise dbTrue: g = DBBool.Operator(Operator.And, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.Return(Exp.New(DBBool, (x.Field("value") < y.Field("value")).Conditional(x.Field("value"), y.Field("value")))); } // Logical OR operator. Returns dbTrue if either operand is // dbTrue, dbNull if either operand is dbNull, otherwise dbFalse: g = DBBool.Operator(Operator.Or, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.Return(Exp.New(DBBool, (x.Field("value") > y.Field("value")).Conditional(x.Field("value"), y.Field("value")))); } // Definitely true operator. Returns true if the operand is // dbTrue, false otherwise: g = DBBool.Operator(Operator.True, typeof(bool), DBBool, "x"); { Operand x = g.Arg("x"); g.Return(x.Field("value") > 0); } // Definitely false operator. Returns true if the operand is // dbFalse, false otherwise: g = DBBool.Operator(Operator.False, typeof(bool), DBBool, "x"); { Operand x = g.Arg("x"); g.Return(x.Field("value") < 0); } // Overload the conversion from DBBool to string: g = DBBool.ImplicitConversionTo(typeof(string), "x"); { Operand x = g.Arg("x"); g.Return((x.Field("value") > 0).Conditional("dbTrue", (x.Field("value") < 0).Conditional("dbFalse", "dbNull"))); } // Override the Object.Equals(object o) method: g = DBBool.Public.Override.Method<bool>("Equals").Parameter<object>("o"); { g.Try(); { g.Return((g.This() == g.Arg("o").Cast(DBBool)).Cast<bool>()); } g.CatchAll(); { g.Return(false); } g.End(); } // Override the Object.GetHashCode() method: g = DBBool.Public.Override.Method<int>("GetHashCode"); { g.Return(value); } // Override the ToString method to convert DBBool to a string: g = DBBool.Public.Override.Method<string>("ToString"); { g.Switch(value); { g.Case(-1); g.Return("DBBool.False"); g.Case(0); g.Return("DBBool.Null"); g.Case(1); g.Return("DBBool.True"); g.DefaultCase(); g.Throw(Exp.New<InvalidOperationException>()); } g.End(); } } TypeGen Test = ag.Class("Test"); { CodeGen g = Test.Static.Void("Main"); { Operand a = g.Local(DBBool), b = g.Local(DBBool); g.Assign(a, Static.Field(DBBool, "dbTrue")); g.Assign(b, Static.Field(DBBool, "dbNull")); g.WriteLine("!{0} = {1}", a, !a); g.WriteLine("!{0} = {1}", b, !b); g.WriteLine("{0} & {1} = {2}", a, b, a & b); g.WriteLine("{0} | {1} = {2}", a, b, a | b); // Invoke the true operator to determine the Boolean // value of the DBBool variable: g.If(b); { g.WriteLine("b is definitely true"); } g.Else(); { g.WriteLine("b is not definitely true"); } g.End(); } } } } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { /// <summary> /// Definition of protection entity operations for the Site Recovery /// extension. /// </summary> public partial interface IProtectionEntityOperations { /// <summary> /// Commit failover of a protection entity. /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginCommitFailoverAsync(string pcName, string name, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Planned failover of a protection entity. /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginPlannedFailoverAsync(string pcName, string name, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Reprotect operation for the given protection entity. /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginReprotectAsync(string pcName, string name, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Test failover of a protection entity. /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginTestFailoverAsync(string pcName, string name, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Unplanned failover of a protection entity. /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Unplanned failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginUnplannedFailoverAsync(string pcName, string name, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> CommitFailoverAsync(string pcName, string name, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Disable Protection for the given protection enity. /// </summary> /// <param name='protectionContainerId'> /// Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Protection entity ID. /// </param> /// <param name='input'> /// Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> DisableProtectionAsync(string protectionContainerId, string protectionEntityId, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='protectionContainerId'> /// Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Protection entity ID. /// </param> /// <param name='input'> /// Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> EnableProtectionAsync(string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Get the protection entity object by Id. /// </summary> /// <param name='protectionContainerId'> /// Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Vm object. /// </returns> Task<ProtectionEntityResponse> GetAsync(string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<CommitFailoverOperationResponse> GetCommitFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<PlannedFailoverOperationResponse> GetPlannedFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<ReprotectOperationResponse> GetReprotectStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<TestFailoverOperationResponse> GetTestFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<UnplannedFailoverOperationResponse> GetUnplannedFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Get the list of all protection entities. /// </summary> /// <param name='protectionContainerId'> /// Parent Protection Container ID. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list Vm operation. /// </returns> Task<ProtectionEntityListResponse> ListAsync(string protectionContainerId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> PlannedFailoverAsync(string pcName, string name, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> ReprotectAsync(string pcName, string name, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> TestFailoverAsync(string pcName, string name, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='pcName'> /// Parent Protection Container name. /// </param> /// <param name='name'> /// Protection entity name. /// </param> /// <param name='parameters'> /// Unplanned failover request. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> UnplannedFailoverAsync(string pcName, string name, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Entities; using Signum.Engine.Maps; using Signum.Utilities; using Signum.Utilities.Reflection; using Signum.Engine.Basics; using System.Threading; using System.Threading.Tasks; using Signum.Utilities.ExpressionTrees; using System.Diagnostics.CodeAnalysis; namespace Signum.Engine { public interface IRetriever : IDisposable { Dictionary<string, object> GetUserData(); T? Complete<T>(PrimaryKey? id, Action<T> complete) where T : Entity; T? Request<T>(PrimaryKey? id) where T : Entity; T? RequestIBA<T>(PrimaryKey? typeId, string? id) where T : class, IEntity; Lite<T>? RequestLite<T>(Lite<T>? lite) where T : class, IEntity; T? ModifiablePostRetrieving<T>(T? entity) where T : Modifiable; IRetriever? Parent { get; } void CompleteAll(); Task CompleteAllAsync(CancellationToken token); ModifiedState ModifiedState { get; } } class RealRetriever : IRetriever { Dictionary<string, object>? userData; public Dictionary<string, object> GetUserData() => userData ?? (userData = new Dictionary<string, object>()); public IRetriever? Parent { get { return null; } } public RealRetriever(EntityCache.RealEntityCache entityCache) { this.entityCache = entityCache; } EntityCache.RealEntityCache entityCache; Dictionary<(Type type, PrimaryKey id), Entity> retrieved = new Dictionary<(Type type, PrimaryKey id), Entity>(); Dictionary<Type, Dictionary<PrimaryKey, Entity>>? requests; Dictionary<(Type type, PrimaryKey id), List<Lite<IEntity>>>? liteRequests; List<Modifiable> modifiablePostRetrieving = new List<Modifiable>(); bool TryGetRequest((Type type, PrimaryKey id) key, [NotNullWhen(true)]out Entity? value) { if (requests != null && requests.TryGetValue(key.type, out var dic) && dic.TryGetValue(key.id, out value)) return true; value = null!; return false; } public T? Complete<T>(PrimaryKey? id, Action<T> complete) where T : Entity { if (id == null) return null; var tuple = (typeof(T), id.Value); if (entityCache.TryGetValue(tuple, out var result)) return (T)result; if (retrieved.TryGetValue(tuple, out result)) return (T)result; T entity; if (TryGetRequest(tuple, out result)) { entity = (T)result; requests![typeof(T)].Remove(id.Value); } else { entity = EntityCache.Construct<T>(id.Value); } retrieved.Add(tuple, entity); complete(entity); return entity; } static GenericInvoker<Func<RealRetriever, PrimaryKey?, Entity>> giRequest = new GenericInvoker<Func<RealRetriever, PrimaryKey?, Entity>>((rr, id) => rr.Request<Entity>(id)!); public T? Request<T>(PrimaryKey? id) where T : Entity { if (id == null) return null; var tuple = (type: typeof(T), id: id.Value); if (entityCache.TryGetValue(tuple, out Entity? ident)) return (T)ident; if (retrieved.TryGetValue(tuple, out ident)) return (T)ident; ICacheController? cc = Schema.Current.CacheController(typeof(T)); if (cc != null && cc.Enabled) { T entityFromCache = EntityCache.Construct<T>(id.Value); retrieved.Add(tuple, entityFromCache); //Cycles cc.Complete(entityFromCache, this); return entityFromCache; } ident = (T?)requests?.TryGetC(typeof(T))?.TryGetC(id.Value); if (ident != null) return (T)ident; T entity = EntityCache.Construct<T>(id.Value); if (requests == null) requests = new Dictionary<Type, Dictionary<PrimaryKey, Entity>>(); requests.GetOrCreate(tuple.type).Add(tuple.id, entity); return entity; } public T? RequestIBA<T>(PrimaryKey? typeId, string? id) where T : class, IEntity { if (id == null) return null; Type type = TypeLogic.IdToType[typeId!.Value]; var parsedId = PrimaryKey.Parse(id, type); return (T)(IEntity)giRequest.GetInvoker(type)(this, parsedId); } public Lite<T>? RequestLite<T>(Lite<T>? lite) where T : class, IEntity { if (lite == null) return null; ICacheController? cc = Schema.Current.CacheController(lite.EntityType); if (cc != null && cc.Enabled) { lite.SetToString(cc.TryGetToString(lite.Id) ?? ("[" + EngineMessage.EntityWithType0AndId1NotFound.NiceToString().FormatWith(lite.EntityType.NiceName(), lite.Id) + "]")); return lite; } var tuple = (type: lite.EntityType, id: lite.Id); if (liteRequests == null) liteRequests = new Dictionary<(Type type, PrimaryKey id), List<Lite<IEntity>>>(); liteRequests.GetOrCreate(tuple).Add(lite); return lite; } public T? ModifiablePostRetrieving<T>(T? modifiable) where T : Modifiable { if (modifiable != null) modifiablePostRetrieving.Add(modifiable); return modifiable; } public Task CompleteAllAsync(CancellationToken token) => CompleteAllPrivate(token); public void CompleteAll() { try { CompleteAllPrivate(null).Wait(); } catch (AggregateException ag) { var ex = ag.InnerExceptions.FirstEx(); ex.PreserveStackTrace(); throw ex; } } public async Task CompleteAllPrivate(CancellationToken? token) { retry: if (requests != null) { while (requests.Count > 0) { var group = requests.WithMax(a => a.Value.Count); var dic = group.Value; ICacheController? cc = Schema.Current.CacheController(group.Key); if (cc != null && cc.Enabled) { cc.Load(); while (dic.Count > 0) { Entity ident = dic.Values.FirstEx(); cc.Complete(ident, this); retrieved.Add((type: ident.GetType(), id : ident.Id), ident); dic.Remove(ident.Id); } } else { if (token == null) Database.RetrieveList(group.Key, dic.Keys.ToList()); else await Database.RetrieveListAsync(group.Key, dic.Keys.ToList(), token.Value); } if (dic.Count == 0) requests.Remove(group.Key); } } if (liteRequests != null) { { List<(Type type, PrimaryKey id)>? toRemove = null; foreach (var item in liteRequests) { var entity = retrieved.TryGetC(item.Key); if (entity != null) { var toStr = entity.ToString(); foreach (var lite in item.Value) lite.SetToString(toStr); if (toRemove == null) toRemove = new List<(Type type, PrimaryKey id)>(); toRemove.Add(item.Key); } } if (toRemove != null) liteRequests.RemoveRange(toRemove); } while (liteRequests.Count > 0) { var group = liteRequests.GroupBy(a => a.Key.type).FirstEx(); var dic = await giGetStrings.GetInvoker(group.Key)(group.Select(a => a.Key.id).ToList(), token); foreach (var item in group) { var toStr = dic.TryGetC(item.Key.id) ?? ("[" + EngineMessage.EntityWithType0AndId1NotFound.NiceToString().FormatWith(item.Key.type.NiceName(), item.Key.id) + "]"); foreach (var lite in item.Value) { lite.SetToString(toStr); } } liteRequests.RemoveRange(group.Select(a => a.Key)); } } var currentlyRetrieved = retrieved.Values.ToHashSet(); var currentlyModifiableRetrieved = modifiablePostRetrieving.ToHashSet(Signum.Utilities.DataStructures.ReferenceEqualityComparer<Modifiable>.Default); foreach (var entity in currentlyRetrieved) { entity.PostRetrieving(); Schema.Current.OnRetrieved(entity); entityCache.Add(entity); } foreach (var embedded in currentlyModifiableRetrieved) embedded.PostRetrieving(); ModifiedState ms = ModifiedState; foreach (var entity in currentlyRetrieved) { entity.Modified = ms; entity.IsNew = false; } foreach (var embedded in currentlyModifiableRetrieved) embedded.Modified = ms; if (liteRequests != null && liteRequests.Count > 0 || requests != null && requests.Count > 0 || retrieved.Count > currentlyRetrieved.Count ) // PostRetrieving could retrieve as well { retrieved.RemoveAll(a => currentlyRetrieved.Contains(a.Value)); modifiablePostRetrieving.RemoveAll(a => currentlyModifiableRetrieved.Contains(a)); goto retry; } } static readonly GenericInvoker<Func<List<PrimaryKey>, CancellationToken?, Task<Dictionary<PrimaryKey, string>>>> giGetStrings = new GenericInvoker<Func<List<PrimaryKey>, CancellationToken?, Task<Dictionary<PrimaryKey, string>>>>((ids, token) => GetStrings<Entity>(ids, token)); static async Task<Dictionary<PrimaryKey, string>> GetStrings<T>(List<PrimaryKey> ids, CancellationToken? token) where T : Entity { ICacheController? cc = Schema.Current.CacheController(typeof(T)); if (cc != null && cc.Enabled) { cc.Load(); return ids.ToDictionary(a => a, a => cc.TryGetToString(a)!); } else if (token != null) { var tasks = ids.GroupsOf(Schema.Current.Settings.MaxNumberOfParameters) .Select(gr => Database.Query<T>().Where(e => gr.Contains(e.Id)).Select(a => KeyValuePair.Create(a.Id, a.ToString())).ToListAsync(token!.Value)) .ToList(); var list = await Task.WhenAll(tasks); return list.SelectMany(li => li).ToDictionary(); } else { var dic = ids.GroupsOf(Schema.Current.Settings.MaxNumberOfParameters) .SelectMany(gr => Database.Query<T>().Where(e => gr.Contains(e.Id)).Select(a => KeyValuePair.Create(a.Id, a.ToString()))) .ToDictionaryEx(); return dic; } } public void Dispose() { entityCache.ReleaseRetriever(this); } public ModifiedState ModifiedState { get { return this.entityCache.IsSealed ? ModifiedState.Sealed : ModifiedState.Clean; } } } class ChildRetriever : IRetriever { public Dictionary<string, object> GetUserData() => this.parent.GetUserData(); EntityCache.RealEntityCache entityCache; public IRetriever parent; public IRetriever? Parent => parent; public ChildRetriever(IRetriever parent, EntityCache.RealEntityCache entityCache) { this.parent= parent; this.entityCache = entityCache; } public T? Complete<T>(PrimaryKey? id, Action<T> complete) where T : Entity { return parent.Complete<T>(id, complete); } public T? Request<T>(PrimaryKey? id) where T : Entity { return parent.Request<T>(id); } public T? RequestIBA<T>(PrimaryKey? typeId, string? id) where T : class, IEntity { return parent.RequestIBA<T>(typeId, id); } public Lite<T>? RequestLite<T>(Lite<T>? lite) where T : class, IEntity { return parent.RequestLite<T>(lite); } public T? ModifiablePostRetrieving<T>(T? entity) where T : Modifiable { return parent.ModifiablePostRetrieving(entity); } public void CompleteAll() { } public Task CompleteAllAsync(CancellationToken token) { return Task.CompletedTask; } public void Dispose() { entityCache.ReleaseRetriever(this); } public ModifiedState ModifiedState { get { return this.entityCache.IsSealed ? ModifiedState.Sealed : ModifiedState.Clean; } } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics.Animation; using FlatRedBall.Instructions; using FlatRedBall.Content.Instructions; using FlatRedBall.Content.AnimationChain; using FlatRedBall.IO; using Microsoft.Xna.Framework.Graphics; namespace FlatRedBall.Graphics.Particle { #region XML Docs /// <summary> /// Save class for the EmissionSettings class. This class is used /// in the .emix (Emitter XML) file. /// </summary> #endregion public class EmissionSettingsSave { #region Fields #region Velocity RangeType mVelocityRangeType = RangeType.Component; float mRadialVelocity; float mRadialVelocityRange; float mXVelocity; float mYVelocity; float mZVelocity; float mXVelocityRange; float mYVelocityRange; float mZVelocityRange; float mWedgeAngle; float mWedgeSpread; #endregion #region Rotation bool mBillboarded; float mRotationX; float mRotationXVelocity; float mRotationXRange; float mRotationXVelocityRange; float mRotationY; float mRotationYVelocity; float mRotationYRange; float mRotationYVelocityRange; float mRotationZ; float mRotationZVelocity; float mRotationZRange; float mRotationZVelocityRange; #endregion #region Acceleration float mXAcceleration; float mYAcceleration; float mZAcceleration; float mXAccelerationRange; float mYAccelerationRange; float mZAccelerationRange; #endregion #region Scale float mScaleX; float mScaleY; float mScaleXRange; float mScaleYRange; float mScaleXVelocity; float mScaleYVelocity; float mScaleXVelocityRange; float mScaleYVelocityRange; bool mMatchScaleXToY; #endregion float mFade; float mTintRed; float mTintGreen; float mTintBlue; float mFadeRate; float mTintRedRate; float mTintGreenRate; float mTintBlueRate; string mBlendOperation; string mColorOperation; bool mAnimate; InstructionBlueprintListSave mInstructions; float mDrag = 0; #endregion #region Properties #region Velocity public RangeType VelocityRangeType { get { return mVelocityRangeType; } set { mVelocityRangeType = value; } } public float RadialVelocity { get { return mRadialVelocity; } set { mRadialVelocity = value; } } public float RadialVelocityRange { get { return mRadialVelocityRange; } set { mRadialVelocityRange = value; } } public float XVelocity { get { return mXVelocity; } set { mXVelocity = value; } } public float YVelocity { get { return mYVelocity; } set { mYVelocity = value; } } public float ZVelocity { get { return mZVelocity; } set { mZVelocity = value; } } public float XVelocityRange { get { return mXVelocityRange; } set { mXVelocityRange = value; } } public float YVelocityRange { get { return mYVelocityRange; } set { mYVelocityRange = value; } } public float ZVelocityRange { get { return mZVelocityRange; } set { mZVelocityRange = value; } } public float WedgeAngle { get { return mWedgeAngle; } set { mWedgeAngle = value; } } public float WedgeSpread { get { return mWedgeSpread; } set { mWedgeSpread = value; } } #endregion #region Rotation public bool Billboarded { get { return mBillboarded; } set { mBillboarded = value; } } public float RotationX { get { return mRotationX; } set { mRotationX = value; } } public float RotationXVelocity { get { return mRotationXVelocity; } set { mRotationXVelocity = value; } } public float RotationXRange { get { return mRotationXRange; } set { mRotationXRange = value; } } public float RotationXVelocityRange { get { return mRotationXVelocityRange; } set { mRotationXVelocityRange = value; } } public float RotationY { get { return mRotationY; } set { mRotationY = value; } } public float RotationYVelocity { get { return mRotationYVelocity; } set { mRotationYVelocity = value; } } public float RotationYRange { get { return mRotationYRange; } set { mRotationYRange = value; } } public float RotationYVelocityRange { get { return mRotationYVelocityRange; } set { mRotationYVelocityRange = value; } } public float RotationZ { get { return mRotationZ; } set { mRotationZ = value; } } public float RotationZVelocity { get { return mRotationZVelocity; } set { mRotationZVelocity = value; } } public float RotationZRange { get { return mRotationZRange; } set { mRotationZRange = value; } } public float RotationZVelocityRange { get { return mRotationZVelocityRange; } set { mRotationZVelocityRange = value; } } #endregion #region Acceleration / Drag public float XAcceleration { get { return mXAcceleration; } set { mXAcceleration = value; } } public float YAcceleration { get { return mYAcceleration; } set { mYAcceleration = value; } } public float ZAcceleration { get { return mZAcceleration; } set { mZAcceleration = value; } } public float XAccelerationRange { get { return mXAccelerationRange; } set { mXAccelerationRange = value; } } public float YAccelerationRange { get { return mYAccelerationRange; } set { mYAccelerationRange = value; } } public float ZAccelerationRange { get { return mZAccelerationRange; } set { mZAccelerationRange = value; } } public float Drag { get { return mDrag; } set { mDrag = value; } } #endregion #region Scale public float ScaleX { get { return mScaleX; } set { mScaleX = value; } } public float ScaleY { get { return mScaleY; } set { mScaleY = value; } } public float ScaleXRange { get { return mScaleXRange; } set { mScaleXRange = value; } } public float ScaleYRange { get { return mScaleYRange; } set { mScaleYRange = value; } } public float ScaleXVelocity { get { return mScaleXVelocity; } set { mScaleXVelocity = value; } } public float ScaleYVelocity { get { return mScaleYVelocity; } set { mScaleYVelocity = value; } } public float ScaleXVelocityRange { get { return mScaleXVelocityRange; } set { mScaleXVelocityRange = value; } } public float ScaleYVelocityRange { get { return mScaleYVelocityRange; } set { mScaleYVelocityRange = value; } } public bool MatchScaleXToY { get { return mMatchScaleXToY; } set { mMatchScaleXToY = value; } } // Compiling with C# 6.0 still causes problems on Android float textureScale = 1; public float TextureScale { get { return textureScale; } set { textureScale = value; } } #endregion #region Tint/Fade/Blend/Color public float Fade { get { return mFade; } set { mFade = value; } } public float TintRed { get { return mTintRed; } set { mTintRed = value; } } public float TintGreen { get { return mTintGreen; } set { mTintGreen = value; } } public float TintBlue { get { return mTintBlue; } set { mTintBlue = value; } } public float FadeRate { get { return mFadeRate; } set { mFadeRate = value; } } public float TintRedRate { get { return mTintRedRate; } set { mTintRedRate = value; } } public float TintGreenRate { get { return mTintGreenRate; } set { mTintGreenRate = value; } } public float TintBlueRate { get { return mTintBlueRate; } set { mTintBlueRate = value; } } public string BlendOperation { get { return mBlendOperation; } set { mBlendOperation = value; } } public string ColorOperation { get { return mColorOperation; } set { mColorOperation = value; } } #endregion #region Texture/Animation Settings /// <summary> /// Whether or not the emitted particle should automatically animate /// </summary> public bool Animate { get { return mAnimate; } set { mAnimate = value; } } /// <summary> /// The animation chains to use for the particle animation /// </summary> public string AnimationChains { get; set; } /// <summary> /// The chain that is currently animating /// </summary> public string CurrentChainName { get; set; } /// <summary> /// The particle texture. /// If animation chains are set, they should override this. /// </summary> public string Texture { get; set; } #endregion public InstructionBlueprintListSave Instructions { get { return mInstructions; } set { mInstructions = value; } } #endregion #region Methods #region Constructor public EmissionSettingsSave() { mVelocityRangeType = RangeType.Radial; mRadialVelocity = 1; mScaleX = 1; mScaleY = 1; mFade = 1; mColorOperation = ""; mBlendOperation = ""; } #endregion public static EmissionSettingsSave FromEmissionSettings(EmissionSettings emissionSettings) { EmissionSettingsSave emissionSettingsSave = new EmissionSettingsSave(); emissionSettingsSave.mVelocityRangeType = emissionSettings.VelocityRangeType; emissionSettingsSave.mRadialVelocity = emissionSettings.RadialVelocity; emissionSettingsSave.mRadialVelocityRange = emissionSettings.RadialVelocityRange; emissionSettingsSave.mXVelocity = emissionSettings.XVelocity; emissionSettingsSave.mYVelocity = emissionSettings.YVelocity; emissionSettingsSave.mZVelocity = emissionSettings.ZVelocity; emissionSettingsSave.mXVelocityRange = emissionSettings.XVelocityRange; emissionSettingsSave.mYVelocityRange = emissionSettings.YVelocityRange; emissionSettingsSave.mZVelocityRange = emissionSettings.ZVelocityRange; emissionSettingsSave.mWedgeAngle = emissionSettings.WedgeAngle; emissionSettingsSave.mWedgeSpread = emissionSettings.WedgeSpread; emissionSettingsSave.Billboarded = emissionSettings.Billboarded; emissionSettingsSave.mRotationX = emissionSettings.RotationX; emissionSettingsSave.mRotationXVelocity = emissionSettings.RotationXVelocity; emissionSettingsSave.mRotationXRange = emissionSettings.RotationXRange; emissionSettingsSave.mRotationXVelocityRange = emissionSettings.RotationXVelocityRange; emissionSettingsSave.mRotationY = emissionSettings.RotationY; emissionSettingsSave.mRotationYVelocity = emissionSettings.RotationYVelocity; emissionSettingsSave.mRotationYRange = emissionSettings.RotationYRange; emissionSettingsSave.mRotationYVelocityRange = emissionSettings.RotationYVelocityRange; emissionSettingsSave.mRotationZ = emissionSettings.RotationZ; emissionSettingsSave.mRotationZVelocity = emissionSettings.RotationZVelocity; emissionSettingsSave.mRotationZRange = emissionSettings.RotationZRange; emissionSettingsSave.mRotationZVelocityRange = emissionSettings.RotationZVelocityRange; emissionSettingsSave.mXAcceleration = emissionSettings.XAcceleration; emissionSettingsSave.mYAcceleration = emissionSettings.YAcceleration; emissionSettingsSave.mZAcceleration = emissionSettings.ZAcceleration; emissionSettingsSave.mXAccelerationRange = emissionSettings.XAccelerationRange; emissionSettingsSave.mYAccelerationRange = emissionSettings.YAccelerationRange; emissionSettingsSave.mZAccelerationRange = emissionSettings.ZAccelerationRange; emissionSettingsSave.mScaleX = emissionSettings.ScaleX; emissionSettingsSave.mScaleY = emissionSettings.ScaleY; emissionSettingsSave.mScaleXRange = emissionSettings.ScaleXRange; emissionSettingsSave.mScaleYRange = emissionSettings.ScaleYRange; emissionSettingsSave.mMatchScaleXToY = emissionSettings.MatchScaleXToY; emissionSettingsSave.mScaleXVelocity = emissionSettings.ScaleXVelocity; emissionSettingsSave.mScaleYVelocity = emissionSettings.ScaleYVelocity; emissionSettingsSave.mScaleXVelocityRange = emissionSettings.ScaleXVelocityRange; emissionSettingsSave.mScaleYVelocityRange = emissionSettings.ScaleYVelocityRange; if (emissionSettings.TextureScale > 0) { emissionSettingsSave.TextureScale = emissionSettings.TextureScale; } else { emissionSettingsSave.TextureScale = -1; } int multiple = 255; emissionSettingsSave.mFade = (1 - emissionSettings.Alpha) * 255; emissionSettingsSave.mTintRed = emissionSettings.Red * 255; emissionSettingsSave.mTintGreen = emissionSettings.Green * 255; emissionSettingsSave.mTintBlue = emissionSettings.Blue * 255; emissionSettingsSave.mFadeRate = -emissionSettings.AlphaRate*255; emissionSettingsSave.mTintRedRate = emissionSettings.RedRate*255; emissionSettingsSave.mTintGreenRate = emissionSettings.GreenRate*255; emissionSettingsSave.mTintBlueRate = emissionSettings.BlueRate*255; emissionSettingsSave.mBlendOperation = GraphicalEnumerations.BlendOperationToFlatRedBallMdxString(emissionSettings.BlendOperation); emissionSettingsSave.mColorOperation = GraphicalEnumerations.ColorOperationToFlatRedBallMdxString( emissionSettings.ColorOperation); // preserve animation and texture settings emissionSettingsSave.mAnimate = emissionSettings.Animate; // TODO: Justin - not sure if we need to force relative here? emissionSettingsSave.AnimationChains = emissionSettings.AnimationChains.Name; emissionSettingsSave.CurrentChainName = emissionSettings.CurrentChainName; // TODO: Justin - not sure if we neet to force relative here? emissionSettingsSave.Texture = emissionSettings.Texture.Name; emissionSettingsSave.Instructions = InstructionBlueprintListSave.FromInstructionBlueprintList(emissionSettings.Instructions); foreach (InstructionSave blueprint in emissionSettingsSave.Instructions.Instructions) { if (GraphicalEnumerations.ConvertableSpriteProperties.Contains(blueprint.Member)) { blueprint.Value = (float)blueprint.Value * multiple; } } emissionSettingsSave.mDrag = emissionSettings.Drag; return emissionSettingsSave; } public void InvertHandedness() { mZVelocity = -mZVelocity; mZVelocityRange = -mZVelocityRange; mRotationY = -mRotationY; mRotationYVelocity = -mRotationYVelocity; mRotationYRange = -mRotationYRange; mRotationYVelocityRange = -mRotationYVelocityRange; mZAcceleration = -mZAcceleration; mZAccelerationRange = -mZAccelerationRange; } public EmissionSettings ToEmissionSettings(string contentManagerName) { EmissionSettings emissionSettings = new EmissionSettings(); emissionSettings.VelocityRangeType = VelocityRangeType; emissionSettings.RadialVelocity = RadialVelocity; emissionSettings.RadialVelocityRange = RadialVelocityRange; emissionSettings.Billboarded = Billboarded; emissionSettings.XVelocity = XVelocity; emissionSettings.YVelocity = YVelocity; emissionSettings.ZVelocity = ZVelocity; emissionSettings.XVelocityRange = XVelocityRange; emissionSettings.YVelocityRange = YVelocityRange; emissionSettings.ZVelocityRange = ZVelocityRange; emissionSettings.WedgeAngle = WedgeAngle; emissionSettings.WedgeSpread = WedgeSpread; emissionSettings.RotationX = RotationX; emissionSettings.RotationXVelocity = RotationXVelocity; emissionSettings.RotationXRange = RotationXRange; emissionSettings.RotationXVelocityRange = RotationXVelocityRange; emissionSettings.RotationY = RotationY; emissionSettings.RotationYVelocity = RotationYVelocity; emissionSettings.RotationYRange = RotationYRange; emissionSettings.RotationYVelocityRange = RotationYVelocityRange; emissionSettings.RotationZ = RotationZ; emissionSettings.RotationZVelocity = RotationZVelocity; emissionSettings.RotationZRange = RotationZRange; emissionSettings.RotationZVelocityRange = RotationZVelocityRange; emissionSettings.XAcceleration = XAcceleration; emissionSettings.YAcceleration = YAcceleration; emissionSettings.ZAcceleration = ZAcceleration; emissionSettings.XAccelerationRange = XAccelerationRange; emissionSettings.YAccelerationRange = YAccelerationRange; emissionSettings.ZAccelerationRange = ZAccelerationRange; emissionSettings.Drag = Drag; emissionSettings.ScaleX = ScaleX; emissionSettings.ScaleY = ScaleY; emissionSettings.ScaleXRange = ScaleXRange; emissionSettings.ScaleYRange = ScaleYRange; emissionSettings.ScaleXVelocity = ScaleXVelocity; emissionSettings.ScaleYVelocity = ScaleYVelocity; emissionSettings.ScaleXVelocityRange = ScaleXVelocityRange; emissionSettings.ScaleYVelocityRange = ScaleYVelocityRange; emissionSettings.MatchScaleXToY = MatchScaleXToY; if (TextureScale > 0) { emissionSettings.TextureScale = TextureScale; } else { emissionSettings.TextureScale = -1; } #if FRB_MDX float divisionValue = 1; #else float divisionValue = 255; #endif emissionSettings.Alpha = (255 - Fade) / divisionValue; emissionSettings.Red = TintRed / divisionValue; emissionSettings.Green = TintGreen / divisionValue; emissionSettings.Blue = TintBlue / divisionValue; emissionSettings.AlphaRate = -FadeRate / divisionValue; emissionSettings.RedRate = TintRedRate / divisionValue; emissionSettings.BlueRate = TintBlueRate / divisionValue; emissionSettings.GreenRate = TintGreenRate / divisionValue; emissionSettings.BlendOperation = GraphicalEnumerations.TranslateBlendOperation(BlendOperation); emissionSettings.ColorOperation = GraphicalEnumerations.TranslateColorOperation(ColorOperation); emissionSettings.Animate = Animate; emissionSettings.CurrentChainName = CurrentChainName; // load the animation chains or the texture but not both // chains take priority over texture? if (!string.IsNullOrEmpty(AnimationChains)) { // load the animation chain, note that this could throw an exception if file names are bad or chain doesn't exist! emissionSettings.AnimationChains = FlatRedBallServices.Load<AnimationChainList>(AnimationChains, contentManagerName); if (!string.IsNullOrEmpty(CurrentChainName)) { emissionSettings.AnimationChain = emissionSettings.AnimationChains[emissionSettings.CurrentChainName]; } } else { if (!string.IsNullOrEmpty(Texture)) { // load the texture, emissionSettings.Texture = FlatRedBallServices.Load<Texture2D>(Texture, contentManagerName); } } if (Instructions != null) { emissionSettings.Instructions = Instructions.ToInstructionBlueprintList(); foreach (InstructionBlueprint blueprint in emissionSettings.Instructions) { if (GraphicalEnumerations.ConvertableSpriteProperties.Contains(blueprint.MemberName)) { blueprint.MemberValue = (float)blueprint.MemberValue / divisionValue; } //if(blueprint.MemberName.Equals("Alpha")){ //} //else if(blueprint.MemberName.Equals("AlphaRate")){ //} //else if(blueprint.MemberName.Equals("Blue")){ //} //else if(blueprint.MemberName.Equals("BlueRate")){ //} //else if(blueprint.MemberName.Equals("Green")){ //} //else if(blueprint.MemberName.Equals("GreenRate")){ //} //else if(blueprint.MemberName.Equals("Red")){ //} //else if(blueprint.MemberName.Equals("RedRate")){ //} } } // TODO: Add support for saving AnimationChains. Probably need to change the mAnimation // field from an AnimationChain to an AnimationChainSave return emissionSettings; } #endregion } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmLogin { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmLogin() : base() { Load += frmLogin_Load; KeyPress += frmLogin_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.TextBox withEventsField_txtUserName; public System.Windows.Forms.TextBox txtUserName { get { return withEventsField_txtUserName; } set { if (withEventsField_txtUserName != null) { withEventsField_txtUserName.Enter -= txtUserName_Enter; } withEventsField_txtUserName = value; if (withEventsField_txtUserName != null) { withEventsField_txtUserName.Enter += txtUserName_Enter; } } } private System.Windows.Forms.Button withEventsField_cmdOK; public System.Windows.Forms.Button cmdOK { get { return withEventsField_cmdOK; } set { if (withEventsField_cmdOK != null) { withEventsField_cmdOK.Click -= cmdOK_Click; } withEventsField_cmdOK = value; if (withEventsField_cmdOK != null) { withEventsField_cmdOK.Click += cmdOK_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtPassword; public System.Windows.Forms.TextBox txtPassword { get { return withEventsField_txtPassword; } set { if (withEventsField_txtPassword != null) { withEventsField_txtPassword.Enter -= txtPassword_Enter; } withEventsField_txtPassword = value; if (withEventsField_txtPassword != null) { withEventsField_txtPassword.Enter += txtPassword_Enter; } } } public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label Label1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmLogin)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.txtUserName = new System.Windows.Forms.TextBox(); this.cmdOK = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.txtPassword = new System.Windows.Forms.TextBox(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Text = "4 POS Application Suite"; this.ClientSize = new System.Drawing.Size(348, 234); this.Location = new System.Drawing.Point(189, 232); this.ControlBox = false; this.Icon = (System.Drawing.Icon)resources.GetObject("frmLogin.Icon"); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.BackgroundImage = (System.Drawing.Image)resources.GetObject("frmLogin.BackgroundImage"); this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmLogin"; this.txtUserName.AutoSize = false; this.txtUserName.Size = new System.Drawing.Size(187, 16); this.txtUserName.Location = new System.Drawing.Point(108, 100); this.txtUserName.TabIndex = 0; this.txtUserName.Text = "default"; this.txtUserName.AcceptsReturn = true; this.txtUserName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtUserName.BackColor = System.Drawing.SystemColors.Window; this.txtUserName.CausesValidation = true; this.txtUserName.Enabled = true; this.txtUserName.ForeColor = System.Drawing.SystemColors.WindowText; this.txtUserName.HideSelection = true; this.txtUserName.ReadOnly = false; this.txtUserName.MaxLength = 0; this.txtUserName.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtUserName.Multiline = false; this.txtUserName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtUserName.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtUserName.TabStop = true; this.txtUserName.Visible = true; this.txtUserName.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtUserName.Name = "txtUserName"; this.cmdOK.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdOK.Text = "&OK"; this.cmdOK.Size = new System.Drawing.Size(76, 26); this.cmdOK.Location = new System.Drawing.Point(34, 150); this.cmdOK.TabIndex = 2; this.cmdOK.BackColor = System.Drawing.SystemColors.Control; this.cmdOK.CausesValidation = true; this.cmdOK.Enabled = true; this.cmdOK.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdOK.Cursor = System.Windows.Forms.Cursors.Default; this.cmdOK.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdOK.TabStop = true; this.cmdOK.Name = "cmdOK"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.CancelButton = this.cmdCancel; this.cmdCancel.Text = "E&xit"; this.cmdCancel.Size = new System.Drawing.Size(76, 26); this.cmdCancel.Location = new System.Drawing.Point(222, 148); this.cmdCancel.TabIndex = 3; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.TabStop = true; this.cmdCancel.Name = "cmdCancel"; this.txtPassword.AutoSize = false; this.txtPassword.Size = new System.Drawing.Size(187, 16); this.txtPassword.ImeMode = System.Windows.Forms.ImeMode.Disable; this.txtPassword.Location = new System.Drawing.Point(108, 122); this.txtPassword.PasswordChar = Strings.ChrW(42); this.txtPassword.TabIndex = 1; this.txtPassword.Text = "password"; this.txtPassword.AcceptsReturn = true; this.txtPassword.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtPassword.BackColor = System.Drawing.SystemColors.Window; this.txtPassword.CausesValidation = true; this.txtPassword.Enabled = true; this.txtPassword.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPassword.HideSelection = true; this.txtPassword.ReadOnly = false; this.txtPassword.MaxLength = 0; this.txtPassword.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPassword.Multiline = false; this.txtPassword.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPassword.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPassword.TabStop = true; this.txtPassword.Visible = true; this.txtPassword.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtPassword.Name = "txtPassword"; this.Label2.Text = "If this is a New Installation please click OK to continue. Passwords may be maintained under Store Setup && Security once you have logged in."; this.Label2.ForeColor = System.Drawing.Color.White; this.Label2.Size = new System.Drawing.Size(273, 41); this.Label2.Location = new System.Drawing.Point(56, 190); this.Label2.TabIndex = 5; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Enabled = true; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.Label1.Text = "NOTE : "; this.Label1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.Label1.ForeColor = System.Drawing.Color.White; this.Label1.Size = new System.Drawing.Size(49, 17); this.Label1.Location = new System.Drawing.Point(8, 190); this.Label1.TabIndex = 4; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Enabled = true; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.Controls.Add(txtUserName); this.Controls.Add(cmdOK); this.Controls.Add(cmdCancel); this.Controls.Add(txtPassword); this.Controls.Add(Label2); this.Controls.Add(Label1); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
/* ==================================================================== 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 NPOI.SS.Formula { using System; using System.Collections; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Util; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.Udf; using System.Collections.Generic; using NPOI.SS.UserModel; using NPOI.SS.Formula.PTG; using NPOI.Util; /** * Evaluates formula cells.<p/> * * For performance reasons, this class keeps a cache of all previously calculated intermediate * cell values. Be sure To call {@link #ClearCache()} if any workbook cells are Changed between * calls To evaluate~ methods on this class.<br/> * * For POI internal use only * * @author Josh Micich */ internal class WorkbookEvaluator { private IEvaluationWorkbook _workbook; private EvaluationCache _cache; private int _workbookIx; private IEvaluationListener _evaluationListener; private Hashtable _sheetIndexesBySheet; private Dictionary<String, int> _sheetIndexesByName; private CollaboratingWorkbooksEnvironment _collaboratingWorkbookEnvironment; private IStabilityClassifier _stabilityClassifier; private UDFFinder _udfFinder; public WorkbookEvaluator(IEvaluationWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) : this(workbook, null, stabilityClassifier, udfFinder) { } public WorkbookEvaluator(IEvaluationWorkbook workbook, IEvaluationListener evaluationListener, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { _workbook = workbook; _evaluationListener = evaluationListener; _cache = new EvaluationCache(evaluationListener); _sheetIndexesBySheet = new Hashtable(); _sheetIndexesByName = new Dictionary<string, int>(); _collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY; _workbookIx = 0; _stabilityClassifier = stabilityClassifier; AggregatingUDFFinder defaultToolkit = // workbook can be null in unit tests workbook == null ? null : (AggregatingUDFFinder)workbook.GetUDFFinder(); if (defaultToolkit != null && udfFinder != null) { defaultToolkit.Add(udfFinder); } _udfFinder = defaultToolkit; } /** * also for debug use. Used in ToString methods */ /* package */ public String GetSheetName(int sheetIndex) { return _workbook.GetSheetName(sheetIndex); } public WorkbookEvaluator GetOtherWorkbookEvaluator(String workbookName) { return _collaboratingWorkbookEnvironment.GetWorkbookEvaluator(workbookName); } internal IEvaluationWorkbook Workbook { get { return _workbook; } } internal IEvaluationSheet GetSheet(int sheetIndex) { return _workbook.GetSheet(sheetIndex); } /* package */ internal IEvaluationName GetName(String name, int sheetIndex) { NamePtg namePtg = _workbook.GetName(name, sheetIndex).CreatePtg(); if (namePtg == null) { return null; } else { return _workbook.GetName(namePtg); } } private static bool IsDebugLogEnabled() { return false; } private static void LogDebug(String s) { if (IsDebugLogEnabled()) { Console.WriteLine(s); } } /* package */ public void AttachToEnvironment(CollaboratingWorkbooksEnvironment collaboratingWorkbooksEnvironment, EvaluationCache cache, int workbookIx) { _collaboratingWorkbookEnvironment = collaboratingWorkbooksEnvironment; _cache = cache; _workbookIx = workbookIx; } /* package */ public CollaboratingWorkbooksEnvironment GetEnvironment() { return _collaboratingWorkbookEnvironment; } /* package */ public void DetachFromEnvironment() { _collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY; _cache = new EvaluationCache(_evaluationListener); _workbookIx = 0; } /* package */ public IEvaluationListener GetEvaluationListener() { return _evaluationListener; } /** * Should be called whenever there are Changes To input cells in the evaluated workbook. * Failure To call this method after changing cell values will cause incorrect behaviour * of the evaluate~ methods of this class */ public void ClearAllCachedResultValues() { _cache.Clear(); _sheetIndexesBySheet.Clear(); } /** * Should be called To tell the cell value cache that the specified (value or formula) cell * Has Changed. */ public void NotifyUpdateCell(IEvaluationCell cell) { int sheetIndex = GetSheetIndex(cell.Sheet); _cache.NotifyUpdateCell(_workbookIx, sheetIndex, cell); } /** * Should be called To tell the cell value cache that the specified cell Has just been * deleted. */ public void NotifyDeleteCell(IEvaluationCell cell) { int sheetIndex = GetSheetIndex(cell.Sheet); _cache.NotifyDeleteCell(_workbookIx, sheetIndex, cell); } public int GetSheetIndex(IEvaluationSheet sheet) { object result = _sheetIndexesBySheet[sheet]; if (result == null) { int sheetIndex = _workbook.GetSheetIndex(sheet); if (sheetIndex < 0) { throw new Exception("Specified sheet from a different book"); } result = sheetIndex; _sheetIndexesBySheet[sheet] = result; } return (int)result; } /* package */ internal int GetSheetIndexByExternIndex(int externSheetIndex) { return _workbook.ConvertFromExternSheetIndex(externSheetIndex); } /** * Case-insensitive. * @return -1 if sheet with specified name does not exist */ /* package */ public int GetSheetIndex(String sheetName) { int result; if (_sheetIndexesByName.ContainsKey(sheetName)) { result = _sheetIndexesByName[sheetName]; } else { int sheetIndex = _workbook.GetSheetIndex(sheetName); if (sheetIndex < 0) { return -1; } result = sheetIndex; _sheetIndexesByName[sheetName] = result; } return result; } public ValueEval Evaluate(IEvaluationCell srcCell) { int sheetIndex = GetSheetIndex(srcCell.Sheet); return EvaluateAny(srcCell, sheetIndex, srcCell.RowIndex, srcCell.ColumnIndex, new EvaluationTracker(_cache)); } /** * @return never <c>null</c>, never {@link BlankEval} */ private ValueEval EvaluateAny(IEvaluationCell srcCell, int sheetIndex, int rowIndex, int columnIndex, EvaluationTracker tracker) { bool shouldCellDependencyBeRecorded = _stabilityClassifier == null ? true : !_stabilityClassifier.IsCellFinal(sheetIndex, rowIndex, columnIndex); ValueEval result; if (srcCell == null || srcCell.CellType != CellType.FORMULA) { result = GetValueFromNonFormulaCell(srcCell); if (shouldCellDependencyBeRecorded) { tracker.AcceptPlainValueDependency(_workbookIx, sheetIndex, rowIndex, columnIndex, result); } return result; } FormulaCellCacheEntry cce = _cache.GetOrCreateFormulaCellEntry(srcCell); if (shouldCellDependencyBeRecorded || cce.IsInputSensitive) { tracker.AcceptFormulaDependency(cce); } IEvaluationListener evalListener = _evaluationListener; if (cce.GetValue() == null) { if (!tracker.StartEvaluate(cce)) { return ErrorEval.CIRCULAR_REF_ERROR; } OperationEvaluationContext ec = new OperationEvaluationContext(this, _workbook, sheetIndex, rowIndex, columnIndex, tracker); try { Ptg[] ptgs = _workbook.GetFormulaTokens(srcCell); if (evalListener == null) { result = EvaluateFormula(ec, ptgs); } else { evalListener.OnStartEvaluate(srcCell, cce); result = EvaluateFormula(ec, ptgs); evalListener.OnEndEvaluate(cce, result); } tracker.UpdateCacheResult(result); } catch (NotImplementedException e) { throw AddExceptionInfo(e, sheetIndex, rowIndex, columnIndex); } finally { tracker.EndEvaluate(cce); } } else { if (evalListener != null) { evalListener.OnCacheHit(sheetIndex, rowIndex, columnIndex, cce.GetValue()); } return cce.GetValue(); } if (IsDebugLogEnabled()) { String sheetName = GetSheetName(sheetIndex); CellReference cr = new CellReference(rowIndex, columnIndex); LogDebug("Evaluated " + sheetName + "!" + cr.FormatAsString() + " To " + cce.GetValue().ToString()); } // Usually (result === cce.getValue()) // But sometimes: (result==ErrorEval.CIRCULAR_REF_ERROR, cce.getValue()==null) // When circular references are detected, the cache entry is only updated for // the top evaluation frame //return cce.GetValue(); return result; } /** * Adds the current cell reference to the exception for easier debugging. * Would be nice to get the formula text as well, but that seems to require * too much digging around and casting to get the FormulaRenderingWorkbook. */ private NotImplementedException AddExceptionInfo(NotImplementedException inner, int sheetIndex, int rowIndex, int columnIndex) { try { String sheetName = _workbook.GetSheetName(sheetIndex); CellReference cr = new CellReference(sheetName, rowIndex, columnIndex, false, false); String msg = "Error evaluating cell " + cr.FormatAsString(); return new NotImplementedException(msg, inner); } catch (Exception) { // avoid bombing out during exception handling //e.printStackTrace(); return inner; // preserve original exception } } /** * Gets the value from a non-formula cell. * @param cell may be <c>null</c> * @return {@link BlankEval} if cell is <c>null</c> or blank, never <c>null</c> */ /* package */ internal static ValueEval GetValueFromNonFormulaCell(IEvaluationCell cell) { if (cell == null) { return BlankEval.instance; } CellType cellType = cell.CellType; switch (cellType) { case CellType.NUMERIC: return new NumberEval(cell.NumericCellValue); case CellType.STRING: return new StringEval(cell.StringCellValue); case CellType.BOOLEAN: return BoolEval.ValueOf(cell.BooleanCellValue); case CellType.BLANK: return BlankEval.instance; case CellType.ERROR: return ErrorEval.ValueOf(cell.ErrorCellValue); } throw new Exception("Unexpected cell type (" + cellType + ")"); } // visibility raised for testing /* package */ public ValueEval EvaluateFormula(OperationEvaluationContext ec, Ptg[] ptgs) { Stack<ValueEval> stack = new Stack<ValueEval>(); for (int i = 0, iSize = ptgs.Length; i < iSize; i++) { // since we don't know how To handle these yet :( Ptg ptg = ptgs[i]; if (ptg is AttrPtg) { AttrPtg attrPtg = (AttrPtg)ptg; if (attrPtg.IsSum) { // Excel prefers To encode 'SUM()' as a tAttr Token, but this evaluator // expects the equivalent function Token //byte nArgs = 1; // tAttrSum always Has 1 parameter ptg = FuncVarPtg.SUM;//.Create("SUM", nArgs); } if (attrPtg.IsOptimizedChoose) { ValueEval arg0 = stack.Pop(); int[] jumpTable = attrPtg.JumpTable; int dist; int nChoices = jumpTable.Length; try { int switchIndex = Choose.EvaluateFirstArg(arg0, ec.RowIndex, ec.ColumnIndex); if (switchIndex < 1 || switchIndex > nChoices) { stack.Push(ErrorEval.VALUE_INVALID); dist = attrPtg.ChooseFuncOffset + 4; // +4 for tFuncFar(CHOOSE) } else { dist = jumpTable[switchIndex - 1]; } } catch (EvaluationException e) { stack.Push(e.GetErrorEval()); dist = attrPtg.ChooseFuncOffset + 4; // +4 for tFuncFar(CHOOSE) } // Encoded dist for tAttrChoose includes size of jump table, but // countTokensToBeSkipped() does not (it counts whole tokens). dist -= nChoices * 2 + 2; // subtract jump table size i += CountTokensToBeSkipped(ptgs, i, dist); continue; } if (attrPtg.IsOptimizedIf) { ValueEval arg0 = stack.Pop(); bool evaluatedPredicate; try { evaluatedPredicate = If.EvaluateFirstArg(arg0, ec.RowIndex, ec.ColumnIndex); } catch (EvaluationException e) { stack.Push(e.GetErrorEval()); int dist = attrPtg.Data; i += CountTokensToBeSkipped(ptgs, i, dist); attrPtg = (AttrPtg)ptgs[i]; dist = attrPtg.Data + 1; i += CountTokensToBeSkipped(ptgs, i, dist); continue; } if (evaluatedPredicate) { // nothing to skip - true param folows } else { int dist = attrPtg.Data; i += CountTokensToBeSkipped(ptgs, i, dist); Ptg nextPtg = ptgs[i + 1]; if (ptgs[i] is AttrPtg && nextPtg is FuncVarPtg) { // this is an if statement without a false param (as opposed to MissingArgPtg as the false param) i++; stack.Push(BoolEval.FALSE); } } continue; } if (attrPtg.IsSkip) { int dist = attrPtg.Data + 1; i += CountTokensToBeSkipped(ptgs, i, dist); if (stack.Peek() == MissingArgEval.instance) { stack.Pop(); stack.Push(BlankEval.instance); } continue; } } if (ptg is ControlPtg) { // skip Parentheses, Attr, etc continue; } if (ptg is MemFuncPtg) { // can ignore, rest of Tokens for this expression are in OK RPN order continue; } if (ptg is MemErrPtg) { continue; } ValueEval opResult; if (ptg is OperationPtg) { OperationPtg optg = (OperationPtg)ptg; if (optg is UnionPtg) { continue; } int numops = optg.NumberOfOperands; ValueEval[] ops = new ValueEval[numops]; // storing the ops in reverse order since they are popping for (int j = numops - 1; j >= 0; j--) { ValueEval p = (ValueEval)stack.Pop(); ops[j] = p; } // logDebug("Invoke " + operation + " (nAgs=" + numops + ")"); opResult = OperationEvaluatorFactory.Evaluate(optg, ops, ec); } else { opResult = GetEvalForPtg(ptg, ec); } if (opResult == null) { throw new Exception("Evaluation result must not be null"); } // logDebug("push " + opResult); stack.Push(opResult); } ValueEval value = ((ValueEval)stack.Pop()); if (stack.Count != 0) { throw new InvalidOperationException("evaluation stack not empty"); } return DereferenceResult(value, ec.RowIndex, ec.ColumnIndex); } /** * Calculates the number of tokens that the evaluator should skip upon reaching a tAttrSkip. * * @return the number of tokens (starting from <c>startIndex+1</c>) that need to be skipped * to achieve the specified <c>distInBytes</c> skip distance. */ private static int CountTokensToBeSkipped(Ptg[] ptgs, int startIndex, int distInBytes) { int remBytes = distInBytes; int index = startIndex; while (remBytes != 0) { index++; remBytes -= ptgs[index].Size; if (remBytes < 0) { throw new Exception("Bad skip distance (wrong token size calculation)."); } if (index >= ptgs.Length) { throw new Exception("Skip distance too far (ran out of formula tokens)."); } } return index - startIndex; } /** * Dereferences a single value from any AreaEval or RefEval evaluation result. * If the supplied evaluationResult is just a plain value, it is returned as-is. * @return a <c>NumberEval</c>, <c>StringEval</c>, <c>BoolEval</c>, * <c>BlankEval</c> or <c>ErrorEval</c>. Never <c>null</c>. */ public static ValueEval DereferenceResult(ValueEval evaluationResult, int srcRowNum, int srcColNum) { ValueEval value; try { value = OperandResolver.GetSingleValue(evaluationResult, srcRowNum, srcColNum); } catch (EvaluationException e) { return e.GetErrorEval(); } if (value == BlankEval.instance) { // Note Excel behaviour here. A blank value is converted To zero. return NumberEval.ZERO; // Formulas _never_ evaluate To blank. If a formula appears To have evaluated To // blank, the actual value is empty string. This can be verified with ISBLANK(). } return value; } /** * returns an appropriate Eval impl instance for the Ptg. The Ptg must be * one of: Area3DPtg, AreaPtg, ReferencePtg, Ref3DPtg, IntPtg, NumberPtg, * StringPtg, BoolPtg <br/>special Note: OperationPtg subtypes cannot be * passed here! */ private ValueEval GetEvalForPtg(Ptg ptg, OperationEvaluationContext ec) { // consider converting all these (ptg is XxxPtg) expressions To (ptg.GetType() == XxxPtg.class) if (ptg is NamePtg) { // named ranges, macro functions NamePtg namePtg = (NamePtg)ptg; IEvaluationName nameRecord = _workbook.GetName(namePtg); if (nameRecord.IsFunctionName) { return new NameEval(nameRecord.NameText); } if (nameRecord.HasFormula) { return EvaluateNameFormula(nameRecord.NameDefinition, ec); } throw new Exception("Don't now how To evalate name '" + nameRecord.NameText + "'"); } if (ptg is NameXPtg) { return ec.GetNameXEval(((NameXPtg)ptg)); } if (ptg is IntPtg) { return new NumberEval(((IntPtg)ptg).Value); } if (ptg is NumberPtg) { return new NumberEval(((NumberPtg)ptg).Value); } if (ptg is StringPtg) { return new StringEval(((StringPtg)ptg).Value); } if (ptg is BoolPtg) { return BoolEval.ValueOf(((BoolPtg)ptg).Value); } if (ptg is ErrPtg) { return ErrorEval.ValueOf(((ErrPtg)ptg).ErrorCode); } if (ptg is MissingArgPtg) { return MissingArgEval.instance; } if (ptg is AreaErrPtg || ptg is RefErrorPtg || ptg is DeletedArea3DPtg || ptg is DeletedRef3DPtg) { return ErrorEval.REF_INVALID; } if (ptg is Ref3DPtg) { Ref3DPtg rptg = (Ref3DPtg)ptg; return ec.GetRef3DEval(rptg.Row, rptg.Column, rptg.ExternSheetIndex); } if (ptg is Area3DPtg) { Area3DPtg aptg = (Area3DPtg)ptg; return ec.GetArea3DEval(aptg.FirstRow, aptg.FirstColumn, aptg.LastRow, aptg.LastColumn, aptg.ExternSheetIndex); } if (ptg is RefPtg) { RefPtg rptg = (RefPtg)ptg; return ec.GetRefEval(rptg.Row, rptg.Column); } if (ptg is AreaPtg) { AreaPtg aptg = (AreaPtg)ptg; return ec.GetAreaEval(aptg.FirstRow, aptg.FirstColumn, aptg.LastRow, aptg.LastColumn); } if (ptg is UnknownPtg) { // POI uses UnknownPtg when the encoded Ptg array seems To be corrupted. // This seems To occur in very rare cases (e.g. unused name formulas in bug 44774, attachment 21790) // In any case, formulas are re-parsed before execution, so UnknownPtg should not Get here throw new RuntimeException("UnknownPtg not allowed"); } if (ptg is ExpPtg) { // ExpPtg is used for array formulas and shared formulas. // it is currently unsupported, and may not even get implemented here throw new RuntimeException("ExpPtg currently not supported"); } throw new RuntimeException("Unexpected ptg class (" + ptg.GetType().Name + ")"); } internal ValueEval EvaluateNameFormula(Ptg[] ptgs, OperationEvaluationContext ec) { if (ptgs.Length > 1) { throw new Exception("Complex name formulas not supported yet"); } return GetEvalForPtg(ptgs[0], ec); } /** * Used by the lazy ref evals whenever they need To Get the value of a contained cell. */ /* package */ public ValueEval EvaluateReference(IEvaluationSheet sheet, int sheetIndex, int rowIndex, int columnIndex, EvaluationTracker tracker) { IEvaluationCell cell = sheet.GetCell(rowIndex, columnIndex); return EvaluateAny(cell, sheetIndex, rowIndex, columnIndex, tracker); } public FreeRefFunction FindUserDefinedFunction(String functionName) { return _udfFinder.FindFunction(functionName); } } }
// 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.Diagnostics; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// Library of XPathNode helper routines. /// </summary> internal abstract class XPathNodeHelper { /// <summary> /// Return chain of namespace nodes. If specified node has no local namespaces, then 0 will be /// returned. Otherwise, the first node in the chain is guaranteed to be a local namespace (its /// parent is this node). Subsequent nodes may not have the same node as parent, so the caller will /// need to test the parent in order to terminate a search that processes only local namespaces. /// </summary> public static int GetLocalNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp) { if (pageElem[idxElem].HasNamespaceDecls) { // Only elements have namespace nodes Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element); return pageElem[idxElem].Document.LookupNamespaces(pageElem, idxElem, out pageNmsp); } pageNmsp = null; return 0; } /// <summary> /// Return chain of in-scope namespace nodes for nodes of type Element. Nodes in the chain might not /// have this element as their parent. Since the xmlns:xml namespace node is always in scope, this /// method will never return 0 if the specified node is an element. /// </summary> public static int GetInScopeNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp) { XPathDocument doc; // Only elements have namespace nodes if (pageElem[idxElem].NodeType == XPathNodeType.Element) { doc = pageElem[idxElem].Document; // Walk ancestors, looking for an ancestor that has at least one namespace declaration while (!pageElem[idxElem].HasNamespaceDecls) { idxElem = pageElem[idxElem].GetParent(out pageElem); if (idxElem == 0) { // There are no namespace nodes declared on ancestors, so return xmlns:xml node return doc.GetXmlNamespaceNode(out pageNmsp); } } // Return chain of in-scope namespace nodes return doc.LookupNamespaces(pageElem, idxElem, out pageNmsp); } pageNmsp = null; return 0; } /// <summary> /// Return the first attribute of the specified node. If no attribute exist, do not /// set pageNode or idxNode and return false. /// </summary> public static bool GetFirstAttribute(ref XPathNode[] pageNode, ref int idxNode) { Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (pageNode[idxNode].HasAttribute) { GetChild(ref pageNode, ref idxNode); Debug.Assert(pageNode[idxNode].NodeType == XPathNodeType.Attribute); return true; } return false; } /// <summary> /// Return the next attribute sibling of the specified node. If the node is not itself an /// attribute, or if there are no siblings, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetNextAttribute(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page; int idx; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); idx = pageNode[idxNode].GetSibling(out page); if (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute) { pageNode = page; idxNode = idx; return true; } return false; } /// <summary> /// Return the first content-typed child of the specified node. If the node has no children, or /// if the node is not content-typed, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (page[idx].HasContentChild) { GetChild(ref page, ref idx); // Skip past attribute children while (page[idx].NodeType == XPathNodeType.Attribute) { idx = page[idx].GetSibling(out page); Debug.Assert(idx != 0); } pageNode = page; idxNode = idx; return true; } return false; } /// <summary> /// Return the next content-typed sibling of the specified node. If the node has no siblings, or /// if the node is not content-typed, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (!page[idx].IsAttrNmsp) { idx = page[idx].GetSibling(out page); if (idx != 0) { pageNode = page; idxNode = idx; return true; } } return false; } /// <summary> /// Return the parent of the specified node. If the node has no parent, do not set pageNode /// or idxNode and return false. /// </summary> public static bool GetParent(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); idx = page[idx].GetParent(out page); if (idx != 0) { pageNode = page; idxNode = idx; return true; } return false; } /// <summary> /// Return a location integer that can be easily compared with other locations from the same document /// in order to determine the relative document order of two nodes. /// </summary> public static int GetLocation(XPathNode[] pageNode, int idxNode) { Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); Debug.Assert(idxNode <= UInt16.MaxValue); Debug.Assert(pageNode[0].PageInfo.PageNumber <= Int16.MaxValue); return (pageNode[0].PageInfo.PageNumber << 16) | idxNode; } /// <summary> /// Return the first element child of the specified node that has the specified name. If no such child exists, /// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect /// to this document's name table, but not the namespaceName. /// </summary> public static bool GetElementChild(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Only check children if at least one element child exists if (page[idx].HasElementChild) { GetChild(ref page, ref idx); Debug.Assert(idx != 0); // Find element with specified localName and namespaceName do { if (page[idx].ElementMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } idx = page[idx].GetSibling(out page); } while (idx != 0); } return false; } /// <summary> /// Return a following sibling element of the specified node that has the specified name. If no such /// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and /// return false. Assume that the localName has been atomized with respect to this document's name table, /// but not the namespaceName. /// </summary> public static bool GetElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Elements should not be returned as "siblings" of attributes (namespaces don't link to elements, so don't need to check them) if (page[idx].NodeType != XPathNodeType.Attribute) { while (true) { idx = page[idx].GetSibling(out page); if (idx == 0) break; if (page[idx].ElementMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } } } return false; } /// <summary> /// Return the first child of the specified node that has the specified type (must be a content type). If no such /// child exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ) { XPathNode[] page = pageNode; int idx = idxNode; int mask; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Only check children if at least one content-typed child exists if (page[idx].HasContentChild) { mask = XPathNavigatorEx.GetContentKindMask(typ); GetChild(ref page, ref idx); do { if (((1 << (int)page[idx].NodeType) & mask) != 0) { // Never return attributes, as Attribute is not a content type if (typ == XPathNodeType.Attribute) return false; pageNode = page; idxNode = idx; return true; } idx = page[idx].GetSibling(out page); } while (idx != 0); } return false; } /// <summary> /// Return a following sibling of the specified node that has the specified type. If no such /// sibling exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ) { XPathNode[] page = pageNode; int idx = idxNode; int mask = XPathNavigatorEx.GetContentKindMask(typ); Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (page[idx].NodeType != XPathNodeType.Attribute) { while (true) { idx = page[idx].GetSibling(out page); if (idx == 0) break; if (((1 << (int)page[idx].NodeType) & mask) != 0) { Debug.Assert(typ != XPathNodeType.Attribute && typ != XPathNodeType.Namespace); pageNode = page; idxNode = idx; return true; } } } return false; } /// <summary> /// Return the first preceding sibling of the specified node. If no such sibling exists, then do not set /// pageNode or idxNode and return false. /// </summary> public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] pageParent = pageNode, pagePrec, pageAnc; int idxParent = idxNode, idxPrec, idxAnc; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); Debug.Assert(pageNode[idxNode].NodeType != XPathNodeType.Attribute); // Since nodes are laid out in document order on pages, the algorithm is: // 1. Get parent of current node // 2. If no parent, then there is no previous sibling, so return false // 3. Get node that immediately precedes the current node in document order // 4. If preceding node is parent, then there is no previous sibling, so return false // 5. Walk ancestors of preceding node, until parent of current node is found idxParent = pageParent[idxParent].GetParent(out pageParent); if (idxParent != 0) { idxPrec = idxNode - 1; if (idxPrec == 0) { // Need to get previous page pagePrec = pageNode[0].PageInfo.PreviousPage; idxPrec = pagePrec.Length - 1; } else { // Previous node is on the same page pagePrec = pageNode; } // If parent node is previous node, then no previous sibling if (idxParent == idxPrec && pageParent == pagePrec) return false; // Find child of parent node by walking ancestor chain pageAnc = pagePrec; idxAnc = idxPrec; do { pagePrec = pageAnc; idxPrec = idxAnc; idxAnc = pageAnc[idxAnc].GetParent(out pageAnc); Debug.Assert(idxAnc != 0 && pageAnc != null); } while (idxAnc != idxParent || pageAnc != pageParent); // We found the previous sibling, but if it's an attribute node, then return false if (pagePrec[idxPrec].NodeType != XPathNodeType.Attribute) { pageNode = pagePrec; idxNode = idxPrec; return true; } } return false; } /// <summary> /// Return the attribute of the specified node that has the specified name. If no such attribute exists, /// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect /// to this document's name table, but not the namespaceName. /// </summary> public static bool GetAttribute(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Find attribute with specified localName and namespaceName if (page[idx].HasAttribute) { GetChild(ref page, ref idx); do { if (page[idx].NameMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } idx = page[idx].GetSibling(out page); } while (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute); } return false; } /// <summary> /// Get the next element node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// If no such element exists, then do not set pageCurrent or idxCurrent and return false. /// Assume that the localName has been atomized with respect to this document's name table, but not the namespaceName. /// </summary> public static bool GetElementFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, string localName, string namespaceName) { XPathNode[] page = pageCurrent; int idx = idxCurrent; Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)"); // If current node is an element having a matching name, if (page[idx].NodeType == XPathNodeType.Element && (object)page[idx].LocalName == (object)localName) { // Then follow similar element name pointers int idxPageEnd = 0; int idxPageCurrent; if (pageEnd != null) { idxPageEnd = pageEnd[0].PageInfo.PageNumber; idxPageCurrent = page[0].PageInfo.PageNumber; // If ending node is <= starting node in document order, then scan to end of document if (idxPageCurrent > idxPageEnd || (idxPageCurrent == idxPageEnd && idx >= idxEnd)) pageEnd = null; } while (true) { idx = page[idx].GetSimilarElement(out page); if (idx == 0) break; // Only scan to ending node if (pageEnd != null) { idxPageCurrent = page[0].PageInfo.PageNumber; if (idxPageCurrent > idxPageEnd) break; if (idxPageCurrent == idxPageEnd && idx >= idxEnd) break; } if ((object)page[idx].LocalName == (object)localName && page[idx].NamespaceUri == namespaceName) goto FoundNode; } return false; } // Since nodes are laid out in document order on pages, scan them sequentially // rather than following links. idx++; do { if ((object)page == (object)pageEnd && idx <= idxEnd) { // Only scan to termination point while (idx != idxEnd) { if (page[idx].ElementMatch(localName, namespaceName)) goto FoundNode; idx++; } break; } else { // Scan all nodes in the page while (idx < page[0].PageInfo.NodeCount) { if (page[idx].ElementMatch(localName, namespaceName)) goto FoundNode; idx++; } } page = page[0].PageInfo.NextPage; idx = 1; } while (page != null); return false; FoundNode: // Found match pageCurrent = page; idxCurrent = idx; return true; } /// <summary> /// Get the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType (but Attributes and Namespaces never match) /// If no such node exists, then do not set pageCurrent or idxCurrent and return false. /// </summary> public static bool GetContentFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, XPathNodeType typ) { XPathNode[] page = pageCurrent; int idx = idxCurrent; int mask = XPathNavigatorEx.GetContentKindMask(typ); Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)"); Debug.Assert(typ != XPathNodeType.Text, "Text should be handled by GetTextFollowing in order to take into account collapsed text."); Debug.Assert(page[idx].NodeType != XPathNodeType.Attribute, "Current node should never be an attribute or namespace--caller should handle this case."); // Since nodes are laid out in document order on pages, scan them sequentially // rather than following sibling/child/parent links. idx++; do { if ((object)page == (object)pageEnd && idx <= idxEnd) { // Only scan to termination point while (idx != idxEnd) { if (((1 << (int)page[idx].NodeType) & mask) != 0) goto FoundNode; idx++; } break; } else { // Scan all nodes in the page while (idx < page[0].PageInfo.NodeCount) { if (((1 << (int)page[idx].NodeType) & mask) != 0) goto FoundNode; idx++; } } page = page[0].PageInfo.NextPage; idx = 1; } while (page != null); return false; FoundNode: Debug.Assert(!page[idx].IsAttrNmsp, "GetContentFollowing should never return attributes or namespaces."); // Found match pageCurrent = page; idxCurrent = idx; return true; } /// <summary> /// Scan all nodes that follow the current node in document order, but precede the ending node in document order. /// Return two types of nodes with non-null text: /// 1. Element parents of collapsed text nodes (since it is the element parent that has the collapsed text) /// 2. Non-collapsed text nodes /// If no such node exists, then do not set pageCurrent or idxCurrent and return false. /// </summary> public static bool GetTextFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd) { XPathNode[] page = pageCurrent; int idx = idxCurrent; Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)"); Debug.Assert(!page[idx].IsAttrNmsp, "Current node should never be an attribute or namespace--caller should handle this case."); // Since nodes are laid out in document order on pages, scan them sequentially // rather than following sibling/child/parent links. idx++; do { if ((object)page == (object)pageEnd && idx <= idxEnd) { // Only scan to termination point while (idx != idxEnd) { if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText)) goto FoundNode; idx++; } break; } else { // Scan all nodes in the page while (idx < page[0].PageInfo.NodeCount) { if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText)) goto FoundNode; idx++; } } page = page[0].PageInfo.NextPage; idx = 1; } while (page != null); return false; FoundNode: // Found match pageCurrent = page; idxCurrent = idx; return true; } /// <summary> /// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order, /// but is not a descendant. If no such node exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetNonDescendant(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; // Get page, idx at which to end sequential scan of nodes do { // If the current node has a sibling, if (page[idx].HasSibling) { // Then that is the first non-descendant pageNode = page; idxNode = page[idx].GetSibling(out pageNode); return true; } // Otherwise, try finding a sibling at the parent level idx = page[idx].GetParent(out page); } while (idx != 0); return false; } /// <summary> /// Return the page and index of the first child (attribute or content) of the specified node. /// </summary> private static void GetChild(ref XPathNode[] pageNode, ref int idxNode) { Debug.Assert(pageNode[idxNode].HasAttribute || pageNode[idxNode].HasContentChild, "Caller must check HasAttribute/HasContentChild on parent before calling GetChild."); Debug.Assert(pageNode[idxNode].HasAttribute || !pageNode[idxNode].HasCollapsedText, "Text child is virtualized and therefore is not present in the physical node page."); if (++idxNode >= pageNode.Length) { // Child is first node on next page pageNode = pageNode[0].PageInfo.NextPage; idxNode = 1; } // Else child is next node on this page } } }
//----------------------------------------------------------------------- // <copyright file="ARCoreAndroidLifecycleManager.cs" company="Google"> // // Copyright 2018 Google 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using GoogleARCore; using UnityEngine; #if UNITY_IOS && !UNITY_EDITOR using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif internal class ARCoreAndroidLifecycleManager : ILifecycleManager { private static ARCoreAndroidLifecycleManager s_Instance = null; private IntPtr m_CachedSessionHandle = IntPtr.Zero; private IntPtr m_CachedFrameHandle = IntPtr.Zero; private Dictionary<IntPtr, NativeSession> m_NativeSessions = new Dictionary<IntPtr, NativeSession>(new IntPtrEqualityComparer()); private DeviceCameraDirection? m_CachedCameraDirection = null; private ARCoreSessionConfig m_CachedConfig = null; private ScreenOrientation? m_CachedScreenOrientation = null; private bool? m_DesiredSessionState = null; // Only care about disable to enable transition here (ignore enable to disable transition) // because it will triggier _OnBeforeResumeSession which links to a public API // RegisterChooseCameraConfigurationCallback. private bool m_HaveDisableToEnableTransition = false; private AndroidNativeHelper.AndroidSurfaceRotation m_CachedDisplayRotation = AndroidNativeHelper.AndroidSurfaceRotation.Rotation0; private List<IntPtr> m_TempCameraConfigHandles = new List<IntPtr>(); private List<CameraConfig> m_TempCameraConfigs = new List<CameraConfig>(); public event Action UpdateSessionFeatures; public event Action EarlyUpdate; public event Action<bool> OnSessionSetEnabled; public static ARCoreAndroidLifecycleManager Instance { get { if (s_Instance == null) { s_Instance = new ARCoreAndroidLifecycleManager(); s_Instance._Initialize(); ARPrestoCallbackManager.Instance.EarlyUpdate += s_Instance._OnEarlyUpdate; ARPrestoCallbackManager.Instance.BeforeResumeSession += s_Instance._OnBeforeResumeSession; ExperimentManager.Instance.Initialize(); } return s_Instance; } } public SessionStatus SessionStatus { get; private set; } public LostTrackingReason LostTrackingReason { get; private set; } public ARCoreSession SessionComponent { get; private set; } public NativeSession NativeSession { get { if (m_CachedSessionHandle == IntPtr.Zero) { return null; } return _GetNativeSession(m_CachedSessionHandle); } } public bool IsSessionChangedThisFrame { get; private set; } public Texture2D BackgroundTexture { get; private set; } public AsyncTask<ApkAvailabilityStatus> CheckApkAvailability() { return ARPrestoCallbackManager.Instance.CheckApkAvailability(); } public AsyncTask<ApkInstallationStatus> RequestApkInstallation(bool userRequested) { return ARPrestoCallbackManager.Instance.RequestApkInstallation(userRequested); } public void CreateSession(ARCoreSession sessionComponent) { sessionComponent.StartCoroutine(InstantPreviewManager.InitializeIfNeeded()); if (SessionComponent != null) { Debug.LogError("Multiple ARCore session components cannot exist in the scene. " + "Destroying the newest."); GameObject.Destroy(sessionComponent); return; } SessionComponent = sessionComponent; } public void EnableSession() { if (m_DesiredSessionState.HasValue && !m_DesiredSessionState.Value) { m_HaveDisableToEnableTransition = true; } m_DesiredSessionState = true; } public void DisableSession() { m_DesiredSessionState = false; } public void ResetSession() { _FireOnSessionSetEnabled(false); _Initialize(); ExternApi.ArPresto_reset(); } private void _OnBeforeResumeSession(IntPtr sessionHandle) { if (SessionComponent == null || sessionHandle == IntPtr.Zero || SessionComponent.GetChooseCameraConfigurationCallback() == null) { return; } NativeSession tempNativeSession = _GetNativeSession(sessionHandle); var listHandle = tempNativeSession.CameraConfigListApi.Create(); tempNativeSession.SessionApi.GetSupportedCameraConfigurations( listHandle, m_TempCameraConfigHandles, m_TempCameraConfigs, SessionComponent.DeviceCameraDirection); if (m_TempCameraConfigHandles.Count == 0) { Debug.LogWarning( "Unable to choose a custom camera configuration because none are available."); } else { var configIndex = SessionComponent.GetChooseCameraConfigurationCallback()(m_TempCameraConfigs); if (configIndex >= 0 && configIndex < m_TempCameraConfigHandles.Count) { var status = tempNativeSession.SessionApi.SetCameraConfig( m_TempCameraConfigHandles[configIndex]); if (status != ApiArStatus.Success) { Debug.LogErrorFormat( "Failed to set the ARCore camera configuration: {0}", status); } } for (int i = 0; i < m_TempCameraConfigHandles.Count; i++) { tempNativeSession.CameraConfigApi.Destroy(m_TempCameraConfigHandles[i]); } } // clean up tempNativeSession.CameraConfigListApi.Destroy(listHandle); m_TempCameraConfigHandles.Clear(); m_TempCameraConfigs.Clear(); } private void _OnEarlyUpdate() { // Update session activity before EarlyUpdate. if (m_HaveDisableToEnableTransition) { _SetSessionEnabled(false); _SetSessionEnabled(true); m_HaveDisableToEnableTransition = false; // Avoid firing session enable event twice. if (m_DesiredSessionState.HasValue && m_DesiredSessionState.Value) { m_DesiredSessionState = null; } } if (m_DesiredSessionState.HasValue) { _SetSessionEnabled(m_DesiredSessionState.Value); m_DesiredSessionState = null; } // Perform updates before calling ArPresto_update. if (SessionComponent != null) { IntPtr previousSession = IntPtr.Zero; ExternApi.ArPresto_getSession(ref previousSession); if (UpdateSessionFeatures != null) { UpdateSessionFeatures(); } _SetCameraDirection(SessionComponent.DeviceCameraDirection); IntPtr currentSession = IntPtr.Zero; ExternApi.ArPresto_getSession(ref currentSession); // Fire the session enabled event when the underlying session has been changed // due to session feature update(camera direction etc). if (previousSession != currentSession) { _FireOnSessionSetEnabled(false); _FireOnSessionSetEnabled(true); } _SetConfiguration(SessionComponent.SessionConfig); } _UpdateDisplayGeometry(); // Update ArPresto and potentially ArCore. ExternApi.ArPresto_update(); // Get state information from ARPresto. ApiPrestoStatus prestoStatus = ApiPrestoStatus.Uninitialized; ExternApi.ArPresto_getStatus(ref prestoStatus); SessionStatus = prestoStatus.ToSessionStatus(); LostTrackingReason = LostTrackingReason.None; if (NativeSession != null && SessionStatus == SessionStatus.LostTracking) { var cameraHandle = NativeSession.FrameApi.AcquireCamera(); LostTrackingReason = NativeSession.CameraApi.GetLostTrackingReason(cameraHandle); NativeSession.CameraApi.Release(cameraHandle); } // Get the current session from presto and note if it has changed. IntPtr sessionHandle = IntPtr.Zero; ExternApi.ArPresto_getSession(ref sessionHandle); IsSessionChangedThisFrame = m_CachedSessionHandle != sessionHandle; m_CachedSessionHandle = sessionHandle; ExternApi.ArPresto_getFrame(ref m_CachedFrameHandle); // Update the native session with the newest frame. if (NativeSession != null) { NativeSession.OnUpdate(m_CachedFrameHandle); } _UpdateTextureIfNeeded(); if (EarlyUpdate != null) { EarlyUpdate(); } } private void _Initialize() { if (m_NativeSessions != null) { foreach (var nativeSession in m_NativeSessions.Values) { nativeSession.MarkDestroyed(); } } m_NativeSessions = new Dictionary<IntPtr, NativeSession>(new IntPtrEqualityComparer()); m_CachedSessionHandle = IntPtr.Zero; m_CachedFrameHandle = IntPtr.Zero; m_CachedConfig = null; m_DesiredSessionState = null; m_HaveDisableToEnableTransition = false; BackgroundTexture = null; SessionComponent = null; IsSessionChangedThisFrame = true; SessionStatus = SessionStatus.None; LostTrackingReason = LostTrackingReason.None; } private void _UpdateTextureIfNeeded() { // If running in editor, updates background texture from Instant Preview only. Texture2D previewBackgroundTexture = BackgroundTexture; if (InstantPreviewManager.UpdateBackgroundTextureIfNeeded(ref previewBackgroundTexture)) { BackgroundTexture = previewBackgroundTexture; return; } IntPtr frameHandle = IntPtr.Zero; ExternApi.ArPresto_getFrame(ref frameHandle); int backgroundTextureId = ExternApi.ArCoreUnity_getBackgroundTextureId(); if (frameHandle == IntPtr.Zero) { // This prevents using a texture that has not been filled out by ARCore. return; } else if (backgroundTextureId == -1) { return; } else if (BackgroundTexture != null && BackgroundTexture.GetNativeTexturePtr().ToInt32() == backgroundTextureId) { return; } else if (BackgroundTexture == null) { // The Unity-cached size and format of the texture (0x0, ARGB) is not the // actual format of the texture. This is okay because the texture is not // accessed by pixels, it is accessed with UV coordinates. BackgroundTexture = Texture2D.CreateExternalTexture( 0, 0, TextureFormat.ARGB32, false, false, new IntPtr(backgroundTextureId)); return; } BackgroundTexture.UpdateExternalTexture(new IntPtr(backgroundTextureId)); } private void _SetSessionEnabled(bool sessionEnabled) { if (sessionEnabled && SessionComponent == null) { return; } _FireOnSessionSetEnabled(sessionEnabled); ExternApi.ArPresto_setEnabled(sessionEnabled); } private bool _SetCameraDirection(DeviceCameraDirection cameraDirection) { // The camera direction has not changed. if (m_CachedCameraDirection.HasValue && m_CachedCameraDirection.Value == cameraDirection) { return false; } if (InstantPreviewManager.IsProvidingPlatform && cameraDirection == DeviceCameraDirection.BackFacing) { return false; } else if (InstantPreviewManager.IsProvidingPlatform) { InstantPreviewManager.LogLimitedSupportMessage( "enable front-facing (selfie) camera"); m_CachedCameraDirection = DeviceCameraDirection.BackFacing; if (SessionComponent != null) { SessionComponent.DeviceCameraDirection = DeviceCameraDirection.BackFacing; } return false; } m_CachedCameraDirection = cameraDirection; var apiCameraDirection = cameraDirection == DeviceCameraDirection.BackFacing ? ApiPrestoDeviceCameraDirection.BackFacing : ApiPrestoDeviceCameraDirection.FrontFacing; ExternApi.ArPresto_setDeviceCameraDirection(apiCameraDirection); return true; } private void _SetConfiguration(ARCoreSessionConfig config) { // There is no configuration to set. if (config == null) { return; } // The configuration has not been updated. if (m_CachedConfig != null && config.Equals(m_CachedConfig) && (config.AugmentedImageDatabase == null || !config.AugmentedImageDatabase.m_IsDirty) && !ExperimentManager.Instance.IsConfigurationDirty) { return; } if (InstantPreviewManager.IsProvidingPlatform) { if (config.PlaneFindingMode == DetectedPlaneFindingMode.Disabled) { InstantPreviewManager.LogLimitedSupportMessage("disable 'Plane Finding'"); config.PlaneFindingMode = DetectedPlaneFindingMode.Horizontal; } if (!config.EnableLightEstimation) { InstantPreviewManager.LogLimitedSupportMessage("disable 'Light Estimation'"); config.EnableLightEstimation = true; } if (config.CameraFocusMode == CameraFocusMode.Auto) { InstantPreviewManager.LogLimitedSupportMessage("enable camera Auto Focus mode"); config.CameraFocusMode = CameraFocusMode.Fixed; } if (config.AugmentedImageDatabase != null) { InstantPreviewManager.LogLimitedSupportMessage("enable 'Augmented Images'"); config.AugmentedImageDatabase = null; } if (config.AugmentedFaceMode == AugmentedFaceMode.Mesh) { InstantPreviewManager.LogLimitedSupportMessage("enable 'Augmented Faces'"); config.AugmentedFaceMode = AugmentedFaceMode.Disabled; } } var prestoConfig = new ApiPrestoConfig(config); ExternApi.ArPresto_setConfiguration(ref prestoConfig); m_CachedConfig = ScriptableObject.CreateInstance<ARCoreSessionConfig>(); m_CachedConfig.CopyFrom(config); } private void _UpdateDisplayGeometry() { IntPtr sessionHandle = IntPtr.Zero; ExternApi.ArPresto_getSession(ref sessionHandle); if (sessionHandle == IntPtr.Zero) { return; } if (!m_CachedScreenOrientation.HasValue || Screen.orientation != m_CachedScreenOrientation) { m_CachedScreenOrientation = Screen.orientation; m_CachedDisplayRotation = AndroidNativeHelper.GetDisplayRotation(); } ExternApi.ArSession_setDisplayGeometry( sessionHandle, (int)m_CachedDisplayRotation, Screen.width, Screen.height); } private NativeSession _GetNativeSession(IntPtr sessionHandle) { NativeSession nativeSession; if (!m_NativeSessions.TryGetValue(sessionHandle, out nativeSession)) { nativeSession = new NativeSession(sessionHandle, m_CachedFrameHandle); m_NativeSessions.Add(sessionHandle, nativeSession); } return nativeSession; } private void _FireOnSessionSetEnabled(bool isEnabled) { if (OnSessionSetEnabled != null) { OnSessionSetEnabled(isEnabled); } } private struct ExternApi { #pragma warning disable 626 [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArSession_setDisplayGeometry( IntPtr sessionHandle, int rotation, int width, int height); [AndroidImport(ApiConstants.ARCoreShimApi)] public static extern int ArCoreUnity_getBackgroundTextureId(); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_getSession(ref IntPtr sessionHandle); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_setDeviceCameraDirection( ApiPrestoDeviceCameraDirection cameraDirection); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_setConfiguration(ref ApiPrestoConfig config); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_setEnabled(bool isEnabled); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_getFrame(ref IntPtr frameHandle); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_getStatus(ref ApiPrestoStatus prestoStatus); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_update(); [AndroidImport(ApiConstants.ARPrestoApi)] public static extern void ArPresto_reset(); #pragma warning restore 626 } } }
// class translated from Java // Credit goes to Charles Hayden http://www.chayden.net/eliza/Eliza.html namespace ElizaCore { /// <summary>Eliza string functions.</summary> /// <remarks>Eliza string functions.</remarks> public class EString { /// <summary>The digits.</summary> /// <remarks>The digits.</remarks> internal static readonly string num = "0123456789"; /// <summary>Look for a match between the string and the pattern.</summary> /// <remarks> /// Look for a match between the string and the pattern. /// Return count of maching characters before * or #. /// Return -1 if strings do not match. /// </remarks> public static int Amatch(string str, string pat) { int count = 0; int i = 0; // march through str int j = 0; // march through pat while (i < str.Length && j < pat.Length) { char p = pat[j]; // stop if pattern is * or # if (p == '*' || p == '#') { return count; } if (str[i] != p) { return -1; } // they are still equal i++; j++; count++; } return count; } /// <summary> /// Search in successive positions of the string, /// looking for a match to the pattern. /// </summary> /// <remarks> /// Search in successive positions of the string, /// looking for a match to the pattern. /// Return the string position in str of the match, /// or -1 for no match. /// </remarks> public static int FindPat(string str, string pat) { int count = 0; for (int i = 0; i < str.Length; i++) { if (Amatch(str.Substring( i), pat) >= 0) { return count; } count++; } return -1; } /// <summary>Look for a number in the string.</summary> /// <remarks> /// Look for a number in the string. /// Return the number of digits at the beginning. /// </remarks> public static int FindNum(string str) { int count = 0; for (int i = 0; i < str.Length; i++) { if (num.IndexOf(str[i]) == -1) { return count; } count++; } return count; } /// <summary> /// Match the string against a pattern and fills in /// matches array with the pieces that matched * and # /// </summary> internal static bool MatchA(string str, string pat, string[] matches) { int i = 0; // move through str int j = 0; // move through matches int pos = 0; // move through pat while (pos < pat.Length && j < matches.Length) { char p = pat[pos]; if (p == '*') { int n; if (pos + 1 == pat.Length) { // * is the last thing in pat // n is remaining string length n = str.Length - i; } else { // * is not last in pat // find using remaining pat n = FindPat(str.Substring( i), pat.Substring( pos + 1)); } if (n < 0) { return false; } matches[j++] = String.Sub(str, i, i + n); i += n; pos++; } else { if (p == '#') { int n = FindNum(str.Substring( i)); matches[j++] = String.Sub(str, i, i + n); i += n; pos++; } else { int n = Amatch(str.Substring( i), pat.Substring( pos)); if (n <= 0) { return false; } i += n; pos += n; } } } if (i >= str.Length && pos >= pat.Length) { return true; } return false; } internal static bool MatchB(string strIn, string patIn, string[] matches) { string str = strIn; string pat = patIn; int j = 0; // move through matches while (pat.Length > 0 && str.Length >= 0 && j < matches.Length) { char p = pat[0]; if (p == '*') { int n; if (pat.Length == 1) { // * is the last thing in pat // n is remaining string length n = str.Length; } else { // * is not last in pat // find using remaining pat n = FindPat(str, pat.Substring( 1)); } if (n < 0) { return false; } matches[j++] = String.Sub(str, 0, n); str = str.Substring( n); pat = pat.Substring( 1); } else { if (p == '#') { int n = FindNum(str); matches[j++] = String.Sub(str, 0, n); str = str.Substring( n); pat = pat.Substring( 1); } else { // } else if (p == ' ' && str.length() > 0 && str.charAt(0) != ' ') { // pat = pat.substring(1); int n = Amatch(str, pat); if (n <= 0) { return false; } str = str.Substring( n); pat = pat.Substring( n); } } } if (str.Length == 0 && pat.Length == 0) { return true; } return false; } public static bool Match(string str, string pat, string[] matches) { return MatchA(str, pat, matches); } public static string Translate(string str, string src, string dest) { if (src.Length != dest.Length) { } // impossible error for (int i = 0; i < src.Length; i++) { str = str.Replace(src[i], dest[i]); } return str; } /// <summary> /// Compresses its input by: /// dropping space before space, comma, and period; /// adding space before question, if char before is not a space; and /// copying all others /// </summary> public static string Compress(string s) { string dest = string.Empty; if (s.Length == 0) { return s; } char c = s[0]; for (int i = 1; i < s.Length; i++) { if (c == ' ' && ((s[i] == ' ') || (s[i] == ',') || (s[i] == '.'))) { } else { // nothing if (c != ' ' && s[i] == '?') { dest += c + " "; } else { dest += c; } } c = s[i]; } dest += c; return dest; } /// <summary>Trim off leading space</summary> public static string Trim(string s) { for (int i = 0; i < s.Length; i++) { if (s[i] != ' ') { return s.Substring( i); } } return string.Empty; } /// <summary>Pad by ensuring there are spaces before and after the sentence.</summary> /// <remarks>Pad by ensuring there are spaces before and after the sentence.</remarks> public static string Pad(string s) { if (s.Length == 0) { return " "; } char first = s[0]; char last = s[s.Length - 1]; if (first == ' ' && last == ' ') { return s; } if (first == ' ' && last != ' ') { return s + " "; } if (first != ' ' && last == ' ') { return " " + s; } if (first != ' ' && last != ' ') { return " " + s + " "; } // impossible return s; } /// <summary>Count number of occurrances of c in str</summary> public static int Count(string s, char c) { int count = 0; for (int i = 0; i < s.Length; i++) { if (s[i] == c) { count++; } } return count; } } }
#region CVS Log /* * Version: * $Id: FrameRegistry.cs,v 1.4 2004/11/16 07:08:14 cwoodbury Exp $ * * Revisions: * $Log: FrameRegistry.cs,v $ * Revision 1.4 2004/11/16 07:08:14 cwoodbury * Changed accessibility modifiers for some methods to internal or * protected internal where appropriate. * * Revision 1.3 2004/11/10 06:51:55 cwoodbury * Hid CVS log messages away in #region * * Revision 1.2 2004/11/10 04:44:16 cwoodbury * Updated documentation. * * Revision 1.1 2004/11/03 01:18:51 cwoodbury * Added to ID3Sharp * */ #endregion /* * Author(s): * Chris Woodbury * * Project Location: * http://id3sharp.sourceforge.net * * License: * Licensed under the Open Software License version 2.0 */ using System; using System.Collections.Generic; using ID3Sharp.Exceptions; using ID3Sharp.Models; namespace ID3Sharp.Frames { /// <summary> /// A registry of frame-type data. This class is also responsible for creating /// new ID3v2Frame objects. /// </summary> internal static class FrameRegistry { #region Private Fields /// <summary> /// A dictionary, itself containing dictionaries for each ID3v2 minor version; /// each of these dictionaries has FrameTypes as keys and frame-ID strings as values. /// </summary> private static Dictionary<ID3Versions,Dictionary<FrameType,string>> idRegistry; /// <summary> /// A dictionary, itself containing dictionaries for each ID3v2 minor version; /// each of these dictionaries has frame-ID strings as keys and FrameTypes as values. /// </summary> private static Dictionary<ID3Versions, Dictionary<string, FrameType>> typeRegistry; /// <summary> /// A dictionary with FrameTypes as keys and prototype ID3v2Frame objects as values. /// </summary> private static Dictionary<FrameType, ID3v2Frame> prototypeRegistry; #endregion /// <summary> /// A static constructor that initializes the FrameRegistry. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline" )] static FrameRegistry() { InitializeRegistry(); } #region Initialization Helpers /// <summary> /// Initializes the internal registries. /// </summary> private static void InitializeRegistry() { idRegistry = new Dictionary<ID3Versions, Dictionary<FrameType, string>>(); idRegistry.Add( ID3Versions.V2_2, new Dictionary<FrameType, string>() ); idRegistry.Add( ID3Versions.V2_3, new Dictionary<FrameType, string>() ); idRegistry.Add( ID3Versions.V2_4, new Dictionary<FrameType, string>() ); typeRegistry = new Dictionary<ID3Versions, Dictionary<string, FrameType>>(); typeRegistry.Add( ID3Versions.V2_2, new Dictionary<string, FrameType>() ); typeRegistry.Add( ID3Versions.V2_3, new Dictionary<string, FrameType>() ); typeRegistry.Add( ID3Versions.V2_4, new Dictionary<string, FrameType>() ); InitializeVersionIDRegistry( ID3Versions.V2_2 ); InitializeVersionIDRegistry( ID3Versions.V2_3 ); InitializeVersionIDRegistry( ID3Versions.V2_4 ); prototypeRegistry = new Dictionary<FrameType, ID3v2Frame>(); InitializePrototypeRegistry(); } /// <summary> /// Initializes version-specific registries. /// </summary> /// <param name="version">The version associated with the registry to initialize.</param> private static void InitializeVersionIDRegistry( ID3Versions version ) { Dictionary<FrameType, string> versionIDRegistry = idRegistry[ version ]; if ( version == ID3Versions.V2_3 || version == ID3Versions.V2_4 ) { #region FrameIDs shared between v2.3 and v2.4 versionIDRegistry.Add( FrameType.AudioEncryption, "AENC" ); versionIDRegistry.Add( FrameType.AttachedPicture, "APIC" ); versionIDRegistry.Add( FrameType.Comments, "COMM" ); versionIDRegistry.Add( FrameType.Commercial, "COMR" ); versionIDRegistry.Add( FrameType.EncryptionMethodRegistraion, "ENCR" ); versionIDRegistry.Add( FrameType.EventTimingCodes, "ETCO" ); versionIDRegistry.Add( FrameType.GeneralEncapsulatedObject, "GEOB" ); versionIDRegistry.Add( FrameType.GroupIdentificationRegistration, "GRID" ); versionIDRegistry.Add( FrameType.LinkedInformation, "LINK" ); versionIDRegistry.Add( FrameType.MusicCDIdentifier, "MCDI" ); versionIDRegistry.Add( FrameType.MpegLocationLookupTable, "MLLT" ); versionIDRegistry.Add( FrameType.Ownership, "OWNE" ); versionIDRegistry.Add( FrameType.PlayCounter, "PCNT" ); versionIDRegistry.Add( FrameType.Popularimeter, "POPM" ); versionIDRegistry.Add( FrameType.PositionSynchronization, "POSS" ); versionIDRegistry.Add( FrameType.Private, "PRIV" ); versionIDRegistry.Add( FrameType.RecommendedBufferSize, "RBUF" ); versionIDRegistry.Add( FrameType.Reverb, "RVRB" ); versionIDRegistry.Add( FrameType.SynchronizedLyrics, "SYLT" ); versionIDRegistry.Add( FrameType.SynchronizedTempoCodes, "SYTC" ); versionIDRegistry.Add( FrameType.AlbumTitle, "TALB" ); versionIDRegistry.Add( FrameType.BeatsPerMinute, "TBPM" ); versionIDRegistry.Add( FrameType.Composer, "TCOM" ); versionIDRegistry.Add( FrameType.ContentType, "TCON" ); versionIDRegistry.Add( FrameType.CopyrightMessage, "TCOP" ); versionIDRegistry.Add( FrameType.PlaylistDelay, "TDLY" ); versionIDRegistry.Add( FrameType.EncodedBy, "TENC" ); versionIDRegistry.Add( FrameType.Lyricist, "TEXT" ); versionIDRegistry.Add( FrameType.ContentGroupDescription, "TIT1" ); versionIDRegistry.Add( FrameType.Title, "TIT2" ); versionIDRegistry.Add( FrameType.Subtitle, "TIT3" ); versionIDRegistry.Add( FrameType.InitialKey, "TKEY" ); versionIDRegistry.Add( FrameType.FileType, "TFLT" ); versionIDRegistry.Add( FrameType.Language, "TLAN" ); versionIDRegistry.Add( FrameType.Length, "TLEN" ); versionIDRegistry.Add( FrameType.MediaType, "TMED" ); versionIDRegistry.Add( FrameType.OriginalAlbumTitle, "TOAL" ); versionIDRegistry.Add( FrameType.OriginalFilename, "TOFN" ); versionIDRegistry.Add( FrameType.OriginalLyricist, "TOLY" ); versionIDRegistry.Add( FrameType.OriginalArtist, "TOPE" ); versionIDRegistry.Add( FrameType.FileOwner, "TOWN" ); versionIDRegistry.Add( FrameType.LeadArtist, "TPE1" ); versionIDRegistry.Add( FrameType.Band, "TPE2" ); versionIDRegistry.Add( FrameType.Conductor, "TPE3" ); versionIDRegistry.Add( FrameType.ModifiedBy, "TPE4" ); versionIDRegistry.Add( FrameType.PartOfASet, "TPOS" ); versionIDRegistry.Add( FrameType.Publisher, "TPUB" ); versionIDRegistry.Add( FrameType.TrackNumber, "TRCK" ); versionIDRegistry.Add( FrameType.InternetRadioStationName, "TRSN" ); versionIDRegistry.Add( FrameType.InternetRadioStationOwner, "TRSO" ); versionIDRegistry.Add( FrameType.SoftwareHardwareAndSettingsUsedForEncoding, "TSSE" ); versionIDRegistry.Add( FrameType.InternationalStandardRecordingCode, "TSRC" ); versionIDRegistry.Add( FrameType.UserDefinedText, "TXXX" ); versionIDRegistry.Add( FrameType.UniqueFileIdentifier, "UFID" ); versionIDRegistry.Add( FrameType.TermsOfUse, "USER" ); versionIDRegistry.Add( FrameType.UnsynchronizedLyrics, "USLT" ); versionIDRegistry.Add( FrameType.CommercialInformation, "WCOM" ); versionIDRegistry.Add( FrameType.CopyrightLegalInformation, "WCOP" ); versionIDRegistry.Add( FrameType.OfficialAudioFileWebpage, "WOAF" ); versionIDRegistry.Add( FrameType.OfficialArtistWebpage, "WOAR" ); versionIDRegistry.Add( FrameType.OfficialAudioSourceWebpage, "WOAS" ); versionIDRegistry.Add( FrameType.OfficialInternetRadioStationHomepage, "WORS" ); versionIDRegistry.Add( FrameType.Payment, "WPAY" ); versionIDRegistry.Add( FrameType.PublishersOfficialWebpage, "WPUB" ); versionIDRegistry.Add( FrameType.UserDefinedUrlLink, "WXXX" ); #endregion if ( version == ID3Versions.V2_3 ) { #region v2.3 FrameIDs versionIDRegistry.Add( FrameType.Equalization, "EQUA" ); versionIDRegistry.Add( FrameType.InvolvedPeopleList, "IPLS" ); versionIDRegistry.Add( FrameType.RelativeVolumeAdjustment, "RVAD" ); versionIDRegistry.Add( FrameType.Date, "TDAT" ); versionIDRegistry.Add( FrameType.Time, "TIME" ); versionIDRegistry.Add( FrameType.OriginalReleaseYear, "TORY" ); versionIDRegistry.Add( FrameType.RecordingDates, "TRDA" ); versionIDRegistry.Add( FrameType.Size, "TSIZ" ); versionIDRegistry.Add( FrameType.Year, "TYER" ); #endregion } else if ( version == ID3Versions.V2_4 ) { #region v2.4 FrameIDs versionIDRegistry.Add( FrameType.AudioSeekPointIndex, "ASPI" ); versionIDRegistry.Add( FrameType.Equalization2, "EQU2" ); versionIDRegistry.Add( FrameType.RelativeVolumeAdjustment2, "RVA2" ); versionIDRegistry.Add( FrameType.Seek, "SEEK" ); versionIDRegistry.Add( FrameType.Signature, "SIGN" ); versionIDRegistry.Add( FrameType.EncodingTime, "TDEN" ); versionIDRegistry.Add( FrameType.OriginalReleaseTime, "TDOR" ); versionIDRegistry.Add( FrameType.RecordingTime, "TDRC" ); versionIDRegistry.Add( FrameType.ReleaseTime, "TDRL" ); versionIDRegistry.Add( FrameType.TaggingTime, "TDTG" ); versionIDRegistry.Add( FrameType.InvolvedPeopleList2, "TIPL" ); versionIDRegistry.Add( FrameType.MusicianCreditsList, "TMCL" ); versionIDRegistry.Add( FrameType.Mood, "TMOO" ); versionIDRegistry.Add( FrameType.ProducedNotice, "TPRO" ); versionIDRegistry.Add( FrameType.AlbumSortOrder, "TSOA" ); versionIDRegistry.Add( FrameType.PerformerSortOrder, "TSOP" ); versionIDRegistry.Add( FrameType.TitleSortOrder, "TSOT" ); versionIDRegistry.Add( FrameType.SetSubtitle, "TSST" ); #endregion } } if ( version == ID3Versions.V2_2 ) { #region v2.2 FrameIDs versionIDRegistry.Add( FrameType.RecommendedBufferSize, "BUF" ); versionIDRegistry.Add( FrameType.PlayCounter, "CNT" ); versionIDRegistry.Add( FrameType.Comments, "COM" ); versionIDRegistry.Add( FrameType.AudioEncryption, "CRA" ); versionIDRegistry.Add( FrameType.EncryptedMetaFrame, "CRM" ); versionIDRegistry.Add( FrameType.EventTimingCodes, "ETC" ); versionIDRegistry.Add( FrameType.Equalization, "EQU" ); versionIDRegistry.Add( FrameType.GeneralEncapsulatedObject, "GEO" ); versionIDRegistry.Add( FrameType.InvolvedPeopleList, "IPL" ); versionIDRegistry.Add( FrameType.LinkedInformation, "LNK" ); versionIDRegistry.Add( FrameType.MusicCDIdentifier, "MCI" ); versionIDRegistry.Add( FrameType.MpegLocationLookupTable, "MLL" ); versionIDRegistry.Add( FrameType.AttachedPicture, "PIC" ); versionIDRegistry.Add( FrameType.Popularimeter, "POP" ); versionIDRegistry.Add( FrameType.Reverb, "REV" ); versionIDRegistry.Add( FrameType.RelativeVolumeAdjustment, "RVA" ); versionIDRegistry.Add( FrameType.SynchronizedLyrics, "SLT" ); versionIDRegistry.Add( FrameType.SynchronizedTempoCodes, "STC" ); versionIDRegistry.Add( FrameType.AlbumTitle, "TAL" ); versionIDRegistry.Add( FrameType.BeatsPerMinute, "TBP" ); versionIDRegistry.Add( FrameType.Composer, "TCM" ); versionIDRegistry.Add( FrameType.ContentType, "TCO" ); versionIDRegistry.Add( FrameType.CopyrightMessage, "TCR" ); versionIDRegistry.Add( FrameType.Date, "TDA" ); versionIDRegistry.Add( FrameType.PlaylistDelay, "TDY" ); versionIDRegistry.Add( FrameType.EncodedBy, "TEN" ); versionIDRegistry.Add( FrameType.FileType, "TFT" ); versionIDRegistry.Add( FrameType.Time, "TIM" ); versionIDRegistry.Add( FrameType.InitialKey, "TKE" ); versionIDRegistry.Add( FrameType.Language, "TLA" ); versionIDRegistry.Add( FrameType.Length, "TLE" ); versionIDRegistry.Add( FrameType.MediaType, "TMT" ); versionIDRegistry.Add( FrameType.OriginalArtist, "TOA" ); versionIDRegistry.Add( FrameType.OriginalFilename, "TOF" ); versionIDRegistry.Add( FrameType.OriginalLyricist, "TOL" ); versionIDRegistry.Add( FrameType.OriginalReleaseYear, "TOR" ); versionIDRegistry.Add( FrameType.OriginalAlbumTitle, "TOT" ); versionIDRegistry.Add( FrameType.LeadArtist, "TP1" ); versionIDRegistry.Add( FrameType.Band, "TP2" ); versionIDRegistry.Add( FrameType.Conductor, "TP3" ); versionIDRegistry.Add( FrameType.ModifiedBy, "TP4" ); versionIDRegistry.Add( FrameType.PartOfASet, "TPA" ); versionIDRegistry.Add( FrameType.Publisher, "TPB" ); versionIDRegistry.Add( FrameType.InternationalStandardRecordingCode, "TRC" ); versionIDRegistry.Add( FrameType.RecordingDates, "TRD" ); versionIDRegistry.Add( FrameType.TrackNumber, "TRK" ); versionIDRegistry.Add( FrameType.Size, "TSI" ); versionIDRegistry.Add( FrameType.SoftwareHardwareAndSettingsUsedForEncoding, "TSS" ); versionIDRegistry.Add( FrameType.ContentGroupDescription, "TT1" ); versionIDRegistry.Add( FrameType.Title, "TT2" ); versionIDRegistry.Add( FrameType.Subtitle, "TT3" ); versionIDRegistry.Add( FrameType.Lyricist, "TXT" ); versionIDRegistry.Add( FrameType.UserDefinedText, "TXX" ); versionIDRegistry.Add( FrameType.Year, "TYE" ); versionIDRegistry.Add( FrameType.UniqueFileIdentifier, "UFI" ); versionIDRegistry.Add( FrameType.OfficialAudioFileWebpage, "WAF" ); versionIDRegistry.Add( FrameType.OfficialArtistWebpage, "WAR" ); versionIDRegistry.Add( FrameType.OfficialAudioSourceWebpage, "WAS" ); versionIDRegistry.Add( FrameType.CommercialInformation, "WCM" ); versionIDRegistry.Add( FrameType.CopyrightLegalInformation, "WCP" ); versionIDRegistry.Add( FrameType.PublishersOfficialWebpage, "WPB" ); versionIDRegistry.Add( FrameType.UserDefinedUrlLink, "WXX" ); #endregion } Dictionary<string, FrameType> versionTypeRegistry = typeRegistry[ version ]; foreach ( FrameType frameType in versionIDRegistry.Keys ) { versionTypeRegistry.Add( versionIDRegistry[ frameType ], frameType ); } } /// <summary> /// Initializes the prototype registry. /// </summary> private static void InitializePrototypeRegistry() { ID3v2Frame commPrototype = new COMMFrame(); ID3v2Frame geobPrototype = new GEOBFrame(); ID3v2Frame privPrototype = new PRIVFrame(); ID3v2Frame pcntPrototype = new PCNTFrame(); ID3v2Frame textPrototype = new TextInformationFrame(); ID3v2Frame tconPrototype = new TCONFrame(); ID3v2Frame trckPrototype = new TRCKFrame(); ID3v2Frame txxxPrototype = new TXXXFrame(); ID3v2Frame ufidPrototype = new UFIDFrame(); ID3v2Frame urlPrototype = new URLLinkFrame(); ID3v2Frame wxxxPrototype = new WXXXFrame(); ID3v2Frame unimplementedPrototype = new UnimplementedFrame(); prototypeRegistry.Add( FrameType.UniqueFileIdentifier, ufidPrototype ); prototypeRegistry.Add( FrameType.ContentGroupDescription, textPrototype ); prototypeRegistry.Add( FrameType.Title, textPrototype ); prototypeRegistry.Add( FrameType.Subtitle, textPrototype ); prototypeRegistry.Add( FrameType.AlbumTitle, textPrototype ); prototypeRegistry.Add( FrameType.OriginalAlbumTitle, textPrototype ); prototypeRegistry.Add( FrameType.TrackNumber, trckPrototype ); prototypeRegistry.Add( FrameType.PartOfASet, textPrototype ); prototypeRegistry.Add( FrameType.SetSubtitle, textPrototype ); prototypeRegistry.Add( FrameType.InternationalStandardRecordingCode, textPrototype ); prototypeRegistry.Add( FrameType.LeadArtist, textPrototype ); prototypeRegistry.Add( FrameType.Band, textPrototype ); prototypeRegistry.Add( FrameType.Conductor, textPrototype ); prototypeRegistry.Add( FrameType.ModifiedBy, textPrototype ); prototypeRegistry.Add( FrameType.OriginalArtist, textPrototype ); prototypeRegistry.Add( FrameType.Lyricist, textPrototype ); prototypeRegistry.Add( FrameType.OriginalLyricist, textPrototype ); prototypeRegistry.Add( FrameType.Composer, textPrototype ); prototypeRegistry.Add( FrameType.MusicianCreditsList, textPrototype ); prototypeRegistry.Add( FrameType.InvolvedPeopleList2, textPrototype ); prototypeRegistry.Add( FrameType.EncodedBy, textPrototype ); prototypeRegistry.Add( FrameType.BeatsPerMinute, textPrototype ); prototypeRegistry.Add( FrameType.Length, textPrototype ); prototypeRegistry.Add( FrameType.InitialKey, textPrototype ); prototypeRegistry.Add( FrameType.Language, textPrototype ); prototypeRegistry.Add( FrameType.ContentType, tconPrototype ); prototypeRegistry.Add( FrameType.FileType, textPrototype ); prototypeRegistry.Add( FrameType.MediaType, textPrototype ); prototypeRegistry.Add( FrameType.Mood, textPrototype ); prototypeRegistry.Add( FrameType.CopyrightMessage, textPrototype ); prototypeRegistry.Add( FrameType.ProducedNotice, textPrototype ); prototypeRegistry.Add( FrameType.Publisher, textPrototype ); prototypeRegistry.Add( FrameType.FileOwner, textPrototype ); prototypeRegistry.Add( FrameType.InternetRadioStationName, textPrototype ); prototypeRegistry.Add( FrameType.InternetRadioStationOwner, textPrototype ); prototypeRegistry.Add( FrameType.OriginalFilename, textPrototype ); prototypeRegistry.Add( FrameType.PlaylistDelay, textPrototype ); prototypeRegistry.Add( FrameType.EncodingTime, textPrototype ); prototypeRegistry.Add( FrameType.OriginalReleaseTime, textPrototype ); prototypeRegistry.Add( FrameType.RecordingTime, textPrototype ); prototypeRegistry.Add( FrameType.ReleaseTime, textPrototype ); prototypeRegistry.Add( FrameType.TaggingTime, textPrototype ); prototypeRegistry.Add( FrameType.SoftwareHardwareAndSettingsUsedForEncoding, textPrototype ); prototypeRegistry.Add( FrameType.AlbumSortOrder, textPrototype ); prototypeRegistry.Add( FrameType.PerformerSortOrder, textPrototype ); prototypeRegistry.Add( FrameType.TitleSortOrder, textPrototype ); prototypeRegistry.Add( FrameType.UserDefinedText, txxxPrototype ); prototypeRegistry.Add( FrameType.CommercialInformation, urlPrototype ); prototypeRegistry.Add( FrameType.CopyrightLegalInformation, urlPrototype ); prototypeRegistry.Add( FrameType.OfficialAudioFileWebpage, urlPrototype ); prototypeRegistry.Add( FrameType.OfficialArtistWebpage, urlPrototype ); prototypeRegistry.Add( FrameType.OfficialAudioSourceWebpage, urlPrototype ); prototypeRegistry.Add( FrameType.OfficialInternetRadioStationHomepage, urlPrototype ); prototypeRegistry.Add( FrameType.Payment, urlPrototype ); prototypeRegistry.Add( FrameType.PublishersOfficialWebpage, urlPrototype ); prototypeRegistry.Add( FrameType.UserDefinedUrlLink, wxxxPrototype ); prototypeRegistry.Add( FrameType.MusicCDIdentifier, unimplementedPrototype ); prototypeRegistry.Add( FrameType.EventTimingCodes, unimplementedPrototype ); prototypeRegistry.Add( FrameType.MpegLocationLookupTable, unimplementedPrototype ); prototypeRegistry.Add( FrameType.SynchronizedTempoCodes, unimplementedPrototype ); prototypeRegistry.Add( FrameType.UnsynchronizedLyrics, unimplementedPrototype ); prototypeRegistry.Add( FrameType.SynchronizedLyrics, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Comments, commPrototype ); prototypeRegistry.Add( FrameType.RelativeVolumeAdjustment2, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Equalization2, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Reverb, unimplementedPrototype ); prototypeRegistry.Add( FrameType.AttachedPicture, unimplementedPrototype ); prototypeRegistry.Add( FrameType.GeneralEncapsulatedObject, geobPrototype ); prototypeRegistry.Add( FrameType.PlayCounter, pcntPrototype ); prototypeRegistry.Add( FrameType.Popularimeter, unimplementedPrototype ); prototypeRegistry.Add( FrameType.RecommendedBufferSize, unimplementedPrototype ); prototypeRegistry.Add( FrameType.AudioEncryption, unimplementedPrototype ); prototypeRegistry.Add( FrameType.LinkedInformation, unimplementedPrototype ); prototypeRegistry.Add( FrameType.PositionSynchronization, unimplementedPrototype ); prototypeRegistry.Add( FrameType.TermsOfUse, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Ownership, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Commercial, unimplementedPrototype ); prototypeRegistry.Add( FrameType.EncryptionMethodRegistraion, unimplementedPrototype ); prototypeRegistry.Add( FrameType.GroupIdentificationRegistration, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Private, privPrototype ); prototypeRegistry.Add( FrameType.Signature, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Seek, unimplementedPrototype ); prototypeRegistry.Add( FrameType.AudioSeekPointIndex, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Equalization, unimplementedPrototype ); prototypeRegistry.Add( FrameType.InvolvedPeopleList, unimplementedPrototype ); prototypeRegistry.Add( FrameType.RelativeVolumeAdjustment, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Date, textPrototype ); prototypeRegistry.Add( FrameType.Time, textPrototype ); prototypeRegistry.Add( FrameType.OriginalReleaseYear, textPrototype ); prototypeRegistry.Add( FrameType.RecordingDates, textPrototype ); prototypeRegistry.Add( FrameType.Size, textPrototype ); prototypeRegistry.Add( FrameType.Year, textPrototype ); prototypeRegistry.Add( FrameType.EncryptedMetaFrame, unimplementedPrototype ); prototypeRegistry.Add( FrameType.Unknown, unimplementedPrototype ); } #endregion #region Registry Accessors /// <summary> /// Returns the frame ID for the given FrameType and version. /// </summary> /// <param name="frameType">The FrameType to look up.</param> /// <param name="version">The ID3v2 version to use.</param> /// <returns>The frame ID for the given FrameType and version.</returns> internal static string GetFrameId( FrameType frameType, ID3Versions version ) { if ( version != ID3Versions.V2_2 && version != ID3Versions.V2_3 && version != ID3Versions.V2_4 ) { throw new UnsupportedVersionException( "This method must be called " + "with a single, specific ID3v2 version" ); } string frameID = null; Dictionary<FrameType, string> versionRegistry = idRegistry[ version ]; if ( versionRegistry.ContainsKey( frameType ) ) { frameID = versionRegistry[ frameType ]; } return frameID; } /// <summary> /// Returns the FrameType for the given frame ID and version. /// </summary> /// <param name="frameID">The frame ID string to look up.</param> /// <param name="version">The ID3v2 version to use.</param> /// <returns>The frame ID for the given FrameType and version.</returns> internal static FrameType GetFrameType( string frameID, ID3Versions version ) { if ( version != ID3Versions.V2_2 && version != ID3Versions.V2_3 && version != ID3Versions.V2_4 ) { throw new UnsupportedVersionException( "This method must be called " + "with a single, specific ID3v2 version" ); } Dictionary<string, FrameType> versionRegistry = typeRegistry[ version ]; FrameType frameType; if ( versionRegistry.ContainsKey( frameID ) ) { frameType = versionRegistry[ frameID ]; } else { frameType = FrameType.Unknown; } return frameType; } /// <summary> /// Returns a new frame of the given type. /// </summary> /// <param name="frameType">The type of frame to return.</param> /// <returns>A new frame of the given type.</returns> internal static ID3v2Frame GetNewFrame( FrameType frameType ) { if ( !prototypeRegistry.ContainsKey( frameType ) ) { throw new FrameTypeNotRegisteredException( frameType ); } ID3v2Frame prototypeFrame = prototypeRegistry[ frameType ]; ID3v2Frame newFrame = prototypeFrame.Copy(); newFrame.Type = frameType; return newFrame; } #endregion } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using FluentAssertions; using IdentityModel; using IdentityModel.Client; using IdentityServer.IntegrationTests.Clients.Setup; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; namespace IdentityServer.IntegrationTests.Clients { public class ResourceOwnerClient { private const string TokenEndpoint = "https://server/connect/token"; private readonly HttpClient _client; public ResourceOwnerClient() { var builder = new WebHostBuilder() .UseStartup<Startup>(); var server = new TestServer(builder); _client = server.CreateClient(); } [Fact] public async Task Valid_user_should_succeed_with_expected_response_payload() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "api1", UserName = "bob", Password = "bob" }); response.IsError.Should().Be(false); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().BeNull(); var payload = GetPayload(response); payload.Count().Should().Be(10); payload.Should().Contain("iss", "https://idsvr4"); payload.Should().Contain("client_id", "roclient"); payload.Should().Contain("sub", "88421113"); payload.Should().Contain("idp", "local"); payload["aud"].Should().Be("api"); var scopes = ((JArray)payload["scope"]).Select(x => x.ToString()); scopes.Count().Should().Be(1); scopes.Should().Contain("api1"); var amr = payload["amr"] as JArray; amr.Count().Should().Be(1); amr.First().ToString().Should().Be("pwd"); } [Fact] public async Task Request_with_no_explicit_scopes_should_return_allowed_scopes() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", UserName = "bob", Password = "bob" }); response.IsError.Should().Be(false); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); var payload = GetPayload(response); payload.Count().Should().Be(11); payload.Should().Contain("iss", "https://idsvr4"); payload.Should().Contain("client_id", "roclient"); payload.Should().Contain("sub", "88421113"); payload.Should().Contain("idp", "local"); payload["aud"].Should().Be("api"); var amr = payload["amr"] as JArray; amr.Count().Should().Be(1); amr.First().ToString().Should().Be("pwd"); var scopes = ((JArray)payload["scope"]).Select(x => x.ToString()); scopes.Count().Should().Be(8); // {[ "address", "api1", "api2", "api4.with.roles", "email", "offline_access", "openid", "role"]} scopes.Should().Contain("address"); scopes.Should().Contain("api1"); scopes.Should().Contain("api2"); scopes.Should().Contain("api4.with.roles"); scopes.Should().Contain("email"); scopes.Should().Contain("offline_access"); scopes.Should().Contain("openid"); scopes.Should().Contain("roles"); } [Fact] public async Task Request_containing_identity_scopes_should_return_expected_payload() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid email api1", UserName = "bob", Password = "bob" }); response.IsError.Should().Be(false); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().BeNull(); var payload = GetPayload(response); payload.Count().Should().Be(10); payload.Should().Contain("iss", "https://idsvr4"); payload.Should().Contain("client_id", "roclient"); payload.Should().Contain("sub", "88421113"); payload.Should().Contain("idp", "local"); payload["aud"].Should().Be("api"); var amr = payload["amr"] as JArray; amr.Count().Should().Be(1); amr.First().ToString().Should().Be("pwd"); var scopes = ((JArray)payload["scope"]).Select(x=>x.ToString()); scopes.Count().Should().Be(3); scopes.Should().Contain("api1"); scopes.Should().Contain("email"); scopes.Should().Contain("openid"); } [Fact] public async Task Request_for_refresh_token_should_return_expected_payload() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid email api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().Be(false); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNullOrWhiteSpace(); var payload = GetPayload(response); payload.Count().Should().Be(10); payload.Should().Contain("iss", "https://idsvr4"); payload.Should().Contain("client_id", "roclient"); payload.Should().Contain("sub", "88421113"); payload.Should().Contain("idp", "local"); payload["aud"].Should().Be("api"); var amr = payload["amr"] as JArray; amr.Count().Should().Be(1); amr.First().ToString().Should().Be("pwd"); var scopes = ((JArray)payload["scope"]).Select(x => x.ToString()); scopes.Count().Should().Be(4); scopes.Should().Contain("api1"); scopes.Should().Contain("email"); scopes.Should().Contain("offline_access"); scopes.Should().Contain("openid"); } [Fact] public async Task Unknown_user_should_fail() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "api1", UserName = "unknown", Password = "bob" }); response.IsError.Should().Be(true); response.ErrorType.Should().Be(ResponseErrorType.Protocol); response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); response.Error.Should().Be("invalid_grant"); } [Fact] public async Task User_with_empty_password_should_succeed() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "api1", UserName = "bob_no_password" }); response.IsError.Should().Be(false); } [Theory] [InlineData("invalid")] [InlineData("")] public async Task User_with_invalid_password_should_fail(string password) { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "api1", UserName = "bob", Password = password }); response.IsError.Should().Be(true); response.ErrorType.Should().Be(ResponseErrorType.Protocol); response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); response.Error.Should().Be("invalid_grant"); } private static Dictionary<string, object> GetPayload(IdentityModel.Client.TokenResponse response) { var token = response.AccessToken.Split('.').Skip(1).Take(1).First(); var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>( Encoding.UTF8.GetString(Base64Url.Decode(token))); return dictionary; } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data; namespace Glass.Mapper.Sc.Tests.DataMappers { [TestFixture] public class SitecoreFieldEnumMapperFixture : AbstractMapperFixture { #region Method - GetField [Test] public void GetField_FieldContainsValidEnum_ReturnsEnum() { //Assign string fieldValue = "Value1"; StubEnum expected = StubEnum.Value1; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsValidEnumInteger_ReturnsEnum() { //Assign string fieldValue = "2"; StubEnum expected = StubEnum.Value2; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsEmptyString_ReturnsDefaultEnum() { //Assign string fieldValue = string.Empty; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(StubEnum.Value1, result); } [Test] [ExpectedException(typeof (MapperException))] public void GetField_FieldContainsInvalidValidEnum_ThrowsException() { //Assign string fieldValue = "hello world"; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert } #endregion #region Method - SetField [Test] public void SetField_ObjectisValidEnum_SetsFieldValue() { //Assign string expected = "Value2"; StubEnum objectValue = StubEnum.Value2; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); item.Editing.BeginEdit(); //Act mapper.SetField(field, objectValue, config, null); //Assert Assert.AreEqual(expected, field.Value); } [Test] [ExpectedException(typeof (ArgumentException))] public void SetField_ObjectIsInt_ThrowsException() { //Assign string objectValue = "hello world"; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act mapper.SetField(field, objectValue, config, null); //Assert } #endregion #region Method - CanHandle [Test] public void CanHandle_PropertyIsEnum_ReturnsTrue() { //Assign var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_PropertyIsNotEnum_ReturnsTrue() { //Assign var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("PropertyNotEnum"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsFalse(result); } #endregion #region Stub public enum StubEnum { Value1 =1, Value2 = 2 } public class Stub { public StubEnum Property { get; set; } public string PropertyNotEnum { get; set; } } #endregion } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class Gallery : android.widget.AbsSpinner, android.view.GestureDetector.OnGestureListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Gallery(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class LayoutParams : android.view.ViewGroup.LayoutParams { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.Gallery.LayoutParams._m0.native == global::System.IntPtr.Zero) global::android.widget.Gallery.LayoutParams._m0 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.LayoutParams.staticClass, global::android.widget.Gallery.LayoutParams._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m1; public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.Gallery.LayoutParams._m1.native == global::System.IntPtr.Zero) global::android.widget.Gallery.LayoutParams._m1 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.LayoutParams.staticClass, "<init>", "(II)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.LayoutParams.staticClass, global::android.widget.Gallery.LayoutParams._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m2; public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.Gallery.LayoutParams._m2.native == global::System.IntPtr.Zero) global::android.widget.Gallery.LayoutParams._m2 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.LayoutParams.staticClass, global::android.widget.Gallery.LayoutParams._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static LayoutParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.Gallery.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/Gallery$LayoutParams")); } } private static global::MonoJavaBridge.MethodId _m0; public override bool onKeyDown(int arg0, android.view.KeyEvent arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z", ref global::android.widget.Gallery._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; public override bool onKeyUp(int arg0, android.view.KeyEvent arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z", ref global::android.widget.Gallery._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public override bool onTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.Gallery._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public override bool dispatchKeyEvent(android.view.KeyEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.widget.Gallery._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Gravity { set { setGravity(value); } } private static global::MonoJavaBridge.MethodId _m4; public virtual void setGravity(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "setGravity", "(I)V", ref global::android.widget.Gallery._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public override bool showContextMenu() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "showContextMenu", "()Z", ref global::android.widget.Gallery._m5); } private static global::MonoJavaBridge.MethodId _m6; protected override void onFocusChanged(bool arg0, int arg1, android.graphics.Rect arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "onFocusChanged", "(ZILandroid/graphics/Rect;)V", ref global::android.widget.Gallery._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m7; protected override void dispatchSetPressed(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "dispatchSetPressed", "(Z)V", ref global::android.widget.Gallery._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } protected new global::android.view.ContextMenu_ContextMenuInfo ContextMenuInfo { get { return getContextMenuInfo(); } } private static global::MonoJavaBridge.MethodId _m8; protected override global::android.view.ContextMenu_ContextMenuInfo getContextMenuInfo() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.ContextMenu_ContextMenuInfo>(this, global::android.widget.Gallery.staticClass, "getContextMenuInfo", "()Landroid/view/ContextMenu$ContextMenuInfo;", ref global::android.widget.Gallery._m8) as android.view.ContextMenu_ContextMenuInfo; } private static global::MonoJavaBridge.MethodId _m9; protected override int computeHorizontalScrollRange() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.Gallery.staticClass, "computeHorizontalScrollRange", "()I", ref global::android.widget.Gallery._m9); } private static global::MonoJavaBridge.MethodId _m10; protected override int computeHorizontalScrollOffset() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.Gallery.staticClass, "computeHorizontalScrollOffset", "()I", ref global::android.widget.Gallery._m10); } private static global::MonoJavaBridge.MethodId _m11; protected override int computeHorizontalScrollExtent() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.Gallery.staticClass, "computeHorizontalScrollExtent", "()I", ref global::android.widget.Gallery._m11); } private static global::MonoJavaBridge.MethodId _m12; protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "onLayout", "(ZIIII)V", ref global::android.widget.Gallery._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m13; public override void dispatchSetSelected(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "dispatchSetSelected", "(Z)V", ref global::android.widget.Gallery._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public override bool showContextMenuForChild(android.view.View arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "showContextMenuForChild", "(Landroid/view/View;)Z", ref global::android.widget.Gallery._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; protected override int getChildDrawingOrder(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.Gallery.staticClass, "getChildDrawingOrder", "(II)I", ref global::android.widget.Gallery._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m16; protected override bool getChildStaticTransformation(android.view.View arg0, android.view.animation.Transformation arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "getChildStaticTransformation", "(Landroid/view/View;Landroid/view/animation/Transformation;)Z", ref global::android.widget.Gallery._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z", ref global::android.widget.Gallery._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m18; public override global::android.view.ViewGroup.LayoutParams generateLayoutParams(android.util.AttributeSet arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.Gallery.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/view/ViewGroup$LayoutParams;", ref global::android.widget.Gallery._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.ViewGroup.LayoutParams; } private static global::MonoJavaBridge.MethodId _m19; protected override global::android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.Gallery.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/view/ViewGroup$LayoutParams;", ref global::android.widget.Gallery._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.ViewGroup.LayoutParams; } private static global::MonoJavaBridge.MethodId _m20; protected override global::android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.Gallery.staticClass, "generateDefaultLayoutParams", "()Landroid/view/ViewGroup$LayoutParams;", ref global::android.widget.Gallery._m20) as android.view.ViewGroup.LayoutParams; } private static global::MonoJavaBridge.MethodId _m21; public virtual void onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V", ref global::android.widget.Gallery._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public virtual bool onSingleTapUp(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.Gallery._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m23; public virtual bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z", ref global::android.widget.Gallery._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m24; public virtual bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z", ref global::android.widget.Gallery._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m25; public virtual void onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V", ref global::android.widget.Gallery._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; public virtual bool onDown(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.Gallery.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.Gallery._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool CallbackDuringFling { set { setCallbackDuringFling(value); } } private static global::MonoJavaBridge.MethodId _m27; public virtual void setCallbackDuringFling(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "setCallbackDuringFling", "(Z)V", ref global::android.widget.Gallery._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int AnimationDuration { set { setAnimationDuration(value); } } private static global::MonoJavaBridge.MethodId _m28; public virtual void setAnimationDuration(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "setAnimationDuration", "(I)V", ref global::android.widget.Gallery._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Spacing { set { setSpacing(value); } } private static global::MonoJavaBridge.MethodId _m29; public virtual void setSpacing(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "setSpacing", "(I)V", ref global::android.widget.Gallery._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new float UnselectedAlpha { set { setUnselectedAlpha(value); } } private static global::MonoJavaBridge.MethodId _m30; public virtual void setUnselectedAlpha(float arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.Gallery.staticClass, "setUnselectedAlpha", "(F)V", ref global::android.widget.Gallery._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public Gallery(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.Gallery._m31.native == global::System.IntPtr.Zero) global::android.widget.Gallery._m31 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.staticClass, global::android.widget.Gallery._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m32; public Gallery(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.Gallery._m32.native == global::System.IntPtr.Zero) global::android.widget.Gallery._m32 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "<init>", "(Landroid/content/Context;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.staticClass, global::android.widget.Gallery._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m33; public Gallery(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.Gallery._m33.native == global::System.IntPtr.Zero) global::android.widget.Gallery._m33 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.staticClass, global::android.widget.Gallery._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } static Gallery() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.Gallery.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/Gallery")); } } }
//----------------------------------------------------------------------- // <copyright file="ActorPublisherSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Akka.Actor; using Akka.Configuration; using Akka.Pattern; using Akka.Streams.Actors; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; using ActorPublisher = Akka.Streams.Actors.ActorPublisher; using Cancel = Akka.Streams.Actors.Cancel; namespace Akka.Streams.Tests.Actor { public class ActorPublisherSpec : AkkaSpec { private static readonly Config Config = ConfigurationFactory.ParseString(@" my-dispatcher1 { type = Dispatcher executor = ""fork-join-executor"" fork-join-executor { parallelism-min = 8 parallelism-max = 8 } mailbox-requirement = ""Akka.Dispatch.IUnboundedMessageQueueSemantics"" } my-dispatcher1 { type = Dispatcher executor = ""fork-join-executor"" fork-join-executor { parallelism-min = 8 parallelism-max = 8 } mailbox-requirement = ""Akka.Dispatch.IUnboundedMessageQueueSemantics"" }"); public ActorPublisherSpec(ITestOutputHelper output = null) : base( Config.WithFallback( ConfigurationFactory.FromResource<ScriptedTest>("Akka.Streams.TestKit.Tests.reference.conf")), output) { EventFilter.Exception<IllegalStateException>().Mute(); } [Fact] public void ActorPublisher_should_accumulate_demand() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var p = ActorPublisher.Create<string>(actorRef); var s = this.CreateSubscriberProbe<string>(); p.Subscribe(s); s.Request(2); probe.ExpectMsg<TotalDemand>().Elements.Should().Be(2); s.Request(3); probe.ExpectMsg<TotalDemand>().Elements.Should().Be(5); s.Cancel(); } [Fact] public void ActorPublisher_should_allow_onNext_up_to_requested_elements_but_not_more() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var p = ActorPublisher.Create<string>(actorRef); var s = this.CreateSubscriberProbe<string>(); p.Subscribe(s); s.Request(2); actorRef.Tell(new Produce("elem-1")); actorRef.Tell(new Produce("elem-2")); actorRef.Tell(new Produce("elem-3")); s.ExpectNext("elem-1"); s.ExpectNext("elem-2"); s.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); s.Cancel(); } [Fact] public void ActorPublisher_should_signal_error() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); actorRef.Tell(new Err("wrong")); s.ExpectSubscription(); s.ExpectError().Message.Should().Be("wrong"); } [Fact] public void ActorPublisher_should_not_terminate_after_signaling_onError() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscription(); probe.Watch(actorRef); actorRef.Tell(new Err("wrong")); s.ExpectError().Message.Should().Be("wrong"); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); } [Fact] public void ActorPublisher_should_terminate_after_signalling_OnErrorThenStop() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscription(); probe.Watch(actorRef); actorRef.Tell(new ErrThenStop("wrong")); s.ExpectError().Message.Should().Be("wrong"); probe.ExpectTerminated(actorRef, TimeSpan.FromSeconds(3)); } [Fact] public void ActorPublisher_should_signal_error_before_subscribe() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); actorRef.Tell(new Err("early err")); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscriptionAndError().Message.Should().Be("early err"); } [Fact] public void ActorPublisher_should_drop_onNext_elements_after_cancel() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var p = ActorPublisher.Create<string>(actorRef); var s = this.CreateSubscriberProbe<string>(); p.Subscribe(s); s.Request(2); actorRef.Tell(new Produce("elem-1")); s.Cancel(); actorRef.Tell(new Produce("elem-2")); s.ExpectNext("elem-1"); s.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); } [Fact] public void ActorPublisher_should_remember_requested_after_restart() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var p = ActorPublisher.Create<string>(actorRef); var s = this.CreateSubscriberProbe<string>(); p.Subscribe(s); s.Request(3); probe.ExpectMsg<TotalDemand>().Elements.Should().Be(3); actorRef.Tell(new Produce("elem-1")); actorRef.Tell(Boom.Instance); actorRef.Tell(new Produce("elem-2")); s.ExpectNext("elem-1"); s.ExpectNext("elem-2"); s.Request(5); probe.ExpectMsg<TotalDemand>().Elements.Should().Be(6); s.Cancel(); } [Fact] public void ActorPublisher_should_signal_onComplete() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.Request(3); actorRef.Tell(new Produce("elem-1")); actorRef.Tell(Complete.Instance); s.ExpectNext("elem-1"); s.ExpectComplete(); } [Fact] public void ActorPublisher_should_not_terminate_after_signalling_onComplete() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); var sub = s.ExpectSubscription(); sub.Request(3); probe.ExpectMsg<TotalDemand>().Elements.Should().Be(3); probe.Watch(actorRef); actorRef.Tell(new Produce("elem-1")); actorRef.Tell(Complete.Instance); s.ExpectNext("elem-1"); s.ExpectComplete(); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); } [Fact] public void ActorPublisher_should_terminate_after_signalling_onCompleteThenStop() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); var sub = s.ExpectSubscription(); sub.Request(3); probe.ExpectMsg<TotalDemand>().Elements.Should().Be(3); probe.Watch(actorRef); actorRef.Tell(new Produce("elem-1")); actorRef.Tell(CompleteThenStop.Instance); s.ExpectNext("elem-1"); s.ExpectComplete(); probe.ExpectTerminated(actorRef,TimeSpan.FromSeconds(3)); } [Fact] public void ActorPublisher_should_signal_immediate_onComplete() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); actorRef.Tell(Complete.Instance); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscriptionAndComplete(); } [Fact] public void ActorPublisher_should_only_allow_one_subscriber() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscription(); var s2 = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s2); s2.ExpectSubscriptionAndError() .Should() .BeOfType<IllegalStateException>() .Which.Message.Should() .Be($"ActorPublisher {ReactiveStreamsCompliance.SupportsOnlyASingleSubscriber}"); } [Fact] public void ActorPublisher_should_not_subscribe_the_same_subscriber_multiple_times() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscription(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectError().Message.Should().Be(ReactiveStreamsCompliance.CanNotSubscribeTheSameSubscriberMultipleTimes); } [Fact] public void ActorPublisher_should_signal_onComplete_when_actor_is_stopped() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisher.Props(probe.Ref)); var s = this.CreateManualSubscriberProbe<string>(); ActorPublisher.Create<string>(actorRef).Subscribe(s); s.ExpectSubscription(); actorRef.Tell(PoisonPill.Instance); s.ExpectComplete(); } [Fact] public void ActorPublisher_should_work_together_with_Flow_and_ActorSubscriber() { var materializer = Sys.Materializer(); this.AssertAllStagesStopped(() => { var probe = CreateTestProbe(); var source = Source.ActorPublisher<int>(Sender.Props); var sink = Sink.ActorSubscriber<string>(Receiver.Props(probe.Ref)); var t = source.Collect(n => { if (n%2 == 0) return "elem-" + n; return null; }).ToMaterialized(sink, Keep.Both).Run(materializer); var snd = t.Item1; var rcv = t.Item2; for (var i = 1; i <= 3; i++) snd.Tell(i); probe.ExpectMsg("elem-2"); for (var n = 4; n <= 500; n++) { if (n%19 == 0) Thread.Sleep(50); // simulate bursts snd.Tell(n); } for (var n = 4; n <= 500; n += 2) probe.ExpectMsg("elem-" + n); Watch(snd); rcv.Tell(PoisonPill.Instance); ExpectTerminated(snd); }, materializer); } [Fact] public void ActorPublisher_should_work_in_a_GraphDsl() { var materializer = Sys.Materializer(); var probe1 = CreateTestProbe(); var probe2 = CreateTestProbe(); var senderRef1 = ActorOf(Sender.Props); var source1 = Source.FromPublisher(ActorPublisher.Create<int>(senderRef1)) .MapMaterializedValue(_ => senderRef1); var sink1 = Sink.FromSubscriber(ActorSubscriber.Create<string>(ActorOf(Receiver.Props(probe1.Ref)))) .MapMaterializedValue(_ => probe1.Ref); var sink2 = Sink.ActorSubscriber<string>(Receiver.Props(probe2.Ref)) .MapMaterializedValue(_ => probe2.Ref); var senderRef2 = RunnableGraph.FromGraph(GraphDsl.Create( Source.ActorPublisher<int>(Sender.Props), (builder, source2) => { var merge = builder.Add(new Merge<int, int>(2)); var bcast = builder.Add(new Broadcast<string>(2)); builder.From(source1).To(merge.In(0)); builder.From(source2.Outlet).To(merge.In(1)); builder.From(merge.Out).Via(Flow.Create<int>().Select(i => i.ToString())).To(bcast.In); builder.From(bcast.Out(0)).Via(Flow.Create<string>().Select(s => s + "mark")).To(sink1); builder.From(bcast.Out(1)).To(sink2); return ClosedShape.Instance; })).Run(materializer); // the scala test is wrong const int noOfMessages = 10; for (var i = 0; i < noOfMessages; i++) { senderRef1.Tell(i); senderRef2.Tell(i+noOfMessages); } var probe1Messages = new List<string>(noOfMessages*2); var probe2Messages = new List<string>(noOfMessages*2); for (var i = 0; i < noOfMessages * 2; i++) { probe1Messages.Add(probe1.ExpectMsg<string>()); probe2Messages.Add(probe2.ExpectMsg<string>()); } probe1Messages.Should().BeEquivalentTo(Enumerable.Range(0, noOfMessages * 2).Select(i => i + "mark")); probe2Messages.Should().BeEquivalentTo(Enumerable.Range(0, noOfMessages * 2).Select(i => i.ToString())); } [Fact] public void ActorPublisher_should_be_able_to_define_a_subscription_timeout_after_which_it_should_shut_down() { var materializer = Sys.Materializer(); this.AssertAllStagesStopped(() => { var timeout = TimeSpan.FromMilliseconds(150); var a = ActorOf(TimeoutingPublisher.Props(TestActor, timeout)); var pub = ActorPublisher.Create<int>(a); // don't subscribe for `timeout` millis, so it will shut itself down ExpectMsg("timed-out"); // now subscribers will already be rejected, while the actor could perform some clean-up var sub = this.CreateManualSubscriberProbe<int>(); pub.Subscribe(sub); sub.ExpectSubscriptionAndError(); ExpectMsg("cleaned-up"); // termination is tiggered by user code Watch(a); ExpectTerminated(a); }, materializer); } [Fact] public void ActorPublisher_should_be_able_to_define_a_subscription_timeout_which_is_cancelled_by_the_first_incoming_Subscriber() { var timeout = TimeSpan.FromMilliseconds(500); var sub = this.CreateManualSubscriberProbe<int>(); var pub = ActorPublisher.Create<int>(ActorOf(TimeoutingPublisher.Props(TestActor, timeout))); // subscribe right away, should cancel subscription-timeout pub.Subscribe(sub); sub.ExpectSubscription(); ExpectNoMsg(TimeSpan.FromSeconds(1)); } [Fact] public void ActorPublisher_should_use_dispatcher_from_materializer_settings() { var materializer = ActorMaterializer.Create(Sys, Sys.Materializer().Settings.WithDispatcher("my-dispatcher1")); var s = this.CreateManualSubscriberProbe<string>(); var actorRef = Source.ActorPublisher<string>(TestPublisher.Props(TestActor, useTestDispatcher: false)) .To(Sink.FromSubscriber(s)) .Run(materializer); actorRef.Tell(ThreadName.Instance); ExpectMsg<string>().Should().Contain("my-dispatcher1"); } [Fact] public void ActorPublisher_should_use_dispatcher_from_operation_attributes() { var materializer = Sys.Materializer(); var s = this.CreateManualSubscriberProbe<string>(); var actorRef = Source.ActorPublisher<string>(TestPublisher.Props(TestActor, useTestDispatcher: false)) .WithAttributes(ActorAttributes.CreateDispatcher("my-dispatcher1")) .To(Sink.FromSubscriber(s)) .Run(materializer); actorRef.Tell(ThreadName.Instance); ExpectMsg<string>().Should().Contain("my-dispatcher1"); } [Fact] public void ActorPublisher_should_use_dispatcher_from_props() { var materializer = Sys.Materializer(); var s = this.CreateManualSubscriberProbe<string>(); var actorRef = Source.ActorPublisher<string>(TestPublisher.Props(TestActor, useTestDispatcher: false).WithDispatcher("my-dispatcher1")) .WithAttributes(ActorAttributes.CreateDispatcher("my-dispatcher2")) .To(Sink.FromSubscriber(s)) .Run(materializer); actorRef.Tell(ThreadName.Instance); ExpectMsg<string>().Should().Contain("my-dispatcher1"); } [Fact] public void ActorPublisher_should_handle_stash() { var probe = CreateTestProbe(); var actorRef = Sys.ActorOf(TestPublisherWithStash.Props(probe.Ref)); var p = new ActorPublisherImpl<string>(actorRef); var s = this.CreateSubscriberProbe<string>(); p.Subscribe(s); s.Request(2); s.Request(3); actorRef.Tell("unstash"); probe.ExpectMsg(new TotalDemand(5)); probe.ExpectMsg(new TotalDemand(5)); s.Request(4); probe.ExpectMsg(new TotalDemand(9)); s.Cancel(); } } internal class TestPublisher : Actors.ActorPublisher<string> { public static Props Props(IActorRef probe, bool useTestDispatcher = true) { var p = Akka.Actor.Props.Create(() => new TestPublisher(probe)); return useTestDispatcher ? p.WithDispatcher("akka.test.stream-dispatcher") : p; } private readonly IActorRef _probe; public TestPublisher(IActorRef probe) { _probe = probe; } protected override bool Receive(object message) { return message.Match() .With<Request>(request => _probe.Tell(new TotalDemand(TotalDemand))) .With<Produce>(produce => OnNext(produce.Elem)) .With<Err>(err => OnError(new Exception(err.Reason))) .With<ErrThenStop>(err => OnErrorThenStop(new Exception(err.Reason))) .With<Complete>(OnComplete) .With<CompleteThenStop>(OnCompleteThenStop) .With<Boom>(() => { throw new Exception("boom"); }) .With<ThreadName>(()=>_probe.Tell(Context.Props.Dispatcher /*Thread.CurrentThread.Name*/)) // TODO fix me when thread name is set by dispatcher .WasHandled; } } internal class TestPublisherWithStash : TestPublisher, IWithUnboundedStash { public TestPublisherWithStash(IActorRef probe) : base(probe) { } public new static Props Props(IActorRef probe, bool useTestDispatcher = true) { var p = Akka.Actor.Props.Create(() => new TestPublisherWithStash(probe)); return useTestDispatcher ? p.WithDispatcher("akka.test.stream-dispatcher") : p; } protected override bool Receive(object message) { if ("unstash".Equals(message)) { Stash.UnstashAll(); Context.Become(base.Receive); } else Stash.Stash(); return true; } public IStash Stash { get; set; } } internal class Sender : Actors.ActorPublisher<int> { public static Props Props { get; } = Props.Create<Sender>().WithDispatcher("akka.test.stream-dispatcher"); private IImmutableList<int> _buffer = ImmutableList<int>.Empty; protected override bool Receive(object message) { return message.Match() .With<int>(i => { if (_buffer.Count == 0 && TotalDemand > 0) OnNext(i); else { _buffer = _buffer.Add(i); DeliverBuffer(); } }) .With<Request>(DeliverBuffer) .With<Cancel>(() => Context.Stop(Self)) .WasHandled; } private void DeliverBuffer() { if (TotalDemand <= 0) return; if (TotalDemand <= int.MaxValue) { var use = _buffer.Take((int) TotalDemand).ToImmutableList(); _buffer = _buffer.Skip((int) TotalDemand).ToImmutableList(); use.ForEach(OnNext); } else { var use = _buffer.Take(int.MaxValue).ToImmutableList(); _buffer = _buffer.Skip(int.MaxValue).ToImmutableList(); use.ForEach(OnNext); DeliverBuffer(); } } } internal class TimeoutingPublisher : Actors.ActorPublisher<int> { public static Props Props(IActorRef probe, TimeSpan timeout) => Akka.Actor.Props.Create(() => new TimeoutingPublisher(probe, timeout)) .WithDispatcher("akka.test.stream-dispatcher"); private readonly IActorRef _probe; public TimeoutingPublisher(IActorRef probe, TimeSpan timeout) { _probe = probe; SubscriptionTimeout = timeout; } protected override bool Receive(object message) { return message.Match() .With<Request>(() => OnNext(1)) .With<SubscriptionTimeoutExceeded>(() => { _probe.Tell("timed-out"); Context.System.Scheduler.ScheduleTellOnce(SubscriptionTimeout, _probe, "cleaned-up", Self); Context.System.Scheduler.ScheduleTellOnce(SubscriptionTimeout, Self, PoisonPill.Instance, Nobody.Instance); }) .WasHandled; } } internal class Receiver : ActorSubscriber { public static Props Props(IActorRef probe) => Akka.Actor.Props.Create(() => new Receiver(probe)).WithDispatcher("akka.test.stream-dispatcher"); private readonly IActorRef _probe; public Receiver(IActorRef probe) { _probe = probe; } public override IRequestStrategy RequestStrategy { get; } = new WatermarkRequestStrategy(10); protected override bool Receive(object message) { return message.Match() .With<OnNext>(next => _probe.Tell(next.Element)) .WasHandled; } } internal class TotalDemand { public readonly long Elements; public TotalDemand(long elements) { Elements = elements; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((TotalDemand) obj); } protected bool Equals(TotalDemand other) => Elements == other.Elements; public override int GetHashCode() => Elements.GetHashCode(); } internal class Produce { public readonly string Elem; public Produce(string elem) { Elem = elem; } } internal class Err { public readonly string Reason; public Err(string reason) { Reason = reason; } } internal class ErrThenStop { public readonly string Reason; public ErrThenStop(string reason) { Reason = reason; } } internal class Boom { public static Boom Instance { get; } = new Boom(); private Boom() { } } internal class Complete { public static Complete Instance { get; } = new Complete(); private Complete() { } } internal class CompleteThenStop { public static CompleteThenStop Instance { get; } = new CompleteThenStop(); private CompleteThenStop() { } } internal class ThreadName { public static ThreadName Instance { get; } = new ThreadName(); private ThreadName() { } } }
// CodeContracts // // 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.Linq; using System.Text; using Microsoft.Cci; using Microsoft.Cci.Contracts; using System.IO; using System.Diagnostics.Contracts; using System.Xml; using Microsoft.Cci.ILToCodeModel; using System.Diagnostics; using Microsoft.Cci.MutableContracts; [assembly: ContractVerification(false)] namespace CCDoc { /// <summary> /// The main class of CCDoc containing the entry point into the program. /// </summary> [ContractVerification(true)] public static class CCDoc { /// <summary> /// The main entry point for the program. Real work is done in "RealMain". This just wraps RealMain in a try-catch-finally. /// </summary> public static int Main(string[] args) { int result = 0; var startTime = DateTime.Now; try { System.Diagnostics.Debug.Listeners.Clear(); // void debug boxes from popping up. result = RealMain(args); } catch (Exception e) { // swallow everything and just return an error code Console.WriteLine("CCDoc failed with uncaught exception: {0}", e.Message); Console.WriteLine("Stack trace: {0}", e.StackTrace); return 1; } finally { var delta = DateTime.Now - startTime; Console.WriteLine("elapsed time: {0}ms", delta.TotalMilliseconds); } return result; } /// <summary> /// The "real" main. This is where all the work in the program starts. /// </summary> ///<remarks> ///Due to technical reasons (see the remarks on "WriteContracts" and "GetContracts"), ///the contracts are gathered first then they are written out. This is instead of ///writting the contracts while they are being found. ///</remarks> ///<remarks> ///The contracts are gathered first then they are written out. We make one pass over the assembly ///to gather contracts, then one pass over the XML file to write out the contracts. This is instead ///of writing the contracts as they are being found, because all members in the assembly may not ///be represented in the XML file or may appear in a different order. ///</remarks> public static int RealMain(string[] args) { #region Parse options var options = new Options(); options.Parse(args); if (options.HelpRequested) { options.PrintOptions(""); return 1; } if (options.HasErrors) { options.PrintErrorsAndExit(Console.Out); return -1; } if (options.breakIntoDebugger) { System.Diagnostics.Debugger.Break(); } if (options.assembly == null && options.GeneralArguments.Count > 0) { options.assembly = options.GeneralArguments[0]; } #endregion try { TrySendLeaderBoardPing(options); #region Set up the DocTracker. (Used for debug output.) TextWriter writer = null; //A null writer is allowed. if (options.debug) { if (options.outFile != null) writer = new StreamWriter(options.outFile); else writer = Console.Out; } DocTracker docTracker = new DocTracker(writer); #endregion #region Collect and write contracts var contracts = GetContracts(options, docTracker); WriteContracts(contracts, options, docTracker); #endregion #region Write contract statistics docTracker.WriteContractsPerKind(MemberKind.Type); docTracker.WriteContractsPerKind(MemberKind.Property); docTracker.WriteContractsPerKind(MemberKind.Method); #endregion } catch { SendLeaderBoardFailure(); throw; } return 0; //success } private static void SendLeaderBoardFailure() { #if LeaderBoard var version = typeof(Options).Assembly.GetName().Version; LeaderBoard.LeaderBoardAPI.SendLeaderBoardFailure(LeaderBoard_CCDocId, version); #endif } const int LeaderBoard_CCDocId = 0x2; const int LeaderBoardFeatureMask_CCDoc = LeaderBoard_CCDocId << 12; private static void TrySendLeaderBoardPing(Options options) { #if LeaderBoard try { LeaderBoard.LeaderBoardAPI.SendLeaderBoardFeatureUse(LeaderBoardFeatureMask_CCDoc); } catch { } #endif } /// <summary> /// Write contracts from dictionary to XML file. /// </summary> static void WriteContracts(IDictionary<string, XContract[]> contracts, Options options, DocTracker docTracker) { Contract.Requires(options != null); Contract.Requires(docTracker != null); Contract.Requires(contracts != null); string xmlDocName = options.xmlFile; #region If an XML file isn't provided, create a new one. if (string.IsNullOrEmpty(xmlDocName) || !File.Exists(xmlDocName)) { docTracker.WriteLine("XML file not provided. Creating a new one."); #region Trim assembly name var trimmedAssemblyName = options.assembly; trimmedAssemblyName = Path.GetFileNameWithoutExtension(trimmedAssemblyName); #endregion if (string.IsNullOrEmpty(xmlDocName)) { xmlDocName = trimmedAssemblyName + ".xml"; } Contract.Assert(xmlDocName != null); #region Create new document XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, null)); var docNode = doc.AppendChild(doc.CreateElement("doc")); var assemblyNode = docNode.AppendChild(doc.CreateElement("assembly")); var nameNode = assemblyNode.AppendChild(doc.CreateElement("name")); nameNode.AppendChild(doc.CreateTextNode(trimmedAssemblyName)); docNode.AppendChild(doc.CreateElement("members")); #endregion doc.Save(xmlDocName); } #endregion #region Traverse the XML file and create a new XML file with contracts var xmlDocTempName = xmlDocName + ".temp"; // xmlDocName may have a path, so don't prepend! using (var reader = XmlReader.Create(xmlDocName)) { docTracker.WriteLine("Reading {0}...", xmlDocName); var settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineHandling = NewLineHandling.None; using (var writer = XmlWriter.Create(xmlDocTempName, settings)) { docTracker.WriteLine("Writing to {0} ...", xmlDocTempName); XmlTraverser xmlTraverser = new XmlTraverser(contracts, docTracker, options); xmlTraverser.Transform(reader, writer); writer.Flush(); } } #endregion #region Rename the output XML file if (String.IsNullOrEmpty(options.outputFile)) { File.Replace(xmlDocTempName, xmlDocName, xmlDocName + ".old"); } else { var outFile = options.outputFile; var ext = Path.GetExtension(outFile); if (ext != "xml") outFile = Path.ChangeExtension(outFile, ".xml"); if (File.Exists(outFile)) { File.Replace(xmlDocTempName, outFile, xmlDocName + ".old"); } else { File.Copy(xmlDocTempName, outFile); } } #endregion } /// <summary> /// Traverse the given assembly (located in options.Assembly) for contracts and return the contracts. /// </summary> /// <remarks> /// We use dictionary mapping special string ids that are unique to each member in an XML file to /// the contracts that that member has. /// </remarks> static IDictionary<string, XContract[]> GetContracts(Options options, DocTracker docTracker) { Contract.Requires(options != null); Contract.Requires(docTracker != null); Contract.Ensures(Contract.Result<IDictionary<string,XContract[]>>() != null); #region Establish host and load assembly Contract.Assume(options.resolvedPaths != null); var host = new CodeContractAwareHostEnvironment(options.libpaths); foreach (var p in options.resolvedPaths) { host.AddResolvedPath(p); } IModule module = host.LoadUnitFrom(options.assembly) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { Console.WriteLine("'{0}' is not a PE file containing a CLR module or assembly.", options.assembly); Environment.Exit(1); } #endregion #region Create the contracts dictionary Dictionary<string, XContract[]> contracts = new Dictionary<string, XContract[]>(StringComparer.Ordinal); //Use Ordinal compare for faster string comparison. #endregion #region Traverse module and extract contracts var contractsVisitor = new ContractVisitor(host, contracts, options, docTracker); var traverser = new ContractTraverser(host); traverser.PreorderVisitor = contractsVisitor; traverser.Traverse(module); #endregion return contracts; } } }
using System; using System.Collections; using System.IO; using System.Text; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Bcpg { /** * reader for Base64 armored objects - read the headers and then start returning * bytes when the data is reached. An IOException is thrown if the CRC check * fails. */ public class ArmoredInputStream : BaseInputStream { /* * set up the decoding table. */ private readonly static byte[] decodingTable; static ArmoredInputStream() { decodingTable = new byte[128]; for (int i = 'A'; i <= 'Z'; i++) { decodingTable[i] = (byte)(i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { decodingTable[i] = (byte)(i - 'a' + 26); } for (int i = '0'; i <= '9'; i++) { decodingTable[i] = (byte)(i - '0' + 52); } decodingTable['+'] = 62; decodingTable['/'] = 63; } /** * decode the base 64 encoded input data. * * @return the offset the data starts in out. */ private int Decode( int in0, int in1, int in2, int in3, int[] result) { if (in3 < 0) { throw new EndOfStreamException("unexpected end of file in armored stream."); } int b1, b2, b3, b4; if (in2 == '=') { b1 = decodingTable[in0] &0xff; b2 = decodingTable[in1] & 0xff; result[2] = ((b1 << 2) | (b2 >> 4)) & 0xff; return 2; } else if (in3 == '=') { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; result[1] = ((b1 << 2) | (b2 >> 4)) & 0xff; result[2] = ((b2 << 4) | (b3 >> 2)) & 0xff; return 1; } else { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; b4 = decodingTable[in3]; result[0] = ((b1 << 2) | (b2 >> 4)) & 0xff; result[1] = ((b2 << 4) | (b3 >> 2)) & 0xff; result[2] = ((b3 << 6) | b4) & 0xff; return 0; } } Stream input; bool start = true; int[] outBuf = new int[3]; int bufPtr = 3; Crc24 crc = new Crc24(); bool crcFound = false; bool hasHeaders = true; string header = null; bool newLineFound = false; bool clearText = false; bool restart = false; IList headerList= Platform.CreateArrayList(); int lastC = 0; bool isEndOfStream; /** * Create a stream for reading a PGP armoured message, parsing up to a header * and then reading the data that follows. * * @param input */ public ArmoredInputStream( Stream input) : this(input, true) { } /** * Create an armoured input stream which will assume the data starts * straight away, or parse for headers first depending on the value of * hasHeaders. * * @param input * @param hasHeaders true if headers are to be looked for, false otherwise. */ public ArmoredInputStream( Stream input, bool hasHeaders) { this.input = input; this.hasHeaders = hasHeaders; if (hasHeaders) { ParseHeaders(); } start = false; } private bool ParseHeaders() { header = null; int c; int last = 0; bool headerFound = false; headerList = Platform.CreateArrayList(); // // if restart we already have a header // if (restart) { headerFound = true; } else { while ((c = input.ReadByte()) >= 0) { if (c == '-' && (last == 0 || last == '\n' || last == '\r')) { headerFound = true; break; } last = c; } } if (headerFound) { StringBuilder Buffer = new StringBuilder("-"); bool eolReached = false; bool crLf = false; if (restart) // we've had to look ahead two '-' { Buffer.Append('-'); } while ((c = input.ReadByte()) >= 0) { if (last == '\r' && c == '\n') { crLf = true; } if (eolReached && (last != '\r' && c == '\n')) { break; } if (eolReached && c == '\r') { break; } if (c == '\r' || (last != '\r' && c == '\n')) { string line = Buffer.ToString(); if (line.Trim().Length < 1) break; headerList.Add(line); Buffer.Length = 0; } if (c != '\n' && c != '\r') { Buffer.Append((char)c); eolReached = false; } else { if (c == '\r' || (last != '\r' && c == '\n')) { eolReached = true; } } last = c; } if (crLf) { input.ReadByte(); // skip last \n } } if (headerList.Count > 0) { header = (string) headerList[0]; } clearText = "-----BEGIN PGP SIGNED MESSAGE-----".Equals(header); newLineFound = true; return headerFound; } /** * @return true if we are inside the clear text section of a PGP * signed message. */ public bool IsClearText() { return clearText; } /** * @return true if the stream is actually at end of file. */ public bool IsEndOfStream() { return isEndOfStream; } /** * Return the armor header line (if there is one) * @return the armor header line, null if none present. */ public string GetArmorHeaderLine() { return header; } /** * Return the armor headers (the lines after the armor header line), * @return an array of armor headers, null if there aren't any. */ public string[] GetArmorHeaders() { if (headerList.Count <= 1) { return null; } string[] hdrs = new string[headerList.Count - 1]; for (int i = 0; i != hdrs.Length; i++) { hdrs[i] = (string) headerList[i + 1]; } return hdrs; } private int ReadIgnoreSpace() { int c; do { c = input.ReadByte(); } while (c == ' ' || c == '\t'); return c; } private int ReadIgnoreWhitespace() { int c; do { c = input.ReadByte(); } while (c == ' ' || c == '\t' || c == '\r' || c == '\n'); return c; } private int ReadByteClearText() { int c = input.ReadByte(); if (c == '\r' || (c == '\n' && lastC != '\r')) { newLineFound = true; } else if (newLineFound && c == '-') { c = input.ReadByte(); if (c == '-') // a header, not dash escaped { clearText = false; start = true; restart = true; } else // a space - must be a dash escape { c = input.ReadByte(); } newLineFound = false; } else { if (c != '\n' && lastC != '\r') { newLineFound = false; } } lastC = c; if (c < 0) { isEndOfStream = true; } return c; } private int ReadClearText(byte[] buffer, int offset, int count) { int pos = offset; try { int end = offset + count; while (pos < end) { int c = ReadByteClearText(); if (c == -1) { break; } buffer[pos++] = (byte) c; } } catch (IOException ioe) { if (pos == offset) throw ioe; } return pos - offset; } private int DoReadByte() { if (bufPtr > 2 || crcFound) { int c = ReadIgnoreSpace(); if (c == '\n' || c == '\r') { c = ReadIgnoreWhitespace(); if (c == '=') // crc reached { bufPtr = Decode(ReadIgnoreSpace(), ReadIgnoreSpace(), ReadIgnoreSpace(), ReadIgnoreSpace(), outBuf); if (bufPtr != 0) { throw new IOException("no crc found in armored message."); } crcFound = true; int i = ((outBuf[0] & 0xff) << 16) | ((outBuf[1] & 0xff) << 8) | (outBuf[2] & 0xff); if (i != crc.Value) { throw new IOException("crc check failed in armored message."); } return ReadByte(); } if (c == '-') // end of record reached { while ((c = input.ReadByte()) >= 0) { if (c == '\n' || c == '\r') { break; } } if (!crcFound) { throw new IOException("crc check not found."); } crcFound = false; start = true; bufPtr = 3; if (c < 0) { isEndOfStream = true; } return -1; } } if (c < 0) { isEndOfStream = true; return -1; } bufPtr = Decode(c, ReadIgnoreSpace(), ReadIgnoreSpace(), ReadIgnoreSpace(), outBuf); } return outBuf[bufPtr++]; } public override int ReadByte() { if (start) { if (hasHeaders) { ParseHeaders(); } crc.Reset(); start = false; } if (clearText) { return ReadByteClearText(); } int c = DoReadByte(); crc.Update(c); return c; } public override int Read(byte[] buffer, int offset, int count) { if (start && count > 0) { if (hasHeaders) { ParseHeaders(); } start = false; } if (clearText) { return ReadClearText(buffer, offset, count); } int pos = offset; try { int end = offset + count; while (pos < end) { int c = DoReadByte(); crc.Update(c); if (c == -1) { break; } buffer[pos++] = (byte) c; } } catch (IOException ioe) { if (pos == offset) throw ioe; } return pos - offset; } public override void Close() { input.Close(); base.Close(); } } }
using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.Runtime.Serialization; using System.Windows.Forms; using WitsWay.TempTests.RemainProcessTest.PlanUI.Enums; namespace WitsWay.TempTests.RemainProcessTest.PlanUI.DrawObjects { /// <summary> /// Rectangle graphic object /// </summary> [Serializable] public class DrawRectangle : DrawObject { private Rectangle _rectangle; private const string EntryRectangle = "Rect"; protected Rectangle Rectangle { get { return _rectangle; } set { _rectangle = value; } } /// <summary> /// Clone this instance /// </summary> public override DrawObject Clone() { DrawRectangle drawRectangle = new DrawRectangle(); drawRectangle._rectangle = _rectangle; FillDrawObjectFields(drawRectangle); return drawRectangle; } public DrawRectangle() { SetRectangle(0, 0, 1, 1); } public DrawRectangle(int x, int y, int width, int height) { Center = new Point(x + (width / 2), y + (height / 2)); _rectangle.X = x; _rectangle.Y = y; _rectangle.Width = width; _rectangle.Height = height; TipText = String.Format("Rectangle Center @ {0}, {1}", Center.X, Center.Y); } public DrawRectangle(int x, int y, int width, int height, Color lineColor, Color fillColor) { Center = new Point(x + (width / 2), y + (height / 2)); _rectangle.X = x; _rectangle.Y = y; _rectangle.Width = width; _rectangle.Height = height; Color = lineColor; FillColor = fillColor; PenWidth = -1; TipText = String.Format("Rectangle Center @ {0}, {1}", Center.X, Center.Y); } public DrawRectangle(int x, int y, int width, int height, Color lineColor, Color fillColor, bool filled) { Center = new Point(x + (width / 2), y + (height / 2)); _rectangle.X = x; _rectangle.Y = y; _rectangle.Width = width; _rectangle.Height = height; Color = lineColor; FillColor = fillColor; Filled = filled; PenWidth = -1; TipText = String.Format("Rectangle Center @ {0}, {1}", Center.X, Center.Y); } public DrawRectangle(int x, int y, int width, int height, DrawingPens.PenType pType, Color fillColor, bool filled) { Center = new Point(x + (width / 2), y + (height / 2)); _rectangle.X = x; _rectangle.Y = y; _rectangle.Width = width; _rectangle.Height = height; DrawPen = DrawingPens.SetCurrentPen(pType); PenType = pType; FillColor = fillColor; Filled = filled; TipText = String.Format("Rectangle Center @ {0}, {1}", Center.X, Center.Y); } public DrawRectangle(int x, int y, int width, int height, Color lineColor, Color fillColor, bool filled, int lineWidth) { Center = new Point(x + (width / 2), y + (height / 2)); _rectangle.X = x; _rectangle.Y = y; _rectangle.Width = width; _rectangle.Height = height; Color = lineColor; FillColor = fillColor; Filled = filled; PenWidth = lineWidth; TipText = String.Format("Rectangle Center @ {0}, {1}", Center.X, Center.Y); } /// <summary> /// Draw rectangle /// </summary> /// <param name="g"></param> public override void Draw(Graphics g) { Pen pen; Brush b = FillBrushes.GetBrush(DrawUnitKind.UnitProcessing);// new SolidBrush(FillColor); if (DrawPen == null) pen = new Pen(Color, PenWidth); else pen = (Pen)DrawPen.Clone(); GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(GetNormalizedRectangle(Rectangle)); // Rotate the path about it's center if necessary if (Rotation != 0) { RectangleF pathBounds = gp.GetBounds(); Matrix m = new Matrix(); m.RotateAt(Rotation, new PointF(pathBounds.Left + (pathBounds.Width / 2), pathBounds.Top + (pathBounds.Height / 2)), MatrixOrder.Append); gp.Transform(m); } g.DrawPath(pen, gp); if (Filled) g.FillPath(b, gp); gp.Dispose(); pen.Dispose(); b.Dispose(); } protected void SetRectangle(int x, int y, int width, int height) { _rectangle.X = x; _rectangle.Y = y; _rectangle.Width = width; _rectangle.Height = height; } /// <summary> /// Get number of handles /// </summary> public override int HandleCount => 8; /// <summary> /// Get number of connection points /// </summary> public override int ConnectionCount => HandleCount; public override Point GetConnection(int connectionNumber) { return GetHandle(connectionNumber); } /// <summary> /// Get handle point by 1-based number /// </summary> /// <param name="handleNumber"></param> /// <returns></returns> public override Point GetHandle(int handleNumber) { int x, y, xCenter, yCenter; xCenter = _rectangle.X + _rectangle.Width / 2; yCenter = _rectangle.Y + _rectangle.Height / 2; x = _rectangle.X; y = _rectangle.Y; switch (handleNumber) { case 1: x = _rectangle.X; y = _rectangle.Y; break; case 2: x = xCenter; y = _rectangle.Y; break; case 3: x = _rectangle.Right; y = _rectangle.Y; break; case 4: x = _rectangle.Right; y = yCenter; break; case 5: x = _rectangle.Right; y = _rectangle.Bottom; break; case 6: x = xCenter; y = _rectangle.Bottom; break; case 7: x = _rectangle.X; y = _rectangle.Bottom; break; case 8: x = _rectangle.X; y = yCenter; break; } return new Point(x, y); } /// <summary> /// Hit test. /// Return value: -1 - no hit /// 0 - hit anywhere /// > 1 - handle number /// </summary> /// <param name="point"></param> /// <returns></returns> public override int HitTest(Point point) { if (Selected) { for (int i = 1; i <= HandleCount; i++) { if (GetHandleRectangle(i).Contains(point)) return i; } } if (PointInObject(point)) return 0; return -1; } protected override bool PointInObject(Point point) { return _rectangle.Contains(point); } /// <summary> /// Get cursor for the handle /// </summary> /// <param name="handleNumber"></param> /// <returns></returns> public override Cursor GetHandleCursor(int handleNumber) { switch (handleNumber) { case 1: return Cursors.SizeNWSE; case 2: return Cursors.SizeNS; case 3: return Cursors.SizeNESW; case 4: return Cursors.SizeWE; case 5: return Cursors.SizeNWSE; case 6: return Cursors.SizeNS; case 7: return Cursors.SizeNESW; case 8: return Cursors.SizeWE; default: return Cursors.Default; } } /// <summary> /// Move handle to new point (resizing) /// </summary> /// <param name="point"></param> /// <param name="handleNumber"></param> public override void MoveHandleTo(Point point, int handleNumber) { int left = Rectangle.Left; int top = Rectangle.Top; int right = Rectangle.Right; int bottom = Rectangle.Bottom; switch (handleNumber) { case 1: left = point.X; top = point.Y; break; case 2: top = point.Y; break; case 3: right = point.X; top = point.Y; break; case 4: right = point.X; break; case 5: right = point.X; bottom = point.Y; break; case 6: bottom = point.Y; break; case 7: left = point.X; bottom = point.Y; break; case 8: left = point.X; break; } Dirty = true; SetRectangle(left, top, right - left, bottom - top); } public override bool IntersectsWith(Rectangle rectangle) { return Rectangle.IntersectsWith(rectangle); } /// <summary> /// Move object /// </summary> /// <param name="deltaX"></param> /// <param name="deltaY"></param> public override void Move(int deltaX, int deltaY) { _rectangle.X += deltaX; _rectangle.Y += deltaY; Dirty = true; } public override void Dump() { base.Dump(); Trace.WriteLine("rectangle.X = " + _rectangle.X.ToString(CultureInfo.InvariantCulture)); Trace.WriteLine("rectangle.Y = " + _rectangle.Y.ToString(CultureInfo.InvariantCulture)); Trace.WriteLine("rectangle.Width = " + _rectangle.Width.ToString(CultureInfo.InvariantCulture)); Trace.WriteLine("rectangle.Height = " + _rectangle.Height.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Normalize rectangle /// </summary> public override void Normalize() { _rectangle = GetNormalizedRectangle(_rectangle); } /// <summary> /// Save objevt to serialization stream /// </summary> /// <param name="info">Contains all data being written to disk</param> /// <param name="orderNumber">Index of the Layer being saved</param> /// <param name="objectIndex">Index of the drawing object in the Layer</param> public override void SaveToStream(SerializationInfo info, int orderNumber, int objectIndex) { info.AddValue( String.Format(CultureInfo.InvariantCulture, "{0}{1}-{2}", EntryRectangle, orderNumber, objectIndex), _rectangle); base.SaveToStream(info, orderNumber, objectIndex); } /// <summary> /// LOad object from serialization stream /// </summary> /// <param name="info"></param> /// <param name="orderNumber"></param> /// <param name="objectIndex"></param> public override void LoadFromStream(SerializationInfo info, int orderNumber, int objectIndex) { _rectangle = (Rectangle)info.GetValue( String.Format(CultureInfo.InvariantCulture, "{0}{1}-{2}", EntryRectangle, orderNumber, objectIndex), typeof(Rectangle)); base.LoadFromStream(info, orderNumber, objectIndex); } #region Helper Functions public static Rectangle GetNormalizedRectangle(int x1, int y1, int x2, int y2) { if (x2 < x1) { int tmp = x2; x2 = x1; x1 = tmp; } if (y2 < y1) { int tmp = y2; y2 = y1; y1 = tmp; } return new Rectangle(x1, y1, x2 - x1, y2 - y1); } public static Rectangle GetNormalizedRectangle(Point p1, Point p2) { return GetNormalizedRectangle(p1.X, p1.Y, p2.X, p2.Y); } public static Rectangle GetNormalizedRectangle(Rectangle r) { return GetNormalizedRectangle(r.X, r.Y, r.X + r.Width, r.Y + r.Height); } #endregion Helper Functions } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 the OpenSimulator Project 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 DEVELOPERS ``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 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; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server { public delegate void OnIRCClientReadyDelegate(IRCClientView cv); public class IRCClientView : IClientAPI, IClientCore { public event OnIRCClientReadyDelegate OnIRCReady; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly TcpClient m_client; private readonly Scene m_scene; private UUID m_agentID = UUID.Random(); public ISceneAgent SceneAgent { get; set; } public int PingTimeMS { get { return 0; } } private string m_username; private string m_nick; private bool m_hasNick = false; private bool m_hasUser = false; private bool m_connected = true; public List<uint> SelectedObjects {get; private set;} public IRCClientView(TcpClient client, Scene scene) { m_client = client; m_scene = scene; WorkManager.StartThread(InternalLoop, "IRCClientView", ThreadPriority.Normal, false, true); } private void SendServerCommand(string command) { SendCommand(":opensimircd " + command); } private void SendCommand(string command) { m_log.Info("[IRCd] Sending >>> " + command); byte[] buf = Util.UTF8.GetBytes(command + "\r\n"); m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null); } private void SendComplete(IAsyncResult result) { m_log.Info("[IRCd] Send Complete."); } private string IrcRegionName { // I know &Channel is more technically correct, but people are used to seeing #Channel // Dont shoot me! get { return "#" + m_scene.RegionInfo.RegionName.Replace(" ", "-"); } } private void InternalLoop() { try { string strbuf = String.Empty; while (m_connected && m_client.Connected) { byte[] buf = new byte[8]; // RFC1459 defines max message size as 512. int count = m_client.GetStream().Read(buf, 0, buf.Length); string line = Util.UTF8.GetString(buf, 0, count); strbuf += line; string message = ExtractMessage(strbuf); if (message != null) { // Remove from buffer strbuf = strbuf.Remove(0, message.Length); m_log.Info("[IRCd] Recieving <<< " + message); message = message.Trim(); // Extract command sequence string command = ExtractCommand(message); ProcessInMessage(message, command); } else { //m_log.Info("[IRCd] Recieved data, but not enough to make a message. BufLen is " + strbuf.Length + // "[" + strbuf + "]"); if (strbuf.Length == 0) { m_connected = false; m_log.Info("[IRCd] Buffer zero, closing..."); if (OnDisconnectUser != null) OnDisconnectUser(); } } Thread.Sleep(0); Watchdog.UpdateThread(); } } catch (IOException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } catch (SocketException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } Watchdog.RemoveThread(); } private void ProcessInMessage(string message, string command) { m_log.Info("[IRCd] Processing [MSG:" + message + "] [COM:" + command + "]"); if (command != null) { switch (command) { case "ADMIN": case "AWAY": case "CONNECT": case "DIE": case "ERROR": case "INFO": case "INVITE": case "ISON": case "KICK": case "KILL": case "LINKS": case "LUSERS": case "OPER": case "PART": case "REHASH": case "SERVICE": case "SERVLIST": case "SERVER": case "SQUERY": case "SQUIT": case "STATS": case "SUMMON": case "TIME": case "TRACE": case "VERSION": case "WALLOPS": case "WHOIS": case "WHOWAS": SendServerCommand("421 " + command + " :Command unimplemented"); break; // Connection Commands case "PASS": break; // Ignore for now. I want to implement authentication later however. case "JOIN": IRC_SendReplyJoin(); break; case "MODE": IRC_SendReplyModeChannel(); break; case "USER": IRC_ProcessUser(message); IRC_Ready(); break; case "USERHOST": string[] userhostArgs = ExtractParameters(message); if (userhostArgs[0] == ":" + m_nick) { SendServerCommand("302 :" + m_nick + "=+" + m_nick + "@" + ((IPEndPoint) m_client.Client.RemoteEndPoint).Address); } break; case "NICK": IRC_ProcessNick(message); IRC_Ready(); break; case "TOPIC": IRC_SendReplyTopic(); break; case "USERS": IRC_SendReplyUsers(); break; case "LIST": break; // TODO case "MOTD": IRC_SendMOTD(); break; case "NOTICE": // TODO break; case "WHO": // TODO IRC_SendNamesReply(); IRC_SendWhoReply(); break; case "PING": IRC_ProcessPing(message); break; // Special case, ignore this completely. case "PONG": break; case "QUIT": if (OnDisconnectUser != null) OnDisconnectUser(); break; case "NAMES": IRC_SendNamesReply(); break; case "PRIVMSG": IRC_ProcessPrivmsg(message); break; default: SendServerCommand("421 " + command + " :Unknown command"); break; } } } private void IRC_Ready() { if (m_hasUser && m_hasNick) { SendServerCommand("001 " + m_nick + " :Welcome to OpenSimulator IRCd"); SendServerCommand("002 " + m_nick + " :Running OpenSimVersion"); SendServerCommand("003 " + m_nick + " :This server was created over 9000 years ago"); SendServerCommand("004 " + m_nick + " :opensimirc r1 aoOirw abeiIklmnoOpqrstv"); SendServerCommand("251 " + m_nick + " :There are 0 users and 0 services on 1 servers"); SendServerCommand("252 " + m_nick + " 0 :operators online"); SendServerCommand("253 " + m_nick + " 0 :unknown connections"); SendServerCommand("254 " + m_nick + " 1 :channels formed"); SendServerCommand("255 " + m_nick + " :I have 1 users, 0 services and 1 servers"); SendCommand(":" + m_nick + " MODE " + m_nick + " :+i"); SendCommand(":" + m_nick + " JOIN :" + IrcRegionName); // Rename to 'Real Name' SendCommand(":" + m_nick + " NICK :" + m_username.Replace(" ", "")); m_nick = m_username.Replace(" ", ""); IRC_SendReplyJoin(); IRC_SendChannelPrivmsg("System", "Welcome to OpenSimulator."); IRC_SendChannelPrivmsg("System", "You are in a maze of twisty little passages, all alike."); IRC_SendChannelPrivmsg("System", "It is pitch black. You are likely to be eaten by a grue."); if (OnIRCReady != null) OnIRCReady(this); } } private void IRC_SendReplyJoin() { IRC_SendReplyTopic(); IRC_SendNamesReply(); } private void IRC_SendReplyModeChannel() { SendServerCommand("324 " + m_nick + " " + IrcRegionName + " +n"); //SendCommand(":" + IrcRegionName + " MODE +n"); } private void IRC_ProcessUser(string message) { string[] userArgs = ExtractParameters(message); // TODO: unused: string username = userArgs[0]; // TODO: unused: string hostname = userArgs[1]; // TODO: unused: string servername = userArgs[2]; string realname = userArgs[3].Replace(":", ""); m_username = realname; m_hasUser = true; } private void IRC_ProcessNick(string message) { string[] nickArgs = ExtractParameters(message); string nickname = nickArgs[0].Replace(":",""); m_nick = nickname; m_hasNick = true; } private void IRC_ProcessPing(string message) { string[] pingArgs = ExtractParameters(message); string pingHost = pingArgs[0]; SendCommand("PONG " + pingHost); } private void IRC_ProcessPrivmsg(string message) { string[] privmsgArgs = ExtractParameters(message); if (privmsgArgs[0] == IrcRegionName) { if (OnChatFromClient != null) { OSChatMessage msg = new OSChatMessage(); msg.Sender = this; msg.Channel = 0; msg.From = this.Name; msg.Message = privmsgArgs[1].Replace(":", ""); msg.Position = Vector3.Zero; msg.Scene = m_scene; msg.SenderObject = null; msg.SenderUUID = this.AgentId; msg.Type = ChatTypeEnum.Say; OnChatFromClient(this, msg); } } else { // Handle as an IM, later. } } private void IRC_SendNamesReply() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { SendServerCommand("353 " + m_nick + " = " + IrcRegionName + " :" + user.Name.Replace(" ", "")); } SendServerCommand("366 " + IrcRegionName + " :End of /NAMES list"); } private void IRC_SendWhoReply() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { /*SendServerCommand(String.Format("352 {0} {1} {2} {3} {4} {5} :0 {6}", IrcRegionName, user.Name.Replace(" ", ""), "nohost.com", "opensimircd", user.Name.Replace(" ", ""), 'H', user.Name));*/ SendServerCommand("352 " + m_nick + " " + IrcRegionName + " n=" + user.Name.Replace(" ", "") + " fakehost.com " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); //SendServerCommand("352 " + IrcRegionName + " " + user.Name.Replace(" ", "") + " nohost.com irc.opensimulator " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); } SendServerCommand("315 " + m_nick + " " + IrcRegionName + " :End of /WHO list"); } private void IRC_SendMOTD() { SendServerCommand("375 :- OpenSimulator Message of the day -"); SendServerCommand("372 :- Hiya!"); SendServerCommand("376 :End of /MOTD command"); } private void IRC_SendReplyTopic() { SendServerCommand("332 " + IrcRegionName + " :OpenSimulator IRC Server"); } private void IRC_SendReplyUsers() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); SendServerCommand("392 :UserID Terminal Host"); if (users.Length == 0) { SendServerCommand("395 :Nobody logged in"); return; } foreach (EntityBase user in users) { char[] nom = new char[8]; char[] term = "terminal_".ToCharArray(); char[] host = "hostname".ToCharArray(); string userName = user.Name.Replace(" ",""); for (int i = 0; i < nom.Length; i++) { if (userName.Length < i) nom[i] = userName[i]; else nom[i] = ' '; } SendServerCommand("393 :" + nom + " " + term + " " + host + ""); } SendServerCommand("394 :End of users"); } private static string ExtractMessage(string buffer) { int pos = buffer.IndexOf("\r\n"); if (pos == -1) return null; string command = buffer.Substring(0, pos + 2); return command; } private static string ExtractCommand(string msg) { string[] msgs = msg.Split(' '); if (msgs.Length < 2) { m_log.Warn("[IRCd] Dropped msg: " + msg); return null; } if (msgs[0].StartsWith(":")) return msgs[1]; return msgs[0]; } private static string[] ExtractParameters(string msg) { string[] msgs = msg.Split(' '); List<string> parms = new List<string>(msgs.Length); bool foundCommand = false; string command = ExtractCommand(msg); for (int i=0;i<msgs.Length;i++) { if (msgs[i] == command) { foundCommand = true; continue; } if (foundCommand != true) continue; if (i != 0 && msgs[i].StartsWith(":")) { List<string> tmp = new List<string>(); for (int j=i;j<msgs.Length;j++) { tmp.Add(msgs[j]); } parms.Add(string.Join(" ", tmp.ToArray())); break; } parms.Add(msgs[i]); } return parms.ToArray(); } #region Implementation of IClientAPI public Vector3 StartPos { get { return new Vector3(m_scene.RegionInfo.RegionSizeX * 0.5f, m_scene.RegionInfo.RegionSizeY * 0.5f, 50f); } set { } } public bool TryGet<T>(out T iface) { iface = default(T); return false; } public T Get<T>() { return default(T); } public UUID AgentId { get { return m_agentID; } } public void Disconnect(string reason) { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue. (" + reason + ")"); m_connected = false; m_client.Close(); } public void Disconnect() { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue."); m_connected = false; m_client.Close(); SceneAgent = null; } public UUID SessionId { get { return m_agentID; } } public UUID SecureSessionId { get { return m_agentID; } } public UUID ActiveGroupId { get { return UUID.Zero; } set {} } public string ActiveGroupName { get { return "IRCd User"; } set {} } public ulong ActiveGroupPowers { get { return 0; } set {} } public Dictionary<UUID, ulong> GetGroupPowers() { return new Dictionary<UUID, ulong>(); } public void SetGroupPowers(Dictionary<UUID, ulong> powers) { } public ulong GetGroupPowers(UUID groupID) { return 0; } public bool IsGroupMember(UUID GroupID) { return false; } public string FirstName { get { string[] names = m_username.Split(' '); return names[0]; } } public string LastName { get { string[] names = m_username.Split(' '); if (names.Length > 1) return names[1]; return names[0]; } } public IScene Scene { get { return m_scene; } } public int NextAnimationSequenceNumber { get { return 0; } } public string Name { get { return m_username; } } public bool IsActive { get { return true; } set { if (!value) Disconnect("IsActive Disconnected?"); } } public bool IsLoggingOut { get { return false; } set { } } public bool SendLogoutPacketWhenClosing { set { } } public uint CircuitCode { get { return (uint)Util.RandomClass.Next(0,int.MaxValue); } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)m_client.Client.RemoteEndPoint; } } #pragma warning disable 67 public event GenericMessage OnGenericMessage; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event EstateChangeInfo OnEstateChangeInfo; public event EstateManageTelehub OnEstateManageTelehub; public event CachedTextureRequest OnCachedTextureRequest; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event ChangeAnim OnChangeAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event TeleportCancel OnTeleportCancel; public event DeRezObject OnDeRezObject; public event RezRestoreToWorld OnRezRestoreToWorld; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall1 OnRequestWearables; public event Action<IClientAPI, bool> OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; public event UpdateAgent OnAgentCameraUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event ObjectDeselect OnObjectDeselect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event ClientChangeObject onClientChangeObject; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event ObjectPermissions OnObjectPermissions; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event UUIDNameRequest OnNameFromUUIDRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event GrantUserFriendRights OnGrantUserRights; public event MoneyTransferRequest OnMoneyTransferRequest; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ParcelBuy OnParcelBuy; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event Action<Vector3, bool, bool> OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event MoveItemsAndLeaveCopy OnMoveItemsAndLeaveCopy; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedGodDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; public event FindAgentUpdate OnFindAgent; public event TrackAgentUpdate OnTrackAgent; public event NewUserReport OnUserReport; public event SaveStateHandler OnSaveState; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event ParcelBuyPass OnParcelBuyPass; public event ParcelGodMark OnParcelGodMark; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; public event ChangeInventoryItemFlags OnChangeInventoryItemFlags; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; public event GenericCall2 OnUpdateThrottles; #pragma warning restore 67 public int DebugPacketLevel { get; set; } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close() { Close(true, false); } public void Close(bool sendStop, bool force) { Disconnect(); } public void Kick(string message) { Disconnect(message); } public void Start() { m_scene.AddNewAgent(this, PresenceType.User); // Mimicking LLClientView which gets always set appearance from client. AvatarAppearance appearance; m_scene.GetAvatarAppearance(this, out appearance); OnSetAppearance(this, appearance.Texture, (byte[])appearance.VisualParams.Clone(),appearance.AvatarSize, new WearableCacheItem[0]); } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { m_log.Info("[IRCd ClientStack] Completing Handshake to Region"); if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(this, true); } } public void Stop() { Disconnect(); } public void SendWearables(AvatarWearable[] wearables, int serial) { } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List<CachedTextureResponseArg> cachedTextures) { } public void SendStartPingCheck(byte seq) { } public void SendKillObject(List<uint> localID) { } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public void SendChatMessage( string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, UUID ownerID, byte source, byte audible) { if (audible > 0 && message.Length > 0) IRC_SendChannelPrivmsg(fromName, message); } private void IRC_SendChannelPrivmsg(string fromName, string message) { SendCommand(":" + fromName.Replace(" ", "") + " PRIVMSG " + IrcRegionName + " :" + message); } public void SendInstantMessage(GridInstantMessage im) { // TODO } public void SendGenericMessage(string method, UUID invoice, List<string> message) { } public void SendGenericMessage(string method, UUID invoice, List<byte[]> message) { } public virtual bool CanSendLayerData() { return false; } public void SendLayerData(float[] map) { } public void SendLayerData(int px, int py, float[] map) { } public void SendWindData(int version, Vector2[] windSpeeds) { } public void SendCloudData(int version, float[] cloudCover) { } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } public AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { } public void SendTeleportFailed(string reason) { } public void SendTeleportStart(uint flags) { } public void SendTeleportProgress(uint flags, string message) { } public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item) { } public void SendPayPrice(UUID objectID, int[] payPrice) { } public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public void SendAvatarDataImmediate(ISceneEntity avatar) { } public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } public void ReprioritizeUpdates() { } public void FlushPrimUpdates() { } public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, UUID transactionID, uint callbackId) { } public void SendRemoveInventoryItem(UUID itemID) { } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public void SendBulkUpdateInventory(InventoryNodeBase node) { } public void SendXferPacket(ulong xferID, uint packet, byte[] data, bool isTaskInventory) { } public void SendAbortXferPacket(ulong xferID) { } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendNameReply(UUID profileId, string firstname, string lastname) { } public void SendAlertMessage(string message) { IRC_SendChannelPrivmsg("Alert",message); } public void SendAgentAlertMessage(string message, bool modal) { } public void SendAlertMessage(string message, string info) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { IRC_SendChannelPrivmsg(objectname,url); } public void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] membershipType, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<LandAccessEntry> accessList, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { // TODO } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { } public void SendObjectPropertiesReply(ISceneEntity entity) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendFindAgent(UUID HunterID, UUID PreyID, double GlobalX, double GlobalY) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public virtual void SetChildAgentThrottle(byte[] throttle,float factor) { } public void SetAgentThrottleSilent(int throttle, int setting) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } #pragma warning disable 0067 public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; #pragma warning restore 0067 public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message) { IRC_SendChannelPrivmsg(FromAvatarName, Message); } public void SendLogoutPacket() { Disconnect(); } public ClientInfo GetClientInfo() { return new ClientInfo(); } public void SetClientInfo(ClientInfo info) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return String.Empty; } public void Terminate() { Disconnect(); } public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties(UUID objectID) { } public void SendRegionHandle(UUID regoinID, ulong handle) { } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendEventInfoReply(EventData info) { } public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List<Vector3> SpawnPoint) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendAgentGroupDataUpdate(UUID avatarID, GroupMembershipData[] data) { } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { } public void SendAcceptCallingCard(UUID transactionID) { } public void SendDeclineCallingCard(UUID transactionID) { } public void SendTerminateFriend(UUID exFriendID) { } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void RefreshGroupMembership() { } public void UpdateGroupMembership(GroupMembershipData[] data) { } public void GroupMembershipRemove(UUID GroupID) { } public void GroupMembershipAddReplace(UUID GroupID,ulong GroupPowers) { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId) { } public void SendAgentTerseUpdate(ISceneEntity presence) { } public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } public void SendSelectedPartsProprieties(List<ISceneEntity> parts) { } public void SendPartPhysicsProprieties(ISceneEntity entity) { } public void SendPartFullUpdate(ISceneEntity ent, uint? parentID) { } public int GetAgentThrottleSilent(int throttle) { return 0; } } }
// 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.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal static class X500NameEncoder { private static readonly char[] s_quoteNeedingChars = { ',', '+', '=', '\"', '\n', // \r is NOT in this list, because it isn't in Windows. '<', '>', '#', ';', }; internal static string X500DistinguishedNameDecode( byte[] encodedName, bool printOid, X500DistinguishedNameFlags flags, bool addTrailingDelimieter=false) { bool reverse = (flags & X500DistinguishedNameFlags.Reversed) == X500DistinguishedNameFlags.Reversed; bool quoteIfNeeded = (flags & X500DistinguishedNameFlags.DoNotUseQuotes) != X500DistinguishedNameFlags.DoNotUseQuotes; string dnSeparator; if ((flags & X500DistinguishedNameFlags.UseSemicolons) == X500DistinguishedNameFlags.UseSemicolons) { dnSeparator = "; "; } else if ((flags & X500DistinguishedNameFlags.UseNewLines) == X500DistinguishedNameFlags.UseNewLines) { dnSeparator = Environment.NewLine; } else { // This is matching Windows (native) behavior, UseCommas does not need to be asserted, // it is just what happens if neither UseSemicolons nor UseNewLines is specified. dnSeparator = ", "; } using (SafeX509NameHandle x509Name = Interop.Crypto.DecodeX509Name(encodedName, encodedName.Length)) { if (x509Name.IsInvalid) { return ""; } // We need to allocate a StringBuilder to hold the data as we're building it, and there's the usual // arbitrary process of choosing a number that's "big enough" to minimize reallocations without wasting // too much space in the average case. // // So, let's look at an example of what our output might be. // // GitHub.com's SSL cert has a "pretty long" subject (partially due to the unknown OIDs): // businessCategory=Private Organization // 1.3.6.1.4.1.311.60.2.1.3=US // 1.3.6.1.4.1.311.60.2.1.2=Delaware // serialNumber=5157550 // street=548 4th Street // postalCode=94107 // C=US // ST=California // L=San Francisco // O=GitHub, Inc. // CN=github.com // // Which comes out to 228 characters using OpenSSL's default pretty-print // (openssl x509 -in github.cer -text -noout) // Throw in some "maybe-I-need-to-quote-this" quotes, and a couple of extra/extra-long O/OU values // and round that up to the next programmer number, and you get that 512 should avoid reallocations // in all but the most dire of cases. StringBuilder decodedName = new StringBuilder(512); int entryCount = Interop.Crypto.GetX509NameEntryCount(x509Name); bool printSpacing = false; for (int i = 0; i < entryCount; i++) { int loc = reverse ? entryCount - i - 1 : i; using (SafeSharedX509NameEntryHandle nameEntry = Interop.Crypto.GetX509NameEntry(x509Name, loc)) { Interop.Crypto.CheckValidOpenSslHandle(nameEntry); string thisOidValue; using (SafeSharedAsn1ObjectHandle oidHandle = Interop.Crypto.GetX509NameEntryOid(nameEntry)) { thisOidValue = Interop.Crypto.GetOidValue(oidHandle); } if (printSpacing) { decodedName.Append(dnSeparator); } else { printSpacing = true; } if (printOid) { AppendOid(decodedName, thisOidValue); } string rdnValue; using (SafeSharedAsn1StringHandle valueHandle = Interop.Crypto.GetX509NameEntryData(nameEntry)) { rdnValue = Interop.Crypto.Asn1StringToManagedString(valueHandle); } bool quote = quoteIfNeeded && NeedsQuoting(rdnValue); if (quote) { decodedName.Append('"'); // If the RDN itself had a quote within it, that quote needs to be escaped // with another quote. rdnValue = rdnValue.Replace("\"", "\"\""); } decodedName.Append(rdnValue); if (quote) { decodedName.Append('"'); } } } if (addTrailingDelimieter) { decodedName.Append(dnSeparator); } return decodedName.ToString(); } } private static bool NeedsQuoting(string rdnValue) { if (string.IsNullOrEmpty(rdnValue)) { return false; } if (IsQuotableWhitespace(rdnValue[0]) || IsQuotableWhitespace(rdnValue[rdnValue.Length - 1])) { return true; } int index = rdnValue.IndexOfAny(s_quoteNeedingChars); return index != -1; } private static bool IsQuotableWhitespace(char c) { // There's a whole lot of Unicode whitespace that isn't covered here; but this // matches what Windows deems quote-worthy. // // 0x20: Space // 0x09: Character Tabulation (tab) // 0x0A: Line Feed // 0x0B: Line Tabulation (vertical tab) // 0x0C: Form Feed // 0x0D: Carriage Return return (c == ' ' || (c >= 0x09 && c <= 0x0D)); } private static void AppendOid(StringBuilder decodedName, string oidValue) { Oid oid = new Oid(oidValue); if (StringComparer.Ordinal.Equals(oid.FriendlyName, oidValue) || string.IsNullOrEmpty(oid.FriendlyName)) { decodedName.Append("OID."); decodedName.Append(oid.Value); } else { decodedName.Append(oid.FriendlyName); } decodedName.Append('='); } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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.ComponentModel; using System.Globalization; using JetBrains.Annotations; using NLog.Internal; namespace NLog.Targets { /// <summary> /// Line ending mode. /// </summary> [TypeConverter(typeof(LineEndingModeConverter))] public sealed class LineEndingMode : IEquatable<LineEndingMode> { /// <summary> /// Insert platform-dependent end-of-line sequence after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode Default = new LineEndingMode("Default", EnvironmentHelper.NewLine); /// <summary> /// Insert CR LF sequence (ASCII 13, ASCII 10) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode CRLF = new LineEndingMode("CRLF", "\r\n"); /// <summary> /// Insert CR character (ASCII 13) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode CR = new LineEndingMode("CR", "\r"); /// <summary> /// Insert LF character (ASCII 10) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode LF = new LineEndingMode("LF", "\n"); /// <summary> /// Do not insert any line ending. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode None = new LineEndingMode("None", String.Empty); private readonly string _name; private readonly string _newLineCharacters; /// <summary> /// Gets the name of the LineEndingMode instance. /// </summary> public string Name { get { return this._name; } } /// <summary> /// Gets the new line characters (value) of the LineEndingMode instance. /// </summary> public string NewLineCharacters { get { return this._newLineCharacters; } } private LineEndingMode() { } /// <summary> /// Initializes a new instance of <see cref="LogLevel"/>. /// </summary> /// <param name="name">The mode name.</param> /// <param name="newLineCharacters">The new line characters to be used.</param> private LineEndingMode(string name, string newLineCharacters) { this._name = name; this._newLineCharacters = newLineCharacters; } /// <summary> /// Returns the <see cref="LineEndingMode"/> that corresponds to the supplied <paramref name="name"/>. /// </summary> /// <param name="name"> /// The textual representation of the line ending mode, such as CRLF, LF, Default etc. /// Name is not case sensitive. /// </param> /// <returns>The <see cref="LineEndingMode"/> value, that corresponds to the <paramref name="name"/>.</returns> /// <exception cref="ArgumentOutOfRangeException">There is no line ending mode with the specified name.</exception> public static LineEndingMode FromString([NotNull] string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Equals(CRLF.Name, StringComparison.OrdinalIgnoreCase)) return CRLF; if (name.Equals(LF.Name, StringComparison.OrdinalIgnoreCase)) return LF; if (name.Equals(CR.Name, StringComparison.OrdinalIgnoreCase)) return CR; if (name.Equals(Default.Name, StringComparison.OrdinalIgnoreCase)) return Default; if (name.Equals(None.Name, StringComparison.OrdinalIgnoreCase)) return None; #if !SILVERLIGHT throw new ArgumentOutOfRangeException("name", name, "LineEndingMode is out of range"); #else throw new ArgumentOutOfRangeException("name", "LineEndingMode is out of range"); #endif } /// <summary> /// Compares two <see cref="LineEndingMode"/> objects and returns a /// value indicating whether the first one is equal to the second one. /// </summary> /// <param name="mode1">The first level.</param> /// <param name="mode2">The second level.</param> /// <returns>The value of <c>mode1.NewLineCharacters == mode2.NewLineCharacters</c>.</returns> public static bool operator ==(LineEndingMode mode1, LineEndingMode mode2) { if (ReferenceEquals(mode1, null)) { return ReferenceEquals(mode2, null); } if (ReferenceEquals(mode2, null)) { return false; } return mode1.NewLineCharacters == mode2.NewLineCharacters; } /// <summary> /// Compares two <see cref="LineEndingMode"/> objects and returns a /// value indicating whether the first one is not equal to the second one. /// </summary> /// <param name="mode1">The first mode</param> /// <param name="mode2">The second mode</param> /// <returns>The value of <c>mode1.NewLineCharacters != mode2.NewLineCharacters</c>.</returns> public static bool operator !=(LineEndingMode mode1, LineEndingMode mode2) { if (ReferenceEquals(mode1, null)) { return !ReferenceEquals(mode2, null); } if (ReferenceEquals(mode2, null)) { return true; } return mode1.NewLineCharacters != mode2.NewLineCharacters; } /// <summary> /// Returns a string representation of the log level. /// </summary> /// <returns>Log level name.</returns> public override string ToString() { return this.Name; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms /// and data structures like a hash table. /// </returns> public override int GetHashCode() { return (_newLineCharacters != null ? _newLineCharacters.GetHashCode() : 0); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is /// equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with /// this instance.</param> /// <returns> /// Value of <c>true</c> if the specified <see cref="System.Object"/> /// is equal to this instance; otherwise, <c>false</c>. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is LineEndingMode && Equals((LineEndingMode) obj); } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(LineEndingMode other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(_newLineCharacters, other._newLineCharacters); } /// <summary> /// Provides a type converter to convert <see cref="LineEndingMode"/> objects to and from other representations. /// </summary> public class LineEndingModeConverter : TypeConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <returns> /// true if this converter can perform the conversion; otherwise, false. /// </returns> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param><param name="sourceType">A <see cref="T:System.Type"/> that represents the type you want to convert from. </param> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <returns> /// An <see cref="T:System.Object"/> that represents the converted value. /// </returns> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param><param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param><param name="value">The <see cref="T:System.Object"/> to convert. </param><exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var name = value as string; return name != null ? LineEndingMode.FromString(name) : base.ConvertFrom(context, culture, value); } } } }
#region Header /** * JsonWriter.cs * Stream-like facility to output JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static readonly NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private bool lower_case_properties; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } public bool LowerCaseProperties { get { return lower_case_properties; } set { lower_case_properties = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; lower_case_properties = false; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write (Environment.NewLine); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { switch (str[i]) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (str[i]); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) str[i] >= 32 && (int) str[i] <= 126) { writer.Write (str[i]); continue; } // Default, turn into a \uXXXX sequence IntToHex ((int) str[i], hex_seq); writer.Write ("\\u"); writer.Write (hex_seq); } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } // [XtraLife] Disable compiler warning... #pragma warning disable 3021 [CLSCompliant(false)] public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } #pragma warning restore 3021 public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); string propertyName = (property_name == null || !lower_case_properties) ? property_name : property_name.ToLowerInvariant(); PutString (propertyName); if (pretty_print) { if (propertyName.Length > context.Padding) context.Padding = propertyName.Length; for (int i = context.Padding - propertyName.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
/* * 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 IndexReader = Lucene.Net.Index.IndexReader; using ToStringUtils = Lucene.Net.Util.ToStringUtils; using Explanation = Lucene.Net.Search.Explanation; using Scorer = Lucene.Net.Search.Scorer; using Searcher = Lucene.Net.Search.Searcher; using Similarity = Lucene.Net.Search.Similarity; using Weight = Lucene.Net.Search.Weight; using NearSpansOrdered = Lucene.Net.Search.Spans.NearSpansOrdered; using NearSpansUnordered = Lucene.Net.Search.Spans.NearSpansUnordered; using SpanNearQuery = Lucene.Net.Search.Spans.SpanNearQuery; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using SpanScorer = Lucene.Net.Search.Spans.SpanScorer; using SpanWeight = Lucene.Net.Search.Spans.SpanWeight; namespace Lucene.Net.Search.Payloads { /// <summary> This class is very similar to /// <see cref="Lucene.Net.Search.Spans.SpanNearQuery" /> except that it factors /// in the value of the payloads located at each of the positions where the /// <see cref="Lucene.Net.Search.Spans.TermSpans" /> occurs. /// <p/> /// In order to take advantage of this, you must override /// <see cref="Lucene.Net.Search.Similarity.ScorePayload" /> /// which returns 1 by default. /// <p/> /// Payload scores are aggregated using a pluggable <see cref="PayloadFunction" />. /// /// </summary> /// <seealso cref="Lucene.Net.Search.Similarity.ScorePayload"> /// </seealso> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class PayloadNearQuery:SpanNearQuery, System.ICloneable { protected internal System.String fieldName; protected internal PayloadFunction function; public PayloadNearQuery(SpanQuery[] clauses, int slop, bool inOrder):this(clauses, slop, inOrder, new AveragePayloadFunction()) { } public PayloadNearQuery(SpanQuery[] clauses, int slop, bool inOrder, PayloadFunction function):base(clauses, slop, inOrder) { fieldName = clauses[0].Field; // all clauses must have same field this.function = function; } public override Weight CreateWeight(Searcher searcher) { return new PayloadNearSpanWeight(this, this, searcher); } public override System.Object Clone() { int sz = clauses.Count; SpanQuery[] newClauses = new SpanQuery[sz]; for (int i = 0; i < sz; i++) { newClauses[i] = clauses[i]; } PayloadNearQuery boostingNearQuery = new PayloadNearQuery(newClauses, internalSlop, inOrder); boostingNearQuery.Boost = Boost; return boostingNearQuery; } public override System.String ToString(System.String field) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); buffer.Append("payloadNear(["); var i = clauses.GetEnumerator(); while (i.MoveNext()) { SpanQuery clause = i.Current; buffer.Append(clause.ToString(field)); if (i.MoveNext()) { buffer.Append(", "); } } buffer.Append("], "); buffer.Append(internalSlop); buffer.Append(", "); buffer.Append(inOrder); buffer.Append(")"); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } // @Override public override int GetHashCode() { int prime = 31; int result = base.GetHashCode(); result = prime * result + ((fieldName == null)?0:fieldName.GetHashCode()); result = prime * result + ((function == null)?0:function.GetHashCode()); return result; } // @Override public override bool Equals(System.Object obj) { if (this == obj) return true; if (!base.Equals(obj)) return false; if (GetType() != obj.GetType()) return false; PayloadNearQuery other = (PayloadNearQuery) obj; if (fieldName == null) { if (other.fieldName != null) return false; } else if (!fieldName.Equals(other.fieldName)) return false; if (function == null) { if (other.function != null) return false; } else if (!function.Equals(other.function)) return false; return true; } //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class PayloadNearSpanWeight:SpanWeight { private void InitBlock(PayloadNearQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private PayloadNearQuery enclosingInstance; public PayloadNearQuery Enclosing_Instance { get { return enclosingInstance; } } public PayloadNearSpanWeight(PayloadNearQuery enclosingInstance, SpanQuery query, Searcher searcher):base(query, searcher) { InitBlock(enclosingInstance); } public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer) { return new PayloadNearSpanScorer(enclosingInstance, internalQuery.GetSpans(reader), this, similarity, reader.Norms(internalQuery.Field)); } } public class PayloadNearSpanScorer:SpanScorer { private void InitBlock(PayloadNearQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; similarity = Similarity; } private PayloadNearQuery enclosingInstance; public PayloadNearQuery Enclosing_Instance { get { return enclosingInstance; } } new internal Lucene.Net.Search.Spans.Spans spans; protected internal float payloadScore; private int payloadsSeen; internal Similarity similarity; protected internal PayloadNearSpanScorer(PayloadNearQuery enclosingInstance, Lucene.Net.Search.Spans.Spans spans, Weight weight, Similarity similarity, byte[] norms):base(spans, weight, similarity, norms) { InitBlock(enclosingInstance); this.spans = spans; } // Get the payloads associated with all underlying subspans public virtual void GetPayloads(Lucene.Net.Search.Spans.Spans[] subSpans) { for (int i = 0; i < subSpans.Length; i++) { if (subSpans[i] is NearSpansOrdered) { if (((NearSpansOrdered) subSpans[i]).IsPayloadAvailable()) { ProcessPayloads(((NearSpansOrdered) subSpans[i]).GetPayload(), subSpans[i].Start(), subSpans[i].End()); } GetPayloads(((NearSpansOrdered) subSpans[i]).GetSubSpans()); } else if (subSpans[i] is NearSpansUnordered) { if (((NearSpansUnordered) subSpans[i]).IsPayloadAvailable()) { ProcessPayloads(((NearSpansUnordered) subSpans[i]).GetPayload(), subSpans[i].Start(), subSpans[i].End()); } GetPayloads(((NearSpansUnordered) subSpans[i]).GetSubSpans()); } } } /// <summary> By default, uses the <see cref="PayloadFunction" /> to score the payloads, but /// can be overridden to do other things. /// /// </summary> /// <param name="payLoads">The payloads /// </param> /// <param name="start">The start position of the span being scored /// </param> /// <param name="end">The end position of the span being scored /// /// </param> /// <seealso cref="Spans"> /// </seealso> protected internal virtual void ProcessPayloads(System.Collections.Generic.ICollection<byte[]> payLoads, int start, int end) { foreach (byte[] thePayload in payLoads) { payloadScore = Enclosing_Instance.function.CurrentScore(doc, Enclosing_Instance.fieldName, start, end, payloadsSeen, payloadScore, similarity.ScorePayload(doc, Enclosing_Instance.fieldName, spans.Start(), spans.End(), thePayload, 0, thePayload.Length)); ++payloadsSeen; } } // public /*protected internal*/ override bool SetFreqCurrentDoc() { if (!more) { return false; } Lucene.Net.Search.Spans.Spans[] spansArr = new Lucene.Net.Search.Spans.Spans[1]; spansArr[0] = spans; payloadScore = 0; payloadsSeen = 0; GetPayloads(spansArr); return base.SetFreqCurrentDoc(); } public override float Score() { return base.Score() * Enclosing_Instance.function.DocScore(doc, Enclosing_Instance.fieldName, payloadsSeen, payloadScore); } protected internal override Explanation Explain(int doc) { Explanation result = new Explanation(); Explanation nonPayloadExpl = base.Explain(doc); result.AddDetail(nonPayloadExpl); Explanation payloadBoost = new Explanation(); result.AddDetail(payloadBoost); float avgPayloadScore = (payloadsSeen > 0?(payloadScore / payloadsSeen):1); payloadBoost.Value = avgPayloadScore; payloadBoost.Description = "scorePayload(...)"; result.Value = nonPayloadExpl.Value * avgPayloadScore; result.Description = "bnq, product of:"; return result; } } } }
namespace AngleSharp.Dom { using AngleSharp.Text; using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// A DOM range to gather DOM tree information. /// </summary> sealed class Range : IRange { #region Fields private Boundary _start; private Boundary _end; #endregion #region ctor public Range(IDocument document) { _start = new Boundary(document, 0); _end = new Boundary(document, 0); } private Range(Boundary start, Boundary end) { _start = start; _end = end; } #endregion #region Properties public INode Root => _start.Node.GetRoot(); public IEnumerable<INode> Nodes => CommonAncestor.GetNodes<INode>(predicate: Intersects); public INode Head => _start.Node; public Int32 Start => _start.Offset; public INode Tail => _end.Node; public Int32 End => _end.Offset; public Boolean IsCollapsed => _start.Node == _end.Node; public INode CommonAncestor { get { var container = Head; while (container != null && !Tail.Contains(container)) { container = container.Parent; } return container!; } } #endregion #region Methods public void StartWith(INode refNode, Int32 offset) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } if (refNode.NodeType == NodeType.DocumentType) { throw new DomException(DomError.InvalidNodeType); } if (offset > refNode.ChildNodes.Length) { throw new DomException(DomError.IndexSizeError); } var bp = new Boundary(refNode, offset); if (bp > _end || Root != refNode.GetRoot()) { _start = bp; } } public void EndWith(INode refNode, Int32 offset) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } if (refNode.NodeType == NodeType.DocumentType) { throw new DomException(DomError.InvalidNodeType); } if (offset > refNode.ChildNodes.Length) { throw new DomException(DomError.IndexSizeError); } var bp = new Boundary(refNode, offset); if (bp < _start || Root != refNode.GetRoot()) { _end = bp; } } public void StartBefore(INode refNode) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } var parent = refNode.Parent; if (parent is null) { throw new DomException(DomError.InvalidNodeType); } _start = new Boundary(parent, parent.ChildNodes.Index(refNode)); } public void EndBefore(INode refNode) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } var parent = refNode.Parent; if (parent is null) { throw new DomException(DomError.InvalidNodeType); } _end = new Boundary(parent, parent.ChildNodes.Index(refNode)); } public void StartAfter(INode refNode) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } var parent = refNode.Parent; if (parent is null) { throw new DomException(DomError.InvalidNodeType); } _start = new Boundary(parent, parent.ChildNodes.Index(refNode) + 1); } public void EndAfter(INode refNode) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } var parent = refNode.Parent; if (parent is null) { throw new DomException(DomError.InvalidNodeType); } _end = new Boundary(parent, parent.ChildNodes.Index(refNode) + 1); } public void Collapse(Boolean toStart) { if (toStart) { _end = _start; } else { _start = _end; } } public void Select(INode refNode) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } var parent = refNode.Parent; if (parent is null) { throw new DomException(DomError.InvalidNodeType); } var index = parent.ChildNodes.Index(refNode); _start = new Boundary(parent, index); _end = new Boundary(parent, index + 1); } public void SelectContent(INode refNode) { if (refNode is null) { throw new ArgumentNullException(nameof(refNode)); } if (refNode.NodeType == NodeType.DocumentType) { throw new DomException(DomError.InvalidNodeType); } var length = refNode.ChildNodes.Length; _start = new Boundary(refNode, 0); _end = new Boundary(refNode, length); } public void ClearContent() { if (!_start.Equals(_end)) { var newBoundary = new Boundary(); var originalStart = _start; var originalEnd = _end; if (originalEnd.Node == originalStart.Node && originalStart.Node is ICharacterData) { var strt = originalStart.Offset; var text = (ICharacterData)originalStart.Node; var span = originalEnd.Offset - originalStart.Offset; text.Replace(strt, span, String.Empty); } else { var nodesToRemove = Nodes.Where(m => !Intersects(m.Parent!)).ToArray(); if (!originalStart.Node.IsInclusiveAncestorOf(originalEnd.Node)) { var referenceNode = originalStart.Node; while (referenceNode.Parent != null && referenceNode.Parent.IsInclusiveAncestorOf(originalEnd.Node)) { referenceNode = referenceNode.Parent; } newBoundary = new Boundary(referenceNode.Parent!, referenceNode.Parent!.ChildNodes.Index(referenceNode) + 1); } else { newBoundary = originalStart; } if (originalStart.Node is ICharacterData) { var strt = originalStart.Offset; var text = (ICharacterData)originalStart.Node; var span = originalEnd.Offset - originalStart.Offset; text.Replace(strt, span, String.Empty); } foreach (var node in nodesToRemove) { node.Parent!.RemoveChild(node); } if (originalEnd.Node is ICharacterData) { var strt = 0; var text = (ICharacterData)originalEnd.Node; var span = originalEnd.Offset; text.Replace(strt, span, String.Empty); } _start = newBoundary; _end = newBoundary; } } } public IDocumentFragment ExtractContent() { var fragment = _start.Node.Owner!.CreateDocumentFragment(); if (!_start.Equals(_end)) { var newBoundary = _start; var originalStart = _start; var originalEnd = _end; if (originalStart.Node == originalEnd.Node && _start.Node is ICharacterData) { var text = (ICharacterData)originalStart.Node; var strt = originalStart.Offset; var span = originalEnd.Offset - originalStart.Offset; var clone = (ICharacterData)text.Clone(); clone.Data = text.Substring(strt, span); fragment.AppendChild(clone); text.Replace(strt, span, String.Empty); } else { var commonAncestor = originalStart.Node; while (!commonAncestor.IsInclusiveAncestorOf(originalEnd.Node)) { commonAncestor = commonAncestor.Parent!; } var firstPartiallyContainedChild = !originalStart.Node.IsInclusiveAncestorOf(originalEnd.Node) ? commonAncestor.GetNodes<INode>(predicate: IsPartiallyContained).FirstOrDefault() : null; var lastPartiallyContainedchild = !originalEnd.Node.IsInclusiveAncestorOf(originalStart.Node) ? commonAncestor.GetNodes<INode>(predicate: IsPartiallyContained).LastOrDefault() : null; var containedChildren = commonAncestor.GetNodes<INode>(predicate: Intersects).ToList(); if (containedChildren.OfType<IDocumentType>().Any()) { throw new DomException(DomError.HierarchyRequest); } if (!originalStart.Node.IsInclusiveAncestorOf(originalEnd.Node)) { var referenceNode = originalStart.Node; while (referenceNode.Parent != null && !referenceNode.IsInclusiveAncestorOf(originalEnd.Node)) { referenceNode = referenceNode.Parent; } newBoundary = new Boundary(referenceNode, referenceNode.Parent!.ChildNodes.Index(referenceNode) + 1); } if (firstPartiallyContainedChild is ICharacterData) { var text = (ICharacterData)originalStart.Node; var strt = originalStart.Offset; var span = text.Length - originalStart.Offset; var clone = (ICharacterData)text.Clone(); clone.Data = text.Substring(strt, span); fragment.AppendChild(clone); text.Replace(strt, span, String.Empty); } else if (firstPartiallyContainedChild != null) { var clone = firstPartiallyContainedChild.Clone(); fragment.AppendChild(clone); var subrange = new Range(originalStart, new Boundary(firstPartiallyContainedChild, firstPartiallyContainedChild.ChildNodes.Length)); var subfragment = subrange.ExtractContent(); fragment.AppendChild(subfragment); } foreach (var child in containedChildren) { fragment.AppendChild(child); } if (lastPartiallyContainedchild is ICharacterData) { var text = (ICharacterData)originalEnd.Node; var clone = (ICharacterData)text.Clone(); clone.Data = text.Substring(0, originalEnd.Offset); fragment.AppendChild(clone); text.Replace(0, originalEnd.Offset, String.Empty); } else if (lastPartiallyContainedchild != null) { var clone = lastPartiallyContainedchild.Clone(); fragment.AppendChild(clone); var subrange = new Range(new Boundary(lastPartiallyContainedchild, 0), originalEnd); var subfragment = subrange.ExtractContent(); fragment.AppendChild(subfragment); } _start = newBoundary; _end = newBoundary; } } return fragment; } public IDocumentFragment CopyContent() { var fragment = _start.Node.Owner!.CreateDocumentFragment(); if (!_start.Equals(_end)) { var originalStart = _start; var originalEnd = _end; if (originalStart.Node == originalEnd.Node && _start.Node is ICharacterData) { var text = (ICharacterData)originalStart.Node; var strt = originalStart.Offset; var span = originalEnd.Offset - originalStart.Offset; var clone = (ICharacterData)text.Clone(); clone.Data = text.Substring(strt, span); fragment.AppendChild(clone); } else { var commonAncestor = originalStart.Node; while (!commonAncestor.IsInclusiveAncestorOf(originalEnd.Node)) { commonAncestor = commonAncestor.Parent!; } var firstPartiallyContainedChild = !originalStart.Node.IsInclusiveAncestorOf(originalEnd.Node) ? commonAncestor.GetNodes<INode>(predicate: IsPartiallyContained).FirstOrDefault() : null; var lastPartiallyContainedchild = !originalEnd.Node.IsInclusiveAncestorOf(originalStart.Node) ? commonAncestor.GetNodes<INode>(predicate: IsPartiallyContained).LastOrDefault() : null; var containedChildren = commonAncestor.GetNodes<INode>(predicate: Intersects).ToList(); if (containedChildren.OfType<IDocumentType>().Any()) { throw new DomException(DomError.HierarchyRequest); } if (firstPartiallyContainedChild is ICharacterData) { var text = (ICharacterData)originalStart.Node; var strt = originalStart.Offset; var span = text.Length - originalStart.Offset; var clone = (ICharacterData)text.Clone(); clone.Data = text.Substring(strt, span); fragment.AppendChild(clone); } else if (firstPartiallyContainedChild != null) { var clone = firstPartiallyContainedChild.Clone(); fragment.AppendChild(clone); var subrange = new Range(originalStart, new Boundary(firstPartiallyContainedChild, firstPartiallyContainedChild.ChildNodes.Length)); var subfragment = subrange.CopyContent(); fragment.AppendChild(subfragment); } foreach (var child in containedChildren) { fragment.AppendChild(child.Clone()); } if (lastPartiallyContainedchild is ICharacterData) { var text = (ICharacterData)originalEnd.Node; var clone = (ICharacterData)text.Clone(); clone.Data = text.Substring(0, originalEnd.Offset); fragment.AppendChild(clone); } else if (lastPartiallyContainedchild != null) { var clone = lastPartiallyContainedchild.Clone(); fragment.AppendChild(clone); var subrange = new Range(new Boundary(lastPartiallyContainedchild, 0), originalEnd); var subfragment = subrange.CopyContent(); fragment.AppendChild(subfragment); } } } return fragment; } public void Insert(INode node) { if (node is null) { throw new ArgumentNullException(nameof(node)); } var snode = _start.Node; var type = snode.NodeType; var istext = type == NodeType.Text; if (type == NodeType.ProcessingInstruction || type == NodeType.Comment || (istext && snode.Parent is null)) { throw new DomException(DomError.HierarchyRequest); } var referenceNode = istext ? snode : _start.ChildAtOffset; var parent = referenceNode is null ? snode : referenceNode.Parent; parent!.EnsurePreInsertionValidity(node, referenceNode); if (istext) { referenceNode = ((IText)snode).Split(_start.Offset); parent = referenceNode.Parent; } if (node == referenceNode) { referenceNode = referenceNode.NextSibling; } node.Parent?.RemoveChild(node); var newOffset = referenceNode is null ? parent!.ChildNodes.Length : parent!.ChildNodes.Index(referenceNode); newOffset += node.NodeType == NodeType.DocumentFragment ? node.ChildNodes.Length : 1; parent.PreInsert(node, referenceNode); if (_start.Equals(_end)) { _end = new Boundary(parent, newOffset); } } public void Surround(INode newParent) { if (newParent is null) { throw new ArgumentNullException(nameof(newParent)); } if (Nodes.Any(m => m.NodeType != NodeType.Text && IsPartiallyContained(m))) { throw new DomException(DomError.InvalidState); } var type = newParent.NodeType; if (type == NodeType.Document || type == NodeType.DocumentType || type == NodeType.DocumentFragment) { throw new DomException(DomError.InvalidNodeType); } var fragment = ExtractContent(); while (newParent.HasChildNodes) { newParent.RemoveChild(newParent.FirstChild); } Insert(newParent); newParent.PreInsert(fragment, null); Select(newParent); } public IRange Clone() { return new Range(_start, _end); } public void Detach() { //Does nothing. } public Boolean Contains(INode node, Int32 offset) { if (node is null) { throw new ArgumentNullException(nameof(node)); } if (node.GetRoot() == Root) { if (node.NodeType == NodeType.DocumentType) { throw new DomException(DomError.InvalidNodeType); } if (offset > node.ChildNodes.Length) { throw new DomException(DomError.IndexSizeError); } return !IsStartAfter(node, offset) && !IsEndBefore(node, offset); } return false; } public RangePosition CompareBoundaryTo(RangeType how, IRange sourceRange) { if (sourceRange is null) { throw new ArgumentNullException(nameof(sourceRange)); } if (Root != sourceRange.Head.GetRoot()) { throw new DomException(DomError.WrongDocument); } var thisPoint = default(Boundary); var otherPoint = default(Boundary); switch (how) { case RangeType.StartToStart: thisPoint = _start; otherPoint = new Boundary(sourceRange.Head, sourceRange.Start); break; case RangeType.StartToEnd: thisPoint = _end; otherPoint = new Boundary(sourceRange.Head, sourceRange.Start); break; case RangeType.EndToEnd: thisPoint = _start; otherPoint = new Boundary(sourceRange.Tail, sourceRange.End); break; case RangeType.EndToStart: thisPoint = _end; otherPoint = new Boundary(sourceRange.Tail, sourceRange.End); break; default: throw new DomException(DomError.NotSupported); } return thisPoint.CompareTo(otherPoint); } public RangePosition CompareTo(INode node, Int32 offset) { if (node is null) { throw new ArgumentNullException(nameof(node)); } if (Root != _start.Node.GetRoot()) { throw new DomException(DomError.WrongDocument); } if (node.NodeType == NodeType.DocumentType) { throw new DomException(DomError.InvalidNodeType); } if (offset > node.ChildNodes.Length) { throw new DomException(DomError.IndexSizeError); } if (IsStartAfter(node, offset)) { return RangePosition.Before; } else if (IsEndBefore(node, offset)) { return RangePosition.After; } return RangePosition.Equal; } public Boolean Intersects(INode node) { if (node is null) { throw new ArgumentNullException(nameof(node)); } if (Root == node.GetRoot()) { var parent = node.Parent; if (parent != null) { var offset = parent.ChildNodes.Index(node); return IsEndAfter(parent, offset) && IsStartBefore(parent, offset + 1); } return true; } return false; } public override String ToString() { var sb = default(StringBuilder); var offset = Start; var dest = End; if (Head is IText startText) { if (Head == Tail) { return startText.Substring(offset, dest - offset); } else { sb ??= StringBuilderPool.Obtain(); sb.Append(startText.Substring(offset, startText.Length - offset)); } } sb ??= StringBuilderPool.Obtain(); var nodes = CommonAncestor.Descendents<IText>(); foreach (var node in nodes) { if (IsStartBefore(node, 0) && IsEndAfter(node, node.Length)) { sb.Append(node.Text); } } if (Tail is IText endText) { sb.Append(endText.Substring(0, dest)); } return sb.ToPool(); } #endregion #region Helpers private Boolean IsStartBefore(INode node, Int32 offset) { return _start < new Boundary(node, offset); } private Boolean IsStartAfter(INode node, Int32 offset) { return _start > new Boundary(node, offset); } private Boolean IsEndBefore(INode node, Int32 offset) { return _end < new Boundary(node, offset); } private Boolean IsEndAfter(INode node, Int32 offset) { return _end > new Boundary(node, offset); } private Boolean IsPartiallyContained(INode node) { var startAncestor = node.IsInclusiveAncestorOf(_start.Node); var endAncestor = node.IsInclusiveAncestorOf(_end.Node); return (startAncestor && !endAncestor) || (!startAncestor && endAncestor); } #endregion #region Boundary private readonly struct Boundary : IEquatable<Boundary> { public Boundary(INode node, Int32 offset) { Node = node; Offset = offset; } public readonly INode Node; public readonly Int32 Offset; public static Boolean operator >(Boundary a, Boundary b) { return false; } public static Boolean operator <(Boundary a, Boundary b) { return false; } public Boolean Equals(Boundary other) { return Node == other.Node && Offset == other.Offset; } public RangePosition CompareTo(Boundary other) { if (this < other) { return RangePosition.Before; } else if (this > other) { return RangePosition.After; } else { return RangePosition.Equal; } } public INode? ChildAtOffset => Node.ChildNodes.Length > Offset ? Node.ChildNodes[Offset] : null; } #endregion } }
// 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 gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.ServiceDirectory.V1 { /// <summary>Settings for <see cref="LookupServiceClient"/> instances.</summary> public sealed partial class LookupServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="LookupServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="LookupServiceSettings"/>.</returns> public static LookupServiceSettings GetDefault() => new LookupServiceSettings(); /// <summary>Constructs a new <see cref="LookupServiceSettings"/> object with default settings.</summary> public LookupServiceSettings() { } private LookupServiceSettings(LookupServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ResolveServiceSettings = existing.ResolveServiceSettings; OnCopy(existing); } partial void OnCopy(LookupServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>LookupServiceClient.ResolveService</c> and <c>LookupServiceClient.ResolveServiceAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 1000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: 5</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.Unknown"/>. /// </description> /// </item> /// <item><description>Timeout: 15 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ResolveServiceSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(15000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.Unknown))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="LookupServiceSettings"/> object.</returns> public LookupServiceSettings Clone() => new LookupServiceSettings(this); } /// <summary> /// Builder class for <see cref="LookupServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class LookupServiceClientBuilder : gaxgrpc::ClientBuilderBase<LookupServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public LookupServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public LookupServiceClientBuilder() { UseJwtAccessWithScopes = LookupServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref LookupServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<LookupServiceClient> task); /// <summary>Builds the resulting client.</summary> public override LookupServiceClient Build() { LookupServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<LookupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<LookupServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private LookupServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return LookupServiceClient.Create(callInvoker, Settings); } private async stt::Task<LookupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return LookupServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => LookupServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => LookupServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => LookupServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>LookupService client wrapper, for convenient use.</summary> /// <remarks> /// Service Directory API for looking up service data at runtime. /// </remarks> public abstract partial class LookupServiceClient { /// <summary> /// The default endpoint for the LookupService service, which is a host of "servicedirectory.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "servicedirectory.googleapis.com:443"; /// <summary>The default LookupService scopes.</summary> /// <remarks> /// The default LookupService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="LookupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="LookupServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="LookupServiceClient"/>.</returns> public static stt::Task<LookupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new LookupServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="LookupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="LookupServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="LookupServiceClient"/>.</returns> public static LookupServiceClient Create() => new LookupServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="LookupServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="LookupServiceSettings"/>.</param> /// <returns>The created <see cref="LookupServiceClient"/>.</returns> internal static LookupServiceClient Create(grpccore::CallInvoker callInvoker, LookupServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } LookupService.LookupServiceClient grpcClient = new LookupService.LookupServiceClient(callInvoker); return new LookupServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC LookupService client</summary> public virtual LookupService.LookupServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ResolveServiceResponse ResolveService(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ResolveServiceResponse> ResolveServiceAsync(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ResolveServiceResponse> ResolveServiceAsync(ResolveServiceRequest request, st::CancellationToken cancellationToken) => ResolveServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>LookupService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service Directory API for looking up service data at runtime. /// </remarks> public sealed partial class LookupServiceClientImpl : LookupServiceClient { private readonly gaxgrpc::ApiCall<ResolveServiceRequest, ResolveServiceResponse> _callResolveService; /// <summary> /// Constructs a client wrapper for the LookupService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="LookupServiceSettings"/> used within this client.</param> public LookupServiceClientImpl(LookupService.LookupServiceClient grpcClient, LookupServiceSettings settings) { GrpcClient = grpcClient; LookupServiceSettings effectiveSettings = settings ?? LookupServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callResolveService = clientHelper.BuildApiCall<ResolveServiceRequest, ResolveServiceResponse>(grpcClient.ResolveServiceAsync, grpcClient.ResolveService, effectiveSettings.ResolveServiceSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callResolveService); Modify_ResolveServiceApiCall(ref _callResolveService); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ResolveServiceApiCall(ref gaxgrpc::ApiCall<ResolveServiceRequest, ResolveServiceResponse> call); partial void OnConstruction(LookupService.LookupServiceClient grpcClient, LookupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC LookupService client</summary> public override LookupService.LookupServiceClient GrpcClient { get; } partial void Modify_ResolveServiceRequest(ref ResolveServiceRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ResolveServiceResponse ResolveService(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ResolveServiceRequest(ref request, ref callSettings); return _callResolveService.Sync(request, callSettings); } /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ResolveServiceResponse> ResolveServiceAsync(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ResolveServiceRequest(ref request, ref callSettings); return _callResolveService.Async(request, callSettings); } } }
/* 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.Linq; using System.Text; using System.Windows.Forms; using System.ComponentModel; using XenAdmin.Controls; using XenAPI; using XenAdmin.Core; using XenAdmin.Properties; using System.Threading; using System.Drawing; using System.Drawing.Design; using System.Collections.ObjectModel; using XenAdmin.Network; namespace XenAdmin.Commands { /// <summary> /// This is the base ToolStripMenuItem for StartVMOnHostToolStripMenuItem, ResumeVMOnHostToolStripMenuItem and MigrateVMToolStripMenuItem. /// </summary> internal abstract class VMOperationToolStripMenuItem : CommandToolStripMenuItem { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly vm_operations _operation; private readonly bool _resumeAfter; protected VMOperationToolStripMenuItem(Command command, bool inContextMenu, vm_operations operation) : base(command, inContextMenu) { if (operation != vm_operations.start_on && operation != vm_operations.resume_on && operation != vm_operations.pool_migrate) { throw new ArgumentException("Invalid operation", "operation"); } if (operation.Equals(vm_operations.resume_on)) _resumeAfter = true; _operation = operation; base.DropDownItems.Add(new ToolStripMenuItem()); } protected override void OnDropDownOpening(EventArgs e) { base.DropDownItems.Clear(); // Work around bug in tool kit where disabled menu items show their dropdown menus if (!Enabled) { ToolStripMenuItem emptyMenuItem = new ToolStripMenuItem(Messages.HOST_MENU_EMPTY); emptyMenuItem.Font = Program.DefaultFont; emptyMenuItem.Enabled = false; base.DropDownItems.Add(emptyMenuItem); return; } VisualMenuItemAlignData.ParentStrip = this; IXenConnection connection = Command.GetSelection()[0].Connection; bool wlb = Helpers.WlbEnabled(connection); if (wlb) { base.DropDownItems.Add(new VMOperationToolStripMenuSubItem(Messages.WLB_OPT_MENU_OPTIMAL_SERVER, Images.StaticImages._000_ServerWlb_h32bit_16)); } else { base.DropDownItems.Add(new VMOperationToolStripMenuSubItem(Messages.HOME_SERVER_MENU_ITEM, Images.StaticImages._000_ServerHome_h32bit_16)); } List<Host> hosts = new List<Host>(connection.Cache.Hosts); hosts.Sort(); foreach (Host host in hosts) { VMOperationToolStripMenuSubItem item = new VMOperationToolStripMenuSubItem(String.Format(Messages.MAINWINDOW_CONTEXT_UPDATING, host.name_label.EscapeAmpersands()), Images.StaticImages._000_ServerDisconnected_h32bit_16); item.Tag = host; base.DropDownItems.Add(item); } // start a new thread to evaluate which hosts can be used. ThreadPool.QueueUserWorkItem(delegate { SelectedItemCollection selection = Command.GetSelection(); Session session = selection[0].Connection.DuplicateSession(); WlbRecommendations recommendations = new WlbRecommendations(selection.AsXenObjects<VM>(), session); recommendations.Initialize(); if (recommendations.IsError) { EnableAppropriateHostsNoWlb(session); } else { EnableAppropriateHostsWlb(session, recommendations); } }); } private void EnableAppropriateHostsWlb(Session session, WlbRecommendations recommendations) { SelectedItemCollection selection = Command.GetSelection(); // set the first menu item to be the WLB optimal server menu item Program.Invoke(Program.MainWindow, delegate { VMOperationToolStripMenuSubItem firstItem = (VMOperationToolStripMenuSubItem)base.DropDownItems[0]; firstItem.Command = new VMOperationWlbOptimalServerCommand(Command.MainWindowCommandInterface, selection, _operation, recommendations); }); List<VMOperationToolStripMenuSubItem> hostMenuItems = new List<VMOperationToolStripMenuSubItem>(); Program.Invoke(Program.MainWindow, delegate { foreach (VMOperationToolStripMenuSubItem item in base.DropDownItems) { Host host = item.Tag as Host; if (host != null) { item.Command = new VMOperationWlbHostCommand(Command.MainWindowCommandInterface, selection, host, _operation, recommendations.GetStarRating(host)); hostMenuItems.Add(item); } } }); // Shuffle the list to make it look cool Helpers.ShuffleList(hostMenuItems); // sort the hostMenuItems by star rating hostMenuItems.Sort(new WlbHostStarCompare()); // refresh the drop-down-items from the menuItems. Program.Invoke(Program.MainWindow, delegate() { foreach (VMOperationToolStripMenuSubItem menuItem in hostMenuItems) { base.DropDownItems.Insert(hostMenuItems.IndexOf(menuItem) + 1, menuItem); } }); Program.Invoke(Program.MainWindow, () => AddAdditionalMenuItems(selection)); } private void EnableAppropriateHostsNoWlb(Session session) { SelectedItemCollection selection = Command.GetSelection(); IXenConnection connection = selection[0].Connection; VMOperationCommand cmdHome = new VMOperationHomeServerCommand(Command.MainWindowCommandInterface, selection, _operation, session); Host affinityHost = connection.Resolve(((VM)Command.GetSelection()[0].XenObject).affinity); VMOperationCommand cpmCmdHome = new CrossPoolMigrateToHomeCommand(Command.MainWindowCommandInterface, selection, affinityHost); Program.Invoke(Program.MainWindow, delegate { var firstItem = (VMOperationToolStripMenuSubItem)base.DropDownItems[0]; bool oldMigrateToHomeCmdCanRun = cmdHome.CanExecute(); if (affinityHost == null || _operation == vm_operations.start_on || !oldMigrateToHomeCmdCanRun && !cpmCmdHome.CanExecute()) firstItem.Command = cmdHome; else firstItem.Command = oldMigrateToHomeCmdCanRun ? cmdHome : cpmCmdHome; }); List<VMOperationToolStripMenuSubItem> dropDownItems = DropDownItems.Cast<VMOperationToolStripMenuSubItem>().ToList(); foreach (VMOperationToolStripMenuSubItem item in dropDownItems) { Host host = item.Tag as Host; if (host != null) { VMOperationCommand cmd = new VMOperationHostCommand(Command.MainWindowCommandInterface, selection, delegate { return host; }, host.Name().EscapeAmpersands(), _operation, session); CrossPoolMigrateCommand cpmCmd = new CrossPoolMigrateCommand(Command.MainWindowCommandInterface, selection, host, _resumeAfter); VMOperationToolStripMenuSubItem tempItem = item; Program.Invoke(Program.MainWindow, delegate { bool oldMigrateCmdCanRun = cmd.CanExecute(); if (_operation == vm_operations.start_on || (!oldMigrateCmdCanRun && !cpmCmd.CanExecute() && string.IsNullOrEmpty(cpmCmd.CantExecuteReason))) tempItem.Command = cmd; else tempItem.Command = oldMigrateCmdCanRun ? cmd : cpmCmd; }); } } Program.Invoke(Program.MainWindow, () => AddAdditionalMenuItems(selection)); } /// <summary> /// Hook to add additional members to the menu item /// Note: Called on main window thread by executing code /// </summary> /// <param name="selection"></param> protected virtual void AddAdditionalMenuItems(SelectedItemCollection selection) { return; } /// <summary> /// This class is an implementation of the 'IComparer' interface /// for sorting vm placement menuItem List when wlb is enabled /// </summary> private class WlbHostStarCompare : IComparer<VMOperationToolStripMenuSubItem> { public int Compare(VMOperationToolStripMenuSubItem x, VMOperationToolStripMenuSubItem y) { int result = 0; // if x and y are enabled, compare their start rating if (x.Enabled && y.Enabled) result = y.StarRating.CompareTo(x.StarRating); // if x and y are disabled, they are equal else if (!x.Enabled && !y.Enabled) result = 0; // if x is disabled, y is greater else if (!x.Enabled) result = 1; // if y is disabled, x is greater else if (!y.Enabled) result = -1; 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.Xml; using System.Collections; using Microsoft.Build.BuildEngine.Shared; using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities; namespace Microsoft.Build.BuildEngine { /// <summary> /// Class representing the Choose construct. The Choose class holds the list /// of When blocks and the Otherwise block. It also contains other data such /// as the XmlElement, parent project, etc. /// </summary> internal class Choose : IItemPropertyGrouping { #region Member Data private ArrayList whenClauseList = null; private When otherwiseClause = null; private When whenLastTaken = null; // If this is a persisted <Choose>, this boolean tells us whether // it came from the main project file, or an imported project file. private bool importedFromAnotherProject; // Maximum nesting level of <Choose> elements. No reasonable project needs more // than this. private const int maximumChooseNesting = 50; #endregion #region Constructors /// <summary> /// Empty constructor for the Choose object. This really should only /// be used by unit tests. /// </summary> /// <remarks> /// </remarks> /// <owner>DavidLe</owner> internal Choose ( ) { whenClauseList = new ArrayList(); } /// <summary> /// Constructor for the Choose object. Parses the contents of the Choose /// and sets up list of When blocks /// </summary> /// <remarks> /// </remarks> /// <owner>DavidLe</owner> /// <param name="parentProject"></param> /// <param name="parentGroupingCollection"></param> /// <param name="chooseElement"></param> /// <param name="importedFromAnotherProject"></param> /// <param name="nestingDepth">stack overflow guard</param> internal Choose ( Project parentProject, GroupingCollection parentGroupingCollection, XmlElement chooseElement, bool importedFromAnotherProject, int nestingDepth ) { whenClauseList = new ArrayList(); error.VerifyThrow(chooseElement != null, "Need valid <Choose> element."); // Make sure this really is the <Choose> node. ProjectXmlUtilities.VerifyThrowElementName(chooseElement, XMakeElements.choose); // Stack overflow guard. The only way in the MSBuild file format that MSBuild elements can be // legitimately nested without limit is the <Choose> construct. So, enforce a nesting limit // to avoid blowing our stack. nestingDepth++; ProjectErrorUtilities.VerifyThrowInvalidProject(nestingDepth <= maximumChooseNesting, chooseElement, "ChooseOverflow", maximumChooseNesting); this.importedFromAnotherProject = importedFromAnotherProject; // This <Choose> is coming from an existing XML element, so // walk through all the attributes and child elements, creating the // necessary When objects. // No attributes on the <Choose> element, so don't allow any. ProjectXmlUtilities.VerifyThrowProjectNoAttributes(chooseElement); bool foundOtherwise = false; // Loop through the child nodes of the <Choose> element. foreach (XmlNode chooseChildNode in chooseElement) { switch (chooseChildNode.NodeType) { // Handle XML comments under the <PropertyGroup> node (just ignore them). case XmlNodeType.Comment: // fall through case XmlNodeType.Whitespace: // ignore whitespace break; case XmlNodeType.Element: // The only two types of child nodes that a <Choose> element can contain // is are <When> elements and zero or one <Otherwise> elements. ProjectXmlUtilities.VerifyThrowProjectValidNamespace((XmlElement)chooseChildNode); if (chooseChildNode.Name == XMakeElements.when) { // don't allow <When> to follow <Otherwise> ProjectErrorUtilities.VerifyThrowInvalidProject(!foundOtherwise, chooseChildNode, "WhenNotAllowedAfterOtherwise"); When newWhen = new When(parentProject, parentGroupingCollection, (XmlElement)chooseChildNode, importedFromAnotherProject, When.Options.ProcessWhen, nestingDepth); this.whenClauseList.Add(newWhen); } else if (chooseChildNode.Name == XMakeElements.otherwise) { ProjectErrorUtilities.VerifyThrowInvalidProject(!foundOtherwise, chooseChildNode, "MultipleOtherwise"); When newWhen = new When(parentProject, parentGroupingCollection, (XmlElement)chooseChildNode, importedFromAnotherProject, When.Options.ProcessOtherwise, nestingDepth); otherwiseClause = newWhen; foundOtherwise = true; } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(chooseChildNode); } break; default: // Unrecognized child element. ProjectXmlUtilities.ThrowProjectInvalidChildElement(chooseChildNode); break; } } ProjectErrorUtilities.VerifyThrowInvalidProject(this.whenClauseList.Count != 0, chooseElement, "ChooseMustContainWhen"); } #endregion #region Properties /// <summary> /// The list of When nodes inside this Choose /// </summary> internal ArrayList Whens { get { return whenClauseList; } } /// <summary> /// The Otherwise node inside this Choose. May be null. /// </summary> internal When Otherwise { get { return otherwiseClause; } } /// <summary> /// True if this Choose is located in an imported project. /// </summary> internal bool IsImported { get { return importedFromAnotherProject; } } #endregion #region Methods /// <summary> /// Evaluates the Choose clause by stepping through each when and evaluating. /// </summary> /// <remarks> /// </remarks> /// <owner>DavidLe</owner> /// <param name="parentPropertyBag"></param> /// <param name="ignoreCondition"></param> /// <param name="honorCondition"></param> /// <param name="conditionedPropertiesTable"></param> /// <param name="pass"></param> internal void Evaluate ( BuildPropertyGroup parentPropertyBag, bool ignoreCondition, bool honorCondition, Hashtable conditionedPropertiesTable, ProcessingPass pass ) { if (pass == ProcessingPass.Pass1) { whenLastTaken = null; bool whenTaken = false; foreach (When currentWhen in this.whenClauseList) { if (currentWhen.EvaluateCondition(parentPropertyBag, conditionedPropertiesTable)) { whenTaken = true; currentWhen.Evaluate(parentPropertyBag, ignoreCondition, honorCondition, conditionedPropertiesTable, pass); whenLastTaken = currentWhen; break; } } if (!whenTaken && otherwiseClause != null) { // Process otherwise whenLastTaken = otherwiseClause; otherwiseClause.Evaluate(parentPropertyBag, ignoreCondition, honorCondition, conditionedPropertiesTable, pass); } } else { ErrorUtilities.VerifyThrow(pass == ProcessingPass.Pass2, "ProcessingPass must be Pass1 or Pass2."); whenLastTaken?.Evaluate(parentPropertyBag, ignoreCondition, honorCondition, conditionedPropertiesTable, pass); } } #endregion } }
// Camera Path 3 // Available on the Unity Asset Store // Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com/camera-path/ // For support contact [email protected] // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using System; using UnityEngine; #if UNITY_EDITOR using System.Text; using System.Xml; #endif public class CameraPathAnimator : MonoBehaviour { public float minimumCameraSpeed = 0.01f; public enum animationModes { once, loop, reverse, reverseLoop, pingPong, still } public enum orientationModes { custom,//rotations will be decided by defining orientations along the curve target,//camera will always face a defined transform mouselook,//camera will have a mouse free look followpath,//camera will use the path to determine where to face - maintaining world up as up reverseFollowpath,//camera will use the path to determine where to face, looking back on the path followTransform,//move the object to the nearest point on the path and look at target twoDimentions, fixedOrientation, none } public Transform orientationTarget; [SerializeField] private CameraPath _cameraPath; //do you want this path to automatically animate at the start of your scene public bool playOnStart = true; //the actual transform you want to animate public Transform animationObject = null; //a link to the camera component private Camera animationObjectCamera = null; //is the transform you are animating a camera? private bool _isCamera = true; private bool _playing = false; public animationModes animationMode = animationModes.once; public orientationModes orientationMode = orientationModes.custom; private float pingPongDirection = 1; public Vector3 fixedOrientaion = Vector3.forward; public Vector3 fixedPosition; public bool normalised = true; //the time used in the editor to preview the path animation public float editorPercentage = 0; //the time the path animation should last for [SerializeField] private float _pathTime = 10; //the time the path animation should last for [SerializeField] private float _pathSpeed = 10; private float _percentage = 0; private float _lastPercentage = 0; public float nearestOffset = 0; private float delayTime = 0; public float startPercent = 0; public bool animateFOV = true; public Vector3 targetModeUp = Vector3.up; //the sensitivity of the mouse in mouselook public float sensitivity = 5.0f; //the minimum the mouse can move down public float minX = -90.0f; //the maximum the mouse can move up public float maxX = 90.0f; private float rotationX = 0; private float rotationY = 0; public bool showPreview = true; public GameObject editorPreview = null; public bool showScenePreview = true; private bool _animateSceneObjectInEditor = false; public Vector3 animatedObjectStartPosition; public Quaternion animatedObjectStartRotation; //Events public delegate void AnimationStartedEventHandler(); public delegate void AnimationPausedEventHandler(); public delegate void AnimationStoppedEventHandler(); public delegate void AnimationFinishedEventHandler(); public delegate void AnimationLoopedEventHandler(); public delegate void AnimationPingPongEventHandler(); public delegate void AnimationPointReachedEventHandler(); public delegate void AnimationCustomEventHandler(string eventName); public delegate void AnimationPointReachedWithNumberEventHandler(int pointNumber); /// <summary> /// Broadcast when the Animation has begun /// </summary> public event AnimationStartedEventHandler AnimationStartedEvent; /// <summary> /// Broadcast when the animation is paused /// </summary> public event AnimationPausedEventHandler AnimationPausedEvent; /// <summary> /// Broadcast when the animation is stopped /// </summary> public event AnimationStoppedEventHandler AnimationStoppedEvent; /// <summary> /// Broadcast when the animation is complete /// </summary> public event AnimationFinishedEventHandler AnimationFinishedEvent; /// <summary> /// Broadcast when the animation has reached the end of the loop and begins the animation again /// </summary> public event AnimationLoopedEventHandler AnimationLoopedEvent; /// <summary> /// Broadcast when the end of a path animation is reached and the animation ping pongs back /// </summary> public event AnimationPingPongEventHandler AnimationPingPongEvent; /// <summary> /// Broadcast when a point is reached /// </summary> public event AnimationPointReachedEventHandler AnimationPointReachedEvent; /// <summary> /// Broadcast when a point is reached sending the point number index with it /// </summary> public event AnimationPointReachedWithNumberEventHandler AnimationPointReachedWithNumberEvent; /// <summary> /// Broadcast when a user defined event is fired sending the event name as a string /// </summary> public event AnimationCustomEventHandler AnimationCustomEvent; //PUBLIC METHODS //Script based controls - hook up your scripts to these to control your /// <summary> /// Gets or sets the path speed. /// </summary> /// <value> /// The path speed. /// </value> public float pathSpeed { get { return _pathSpeed; } set { if (_cameraPath.speedList.listEnabled) Debug.LogWarning("Path Speed in Animator component is ignored and overridden by Camera Path speed points."); _pathSpeed = Mathf.Max(value, minimumCameraSpeed); } } /// <summary> /// Gets or sets the path time (use only in the Animation Mode Still. /// </summary> /// <value> /// The animation time. /// </value> public float animationTime { get { return _pathTime; } set { if (animationMode != animationModes.still) Debug.LogWarning("Path time is ignored and overridden during animation when not in Animation Mode Still."); _pathTime = Mathf.Max(value, 0.0001f); } } /// <summary> /// Retreive the current time of the path animation /// </summary> public float currentTime { get { return _pathTime * _percentage; } } /// <summary> /// Play the path. If path has finished do not play it. /// </summary> public void Play() { _playing = true; if (!isReversed) { if(_percentage == 0) { if (AnimationStartedEvent != null) AnimationStartedEvent(); cameraPath.eventList.OnAnimationStart(0); } } else { if(_percentage == 1) { if (AnimationStartedEvent != null) AnimationStartedEvent(); cameraPath.eventList.OnAnimationStart(1); } } _lastPercentage = _percentage; } /// <summary> /// Stop and reset the animation back to the beginning /// </summary> public void Stop() { _playing = false; _percentage = 0; if (AnimationStoppedEvent != null) AnimationStoppedEvent(); } /// <summary> /// Pause the animation where it is /// </summary> public void Pause() { _playing = false; if (AnimationPausedEvent != null) AnimationPausedEvent(); } /// <summary> /// set the time of the animtion /// </summary> /// <param name="value">Seek Percent 0-1</param> public void Seek(float value) { _percentage = Mathf.Clamp01(value); _lastPercentage = _percentage; //thanks kelnishi! UpdateAnimationTime(false); UpdatePointReached(); bool p = _playing; _playing = true; UpdateAnimation(); _playing = p; } /// <summary> /// Is the animation playing /// </summary> public bool isPlaying { get { return _playing; } } /// <summary> /// Current percent of animation /// </summary> public float percentage { get { return _percentage; } } /// <summary> /// Is the animation ping pong direction forward /// </summary> public bool pingPongGoingForward { get { return pingPongDirection == 1; } } /// <summary> /// Reverse the animation /// </summary> public void Reverse() { switch (animationMode) { case animationModes.once: animationMode = animationModes.reverse; break; case animationModes.reverse: animationMode = animationModes.once; break; case animationModes.pingPong: pingPongDirection = pingPongDirection == -1 ? 1 : -1; break; case animationModes.loop: animationMode = animationModes.reverseLoop; break; case animationModes.reverseLoop: animationMode = animationModes.loop; break; } } /// <summary> /// A link to the Camera Path component /// </summary> public CameraPath cameraPath { get { if (!_cameraPath) _cameraPath = GetComponent<CameraPath>(); return _cameraPath; } } /// <summary> /// Retrieve the animation orientation at a percent based on the animation mode /// </summary> /// <param name="percent">Path Percent 0-1</param> /// <param name="ignoreNormalisation">Should the percetage be normalised</param> /// <returns>A rotation</returns> public Quaternion GetAnimatedOrientation(float percent, bool ignoreNormalisation) { Quaternion output = Quaternion.identity; Vector3 currentPosition, forward; // bool isStill = animationMode == animationModes.still; switch (orientationMode) { case orientationModes.custom: output = cameraPath.GetPathRotation(percent, ignoreNormalisation); break; case orientationModes.target: currentPosition = cameraPath.GetPathPosition(percent); if(orientationTarget != null) forward = orientationTarget.transform.position - currentPosition; else forward = Vector3.forward; output = Quaternion.LookRotation(forward, targetModeUp); break; case orientationModes.followpath: output = Quaternion.LookRotation(cameraPath.GetPathDirection(percent)); output *= Quaternion.Euler(transform.forward * -cameraPath.GetPathTilt(percent)); break; case orientationModes.reverseFollowpath: output = Quaternion.LookRotation(-cameraPath.GetPathDirection(percent)); output *= Quaternion.Euler(transform.forward * -cameraPath.GetPathTilt(percent)); break; case orientationModes.mouselook: if(!Application.isPlaying) { output = Quaternion.LookRotation(cameraPath.GetPathDirection(percent)); output *= Quaternion.Euler(transform.forward * -cameraPath.GetPathTilt(percent)); } else { output = GetMouseLook(); } break; case orientationModes.followTransform: if(orientationTarget == null) return Quaternion.identity; float nearestPerc = cameraPath.GetNearestPoint(orientationTarget.position); nearestPerc = Mathf.Clamp01(nearestPerc + nearestOffset); currentPosition = cameraPath.GetPathPosition(nearestPerc); forward = orientationTarget.transform.position - currentPosition; output = Quaternion.LookRotation(forward); break; case orientationModes.twoDimentions: output = Quaternion.LookRotation(Vector3.forward); break; case orientationModes.fixedOrientation: output = Quaternion.LookRotation(fixedOrientaion); break; case orientationModes.none: output = animationObject.rotation; break; } output *= transform.rotation; return output; } //MONOBEHAVIOURS private void Awake() { if(animationObject == null) _isCamera = false; else { animationObjectCamera = animationObject.GetComponentInChildren<Camera>(); _isCamera = animationObjectCamera != null; } Camera[] cams = Camera.allCameras; if (cams.Length == 0) { Debug.LogWarning("Warning: There are no cameras in the scene"); _isCamera = false; } if (!isReversed) { _percentage = 0+startPercent; } else { _percentage = 1-startPercent; } Vector3 initalRotation = cameraPath.GetPathRotation(_percentage, false).eulerAngles; rotationX = initalRotation.y; rotationY = initalRotation.x; } private void OnEnable() { cameraPath.eventList.CameraPathEventPoint += OnCustomEvent; cameraPath.delayList.CameraPathDelayEvent += OnDelayEvent; if (animationObject != null) animationObjectCamera = animationObject.GetComponentInChildren<Camera>(); } private void Start() { if (playOnStart) Play(); if(Application.isPlaying && orientationTarget==null && (orientationMode==orientationModes.followTransform || orientationMode == orientationModes.target)) Debug.LogWarning("There has not been an orientation target specified in the Animation component of Camera Path.",transform); } private void Update() { if (!isCamera) { if (_playing) { UpdateAnimationTime(); UpdateAnimation(); UpdatePointReached(); } else { if (_cameraPath.nextPath != null && _percentage >= 1) { PlayNextAnimation(); } } } } private void LateUpdate() { if (isCamera) { if (_playing) { UpdateAnimationTime(); UpdateAnimation(); UpdatePointReached(); } else { if (_cameraPath.nextPath != null && _percentage >= 1) { PlayNextAnimation(); } } } } private void OnDisable() { CleanUp(); } private void OnDestroy() { CleanUp(); } //PRIVATE METHODS private void PlayNextAnimation() { if (_cameraPath.nextPath != null) { _cameraPath.nextPath.GetComponent<CameraPathAnimator>().Play(); _percentage = 0; Stop(); } } void UpdateAnimation() { if (animationObject == null) { Debug.LogError("There is no animation object specified in the Camera Path Animator component. Nothing to animate.\nYou can find this component in the main camera path game object called "+gameObject.name+"."); Stop(); return; } if (!_playing) return; if(animationMode != animationModes.still) { if (cameraPath.speedList.listEnabled) _pathTime = _cameraPath.pathLength / Mathf.Max(cameraPath.GetPathSpeed(_percentage), minimumCameraSpeed); else _pathTime = _cameraPath.pathLength / Mathf.Max(_pathSpeed * cameraPath.GetPathEase(_percentage), minimumCameraSpeed); animationObject.position = cameraPath.GetPathPosition(_percentage); } if(orientationMode != orientationModes.none) animationObject.rotation = GetAnimatedOrientation(_percentage,false); if(isCamera && _cameraPath.fovList.listEnabled) { if (!animationObjectCamera.isOrthoGraphic) animationObjectCamera.fieldOfView = _cameraPath.GetPathFOV(_percentage); else animationObjectCamera.orthographicSize = _cameraPath.GetPathOrthographicSize(_percentage); } CheckEvents(); } private void UpdatePointReached() { if(_percentage == _lastPercentage)//no movement return; if (Mathf.Abs(percentage - _lastPercentage) > 0.999f) { _lastPercentage = percentage;//probable loop return; } for (int i = 0; i < cameraPath.realNumberOfPoints; i++) { CameraPathControlPoint point = cameraPath[i]; bool eventBetweenAnimationDelta = (point.percentage >= _lastPercentage && point.percentage <= percentage) || (point.percentage >= percentage && point.percentage <= _lastPercentage); if (eventBetweenAnimationDelta) { if (AnimationPointReachedEvent != null) AnimationPointReachedEvent(); if (AnimationPointReachedWithNumberEvent != null) AnimationPointReachedWithNumberEvent(i); } } _lastPercentage = percentage; } private void UpdateAnimationTime() { UpdateAnimationTime(true); } private void UpdateAnimationTime(bool advance) { if(orientationMode == orientationModes.followTransform) return; if(delayTime > 0) { delayTime += -Time.deltaTime; return; } if(advance) { switch(animationMode) { case animationModes.once: if(_percentage >= 1) { _playing = false; if(AnimationFinishedEvent != null) AnimationFinishedEvent(); } else { _percentage += Time.deltaTime * (1.0f / _pathTime); } break; case animationModes.loop: if(_percentage >= 1) { _percentage = 0; _lastPercentage = 0; if(AnimationLoopedEvent != null) AnimationLoopedEvent(); } _percentage += Time.deltaTime * (1.0f / _pathTime); break; case animationModes.reverseLoop: if(_percentage <= 0) { _percentage = 1; _lastPercentage = 1; if(AnimationLoopedEvent != null) AnimationLoopedEvent(); } _percentage += -Time.deltaTime * (1.0f / _pathTime); break; case animationModes.reverse: if(_percentage <= 0.0f) { _percentage = 0.0f; _playing = false; if(AnimationFinishedEvent != null) AnimationFinishedEvent(); } else { _percentage += -Time.deltaTime * (1.0f / _pathTime); } break; case animationModes.pingPong: float timeStep = Time.deltaTime * (1.0f / _pathTime); _percentage += timeStep * pingPongDirection; if(_percentage >= 1) { _percentage = 1.0f - timeStep; _lastPercentage = 1; pingPongDirection = -1; if(AnimationPingPongEvent != null) AnimationPingPongEvent(); } if(_percentage <= 0) { _percentage = timeStep; _lastPercentage = 0; pingPongDirection = 1; if(AnimationPingPongEvent != null) AnimationPingPongEvent(); } break; case animationModes.still: if(_percentage >= 1) { _playing = false; if (AnimationFinishedEvent != null) AnimationFinishedEvent(); } else { _percentage += Time.deltaTime * (1.0f / _pathTime); } break; } } _percentage = Mathf.Clamp01(_percentage); } private Quaternion GetMouseLook() { if (animationObject == null) return Quaternion.identity; rotationX += Input.GetAxis("Mouse X") * sensitivity; rotationY += -Input.GetAxis("Mouse Y") * sensitivity; rotationY = Mathf.Clamp(rotationY, minX, maxX); return Quaternion.Euler(new Vector3(rotationY, rotationX, 0)); } private void CheckEvents() { cameraPath.CheckEvents(_percentage); } private bool isReversed { get { return (animationMode == animationModes.reverse || animationMode == animationModes.reverseLoop || pingPongDirection < 0); } } public bool isCamera { get { if (animationObject == null) _isCamera = false; else { _isCamera = animationObjectCamera != null; } return _isCamera; } } public bool animateSceneObjectInEditor { get {return _animateSceneObjectInEditor;} set { if (value != _animateSceneObjectInEditor) { _animateSceneObjectInEditor = value; if (animationObject != null && animationMode != animationModes.still) { if (_animateSceneObjectInEditor) { animatedObjectStartPosition = animationObject.transform.position; animatedObjectStartRotation = animationObject.transform.rotation; } else { animationObject.transform.position = animatedObjectStartPosition; animationObject.transform.rotation = animatedObjectStartRotation; } } } _animateSceneObjectInEditor = value; } } private void CleanUp() { cameraPath.eventList.CameraPathEventPoint += OnCustomEvent; cameraPath.delayList.CameraPathDelayEvent += OnDelayEvent; } private void OnDelayEvent(float time) { if(time > 0) delayTime = time;//start delay timer else Pause();//indeffinite delay } private void OnCustomEvent(string eventName) { if(AnimationCustomEvent != null) AnimationCustomEvent(eventName); } #if UNITY_EDITOR /// <summary> /// Convert this camera path into an xml string for export /// </summary> /// <returns>A generated XML string</returns> public string ToXML() { StringBuilder sb = new StringBuilder(); sb.AppendLine("<animator>"); sb.AppendLine("<animationObject>" + ((animationObject != null) ? animationObject.name : "null") + "</animationObject>"); sb.AppendLine("<orientationTarget>" + ((orientationTarget != null) ? orientationTarget.name : "null") + "</orientationTarget>"); sb.AppendLine("<animateSceneObjectInEditor>" + _animateSceneObjectInEditor + "</animateSceneObjectInEditor>"); sb.AppendLine("<playOnStart>" + playOnStart + "</playOnStart>"); sb.AppendLine("<animationMode>" + animationMode + "</animationMode>"); sb.AppendLine("<orientationMode>" + orientationMode + "</orientationMode>"); sb.AppendLine("<normalised>" + normalised + "</normalised>"); sb.AppendLine("<pathSpeed>" + _pathSpeed + "</pathSpeed>"); sb.AppendLine("</animator>"); return sb.ToString(); } /// <summary> /// Import XML data into this camera path overwriting the current data /// </summary> /// <param name="XMLPath">An XML file path</param> public void FromXML(XmlNode xml) { if(xml == null) return; GameObject animationObjectGO = GameObject.Find(xml["animationObject"].FirstChild.Value); if(animationObjectGO != null) animationObject = animationObjectGO.transform; GameObject orientationTargetGO = GameObject.Find(xml["orientationTarget"].FirstChild.Value); if (orientationTargetGO != null) orientationTarget = orientationTargetGO.transform; _animateSceneObjectInEditor = bool.Parse(xml["animateSceneObjectInEditor"].FirstChild.Value); playOnStart = bool.Parse(xml["playOnStart"].FirstChild.Value); animationMode = (animationModes)Enum.Parse(typeof(animationModes), xml["animationMode"].FirstChild.Value); orientationMode = (orientationModes)Enum.Parse(typeof(orientationModes), xml["orientationMode"].FirstChild.Value); normalised = bool.Parse(xml["normalised"].FirstChild.Value); _pathSpeed = float.Parse(xml["pathSpeed"].FirstChild.Value); } #endif }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore : global::pony.unity3d.ui.TintButton { public TextureButtonUCore(global::haxe.lang.EmptyObject empty) : base(global::haxe.lang.EmptyObject.EMPTY) { unchecked { } #line default } public TextureButtonUCore() : base() { unchecked { } #line default } public static new object __hx_createEmpty() { unchecked { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return new global::pony.unity3d.ui.ucore.TextureButtonUCore(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return new global::pony.unity3d.ui.ucore.TextureButtonUCore(); } #line default } public global::UnityEngine.Texture[] defs; public global::UnityEngine.Texture[] overs; public global::UnityEngine.Texture[] press; public override void Start() { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int _g1 = 0; #line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int _g = ( this.overs as global::System.Array ).Length; #line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" while (( _g1 < _g )) { #line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int i = _g1++; #line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" if (( this.overs[i] != default(global::UnityEngine.Texture) )) { global::haxe.lang.Function __temp_stmt703 = default(global::haxe.lang.Function); #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t = new global::Array<object>(new object[]{this.overs[i]}); #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("txset"), ((int) (438599838) ))) )}); #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt703 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_24__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f) ))) )); } #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object __temp_stmt702 = global::pony._Function.Function_Impl_.@from(__temp_stmt703, 1); #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Focus, i})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt702, true), default(global::haxe.lang.Null<int>)); global::haxe.lang.Function __temp_stmt705 = default(global::haxe.lang.Function); #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t1 = new global::Array<object>(new object[]{this.overs[i]}); #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f1 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("txset"), ((int) (438599838) ))) )}); #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt705 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_25__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f1) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t1) ))) )); } #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object __temp_stmt704 = global::pony._Function.Function_Impl_.@from(__temp_stmt705, 1); #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Leave, i})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt704, true), default(global::haxe.lang.Null<int>)); } } } #line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int _g11 = 0; #line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int _g2 = ( this.press as global::System.Array ).Length; #line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" while (( _g11 < _g2 )) { #line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int i1 = _g11++; #line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" if (( this.press[i1] != default(global::UnityEngine.Texture) )) { global::haxe.lang.Function __temp_stmt707 = default(global::haxe.lang.Function); #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t2 = new global::Array<object>(new object[]{this.press[i1]}); #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f2 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("txset"), ((int) (438599838) ))) )}); #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt707 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_29__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t2) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f2) ))) )); } #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object __temp_stmt706 = global::pony._Function.Function_Impl_.@from(__temp_stmt707, 1); #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Press, i1})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt706, true), default(global::haxe.lang.Null<int>)); } } } #line 32 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" if (( ( this.defs as global::System.Array ).Length == 0 )) { global::haxe.lang.Function __temp_stmt717 = default(global::haxe.lang.Function); #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t3 = new global::Array<object>(new object[]{this.guiTexture.texture}); #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f3 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("txset"), ((int) (438599838) ))) )}); #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt717 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_33__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t3) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f3) ))) )); } #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object __temp_stmt716 = global::pony._Function.Function_Impl_.@from(__temp_stmt717, 1); #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Default, 0})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt716, true), default(global::haxe.lang.Null<int>)); } else { #line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.defs[0] = this.guiTexture.texture; { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int _g12 = 0; #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int _g3 = ( this.defs as global::System.Array ).Length; #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" while (( _g12 < _g3 )) { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" int i2 = _g12++; #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" if (( this.defs[i2] != default(global::UnityEngine.Texture) )) { global::haxe.lang.Function __temp_stmt709 = default(global::haxe.lang.Function); #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t4 = new global::Array<object>(new object[]{this.defs[i2]}); #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f4 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("txset"), ((int) (438599838) ))) )}); #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt709 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_37__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t4) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f4) ))) )); } #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object __temp_stmt708 = global::pony._Function.Function_Impl_.@from(__temp_stmt709, 1); #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Default, i2})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt708, true), default(global::haxe.lang.Null<int>)); object __temp_stmt710 = default(object); #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::haxe.lang.Function __temp_stmt711 = default(global::haxe.lang.Function); #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t5 = new global::Array<object>(new object[]{this.defs[i2]}); #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f6 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("_txset"), ((int) (369870815) ))) )}); #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt711 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_38__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t5) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f6) ))) )); } #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object f5 = global::pony._Function.Function_Impl_.@from(__temp_stmt711, 0); #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt710 = global::pony.events._Listener.Listener_Impl_._fromFunction(f5, false); } #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Focus, i2})).@add(__temp_stmt710, default(global::haxe.lang.Null<int>)); object __temp_stmt712 = default(object); #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::haxe.lang.Function __temp_stmt713 = default(global::haxe.lang.Function); #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t6 = new global::Array<object>(new object[]{this.defs[i2]}); #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f8 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("_txset"), ((int) (369870815) ))) )}); #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt713 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_39__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f8) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t6) ))) )); } #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object f7 = global::pony._Function.Function_Impl_.@from(__temp_stmt713, 0); #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt712 = global::pony.events._Listener.Listener_Impl_._fromFunction(f7, false); } #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Leave, i2})).@add(__temp_stmt712, default(global::haxe.lang.Null<int>)); object __temp_stmt714 = default(object); #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::haxe.lang.Function __temp_stmt715 = default(global::haxe.lang.Function); #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> t7 = new global::Array<object>(new object[]{this.defs[i2]}); #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::Array<object> f10 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("_txset"), ((int) (369870815) ))) )}); #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt715 = new global::pony.unity3d.ui.ucore.TextureButtonUCore_Start_40__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f10) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (t7) ))) )); } #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" object f9 = global::pony._Function.Function_Impl_.@from(__temp_stmt715, 0); #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" __temp_stmt714 = global::pony.events._Listener.Listener_Impl_._fromFunction(f9, false); } #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Press, i2})).@add(__temp_stmt714, default(global::haxe.lang.Null<int>)); } } } } #line 44 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" base.Start(); } #line default } public virtual void txset(global::UnityEngine.Texture t, global::pony.events.Event e) { unchecked { #line 48 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.restoreColor(); this.guiTexture.texture = t; { #line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" if (( e.parent != default(global::pony.events.Event) )) { #line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" e.parent.stopPropagation(); } #line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" e._stopPropagation = true; } } #line default } public virtual void _txset(global::UnityEngine.Texture t) { unchecked { #line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.guiTexture.texture = t; } #line default } public override object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" switch (hash) { case 1216893827: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.press = ((global::UnityEngine.Texture[]) (@value) ); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return @value; } case 935762079: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.overs = ((global::UnityEngine.Texture[]) (@value) ); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return @value; } case 1114002190: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.defs = ((global::UnityEngine.Texture[]) (@value) ); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return @value; } default: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return base.__hx_setField(field, hash, @value, handleProperties); } } } #line default } public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" switch (hash) { case 369870815: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("_txset"), ((int) (369870815) ))) ); } case 438599838: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("txset"), ((int) (438599838) ))) ); } case 389604418: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) ); } case 1216893827: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return this.press; } case 935762079: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return this.overs; } case 1114002190: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return this.defs; } default: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties); } } } #line default } public override object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" switch (hash) { case 389604418: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return global::haxe.lang.Runtime.slowCallField(this, field, dynargs); } case 369870815: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this._txset(((global::UnityEngine.Texture) (dynargs[0]) )); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" break; } case 438599838: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.txset(((global::UnityEngine.Texture) (dynargs[0]) ), ((global::pony.events.Event) (dynargs[1]) )); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" break; } default: { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return base.__hx_invokeField(field, hash, dynargs); } } #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return default(object); } #line default } public override void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" baseArr.push("press"); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" baseArr.push("overs"); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" baseArr.push("defs"); #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" { #line 15 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" base.__hx_getFields(baseArr); } } #line default } } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_24__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_24__Fun(global::Array<object> t, global::Array<object> f) : base(1, 0) { unchecked { #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t = t; #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f = f; } #line default } public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1) { unchecked { #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::pony.events.Event e = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) ); #line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.Texture) (this.t[0]) ), e); } #line default } public global::Array<object> t; public global::Array<object> f; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_25__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_25__Fun(global::Array<object> f1, global::Array<object> t1) : base(1, 0) { unchecked { #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f1 = f1; #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t1 = t1; } #line default } public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1) { unchecked { #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::pony.events.Event e1 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) ); #line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f1[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.Texture) (this.t1[0]) ), e1); } #line default } public global::Array<object> f1; public global::Array<object> t1; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_29__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_29__Fun(global::Array<object> t2, global::Array<object> f2) : base(1, 0) { unchecked { #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t2 = t2; #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f2 = f2; } #line default } public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1) { unchecked { #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::pony.events.Event e2 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) ); #line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f2[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.Texture) (this.t2[0]) ), e2); } #line default } public global::Array<object> t2; public global::Array<object> f2; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_33__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_33__Fun(global::Array<object> t3, global::Array<object> f3) : base(1, 0) { unchecked { #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t3 = t3; #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f3 = f3; } #line default } public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1) { unchecked { #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::pony.events.Event e3 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) ); #line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f3[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.Texture) (this.t3[0]) ), e3); } #line default } public global::Array<object> t3; public global::Array<object> f3; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_37__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_37__Fun(global::Array<object> t4, global::Array<object> f4) : base(1, 0) { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t4 = t4; #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f4 = f4; } #line default } public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1) { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" global::pony.events.Event e4 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) ); #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f4[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.Texture) (this.t4[0]) ), e4); } #line default } public global::Array<object> t4; public global::Array<object> f4; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_38__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_38__Fun(global::Array<object> t5, global::Array<object> f6) : base(0, 0) { unchecked { #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t5 = t5; #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f6 = f6; } #line default } public override object __hx_invoke0_o() { unchecked { #line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f6[0]) ).__hx_invoke1_o(default(double), ((global::UnityEngine.Texture) (this.t5[0]) )); } #line default } public global::Array<object> t5; public global::Array<object> f6; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_39__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_39__Fun(global::Array<object> f8, global::Array<object> t6) : base(0, 0) { unchecked { #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f8 = f8; #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t6 = t6; } #line default } public override object __hx_invoke0_o() { unchecked { #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f8[0]) ).__hx_invoke1_o(default(double), ((global::UnityEngine.Texture) (this.t6[0]) )); } #line default } public global::Array<object> f8; public global::Array<object> t6; } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class TextureButtonUCore_Start_40__Fun : global::haxe.lang.Function { public TextureButtonUCore_Start_40__Fun(global::Array<object> f10, global::Array<object> t7) : base(0, 0) { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.f10 = f10; #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" this.t7 = t7; } #line default } public override object __hx_invoke0_o() { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/TextureButtonUCore.hx" return ((global::haxe.lang.Function) (this.f10[0]) ).__hx_invoke1_o(default(double), ((global::UnityEngine.Texture) (this.t7[0]) )); } #line default } public global::Array<object> f10; public global::Array<object> t7; } }
// 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.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class libproc { // Constants from sys\param.h private const int MAXCOMLEN = 16; private const int MAXPATHLEN = 1024; // Constants from proc_info.h private const int MAXTHREADNAMESIZE = 64; private const int PROC_PIDLISTFDS = 1; private const int PROC_PIDTASKALLINFO = 2; private const int PROC_PIDTHREADINFO = 5; private const int PROC_PIDLISTTHREADS = 6; private const int PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN; private static int PROC_PIDLISTFD_SIZE = Marshal.SizeOf<proc_fdinfo>(); private static int PROC_PIDLISTTHREADS_SIZE = (Marshal.SizeOf<uint>() * 2); // Constants from sys\resource.h private const int RUSAGE_SELF = 0; // Defines from proc_info.h internal enum ThreadRunState { TH_STATE_RUNNING = 1, TH_STATE_STOPPED = 2, TH_STATE_WAITING = 3, TH_STATE_UNINTERRUPTIBLE = 4, TH_STATE_HALTED = 5 } // Defines in proc_info.h [Flags] internal enum ThreadFlags { TH_FLAGS_SWAPPED = 0x1, TH_FLAGS_IDLE = 0x2 } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_bsdinfo { internal uint pbi_flags; internal uint pbi_status; internal uint pbi_xstatus; internal uint pbi_pid; internal uint pbi_ppid; internal uint pbi_uid; internal uint pbi_gid; internal uint pbi_ruid; internal uint pbi_rgid; internal uint pbi_svuid; internal uint pbi_svgid; internal uint reserved; internal fixed byte pbi_comm[MAXCOMLEN]; internal fixed byte pbi_name[MAXCOMLEN * 2]; internal uint pbi_nfiles; internal uint pbi_pgid; internal uint pbi_pjobc; internal uint e_tdev; internal uint e_tpgid; internal int pbi_nice; internal ulong pbi_start_tvsec; internal ulong pbi_start_tvusec; } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_taskinfo { internal ulong pti_virtual_size; internal ulong pti_resident_size; internal ulong pti_total_user; internal ulong pti_total_system; internal ulong pti_threads_user; internal ulong pti_threads_system; internal int pti_policy; internal int pti_faults; internal int pti_pageins; internal int pti_cow_faults; internal int pti_messages_sent; internal int pti_messages_received; internal int pti_syscalls_mach; internal int pti_syscalls_unix; internal int pti_csw; internal int pti_threadnum; internal int pti_numrunning; internal int pti_priority; }; // from sys\resource.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct rusage_info_v3 { internal fixed byte ri_uuid[16]; internal ulong ri_user_time; internal ulong ri_system_time; internal ulong ri_pkg_idle_wkups; internal ulong ri_interrupt_wkups; internal ulong ri_pageins; internal ulong ri_wired_size; internal ulong ri_resident_size; internal ulong ri_phys_footprint; internal ulong ri_proc_start_abstime; internal ulong ri_proc_exit_abstime; internal ulong ri_child_user_time; internal ulong ri_child_system_time; internal ulong ri_child_pkg_idle_wkups; internal ulong ri_child_interrupt_wkups; internal ulong ri_child_pageins; internal ulong ri_child_elapsed_abstime; internal ulong ri_diskio_bytesread; internal ulong ri_diskio_byteswritten; internal ulong ri_cpu_time_qos_default; internal ulong ri_cpu_time_qos_maintenance; internal ulong ri_cpu_time_qos_background; internal ulong ri_cpu_time_qos_utility; internal ulong ri_cpu_time_qos_legacy; internal ulong ri_cpu_time_qos_user_initiated; internal ulong ri_cpu_time_qos_user_interactive; internal ulong ri_billed_system_time; internal ulong ri_serviced_system_time; } // From proc_info.h [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal unsafe struct proc_taskallinfo { internal proc_bsdinfo pbsd; internal proc_taskinfo ptinfo; } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_threadinfo { internal ulong pth_user_time; internal ulong pth_system_time; internal int pth_cpu_usage; internal int pth_policy; internal int pth_run_state; internal int pth_flags; internal int pth_sleep_time; internal int pth_curpri; internal int pth_priority; internal int pth_maxpriority; internal fixed byte pth_name[MAXTHREADNAMESIZE]; } [StructLayout(LayoutKind.Sequential)] internal struct proc_fdinfo { internal int proc_fd; internal uint proc_fdtype; } /// <summary> /// Queries the OS for the PIDs for all running processes /// </summary> /// <param name="buffer">A pointer to the memory block where the PID array will start</param> /// <param name="buffersize">The length of the block of memory allocated for the PID array</param> /// <returns>Returns the number of elements (PIDs) in the buffer</returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_listallpids( int* pBuffer, int buffersize); /// <summary> /// Queries the OS for the list of all running processes and returns the PID for each /// </summary> /// <returns>Returns a list of PIDs corresponding to all running processes</returns> internal static unsafe int[] proc_listallpids() { // Get the number of processes currently running to know how much data to allocate int numProcesses = proc_listallpids(null, 0); if (numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } int[] processes; do { // Create a new array for the processes (plus a 10% buffer in case new processes have spawned) // Since we don't know how many threads there could be, if result == size, that could mean two things // 1) We guessed exactly how many processes there are // 2) There are more processes that we didn't get since our buffer is too small // To make sure it isn't #2, when the result == size, increase the buffer and try again processes = new int[(int)(numProcesses * 1.10)]; fixed (int* pBuffer = processes) { numProcesses = proc_listallpids(pBuffer, processes.Length * Marshal.SizeOf<int>()); if (numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } } } while (numProcesses == processes.Length); // Remove extra elements Array.Resize<int>(ref processes, numProcesses); return processes; } /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTASKALLINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_taskallinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_taskallinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTHREADINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_threadinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_threadinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDLISTFDS</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_fdinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_fdinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTASKALLINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size ulong[]) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, ulong* buffer, int bufferSize); /// <summary> /// Gets the process information for a given process /// </summary> /// <param name="pid">The PID (process ID) of the process</param> /// <returns> /// Returns a valid proc_taskallinfo struct for valid processes that the caller /// has permission to access; otherwise, returns null /// </returns> internal static unsafe proc_taskallinfo? GetProcessInfoById(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } // Get the process information for the specified pid int size = Marshal.SizeOf<proc_taskallinfo>(); proc_taskallinfo info = default(proc_taskallinfo); int result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, size); return (result == size ? new proc_taskallinfo?(info) : null); } /// <summary> /// Gets the thread information for the given thread /// </summary> /// <param name="thread">The ID of the thread to query for information</param> /// <returns> /// Returns a valid proc_threadinfo struct for valid threads that the caller /// has permissions to access; otherwise, returns null /// </returns> internal static unsafe proc_threadinfo? GetThreadInfoById(int pid, ulong thread) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } // Negative TIDs are invalid if (thread < 0) { throw new ArgumentOutOfRangeException("thread"); } // Get the thread information for the specified thread in the specified process int size = Marshal.SizeOf<proc_threadinfo>(); proc_threadinfo info = default(proc_threadinfo); int result = proc_pidinfo(pid, PROC_PIDTHREADINFO, (ulong)thread, &info, size); return (result == size ? new proc_threadinfo?(info) : null); } internal static unsafe List<KeyValuePair<ulong, proc_threadinfo?>> GetAllThreadsInProcess(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } int result = 0; int size = 20; // start assuming 20 threads is enough ulong[] threadIds = null; var threads = new List<KeyValuePair<ulong, proc_threadinfo?>>(); // We have no way of knowning how many threads the process has (and therefore how big our buffer should be) // so while the return value of the function is the same as our buffer size (meaning it completely filled // our buffer), double our buffer size and try again. This ensures that we don't miss any threads do { threadIds = new ulong[size]; fixed (ulong* pBuffer = threadIds) { result = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, pBuffer, Marshal.SizeOf<ulong>() * threadIds.Length); } if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return threads; } else { checked { size *= 2; } } } while (result == Marshal.SizeOf<ulong>() * threadIds.Length); Debug.Assert((result % Marshal.SizeOf<ulong>()) == 0); // Loop over each thread and get the thread info int count = (int)(result / Marshal.SizeOf<ulong>()); threads.Capacity = count; for (int i = 0; i < count; i++) { threads.Add(new KeyValuePair<ulong, proc_threadinfo?>(threadIds[i], GetThreadInfoById(pid, threadIds[i]))); } return threads; } /// <summary> /// Retrieves the number of open file descriptors for the specified pid /// </summary> /// <returns>A count of file descriptors for this process.</returns> /// <remarks> /// This function doesn't use the helper since it seems to allow passing NULL /// values in to the buffer and length parameters to get back an estimation /// of how much data we will need to allocate; the other flavors don't seem /// to support doing that. /// </remarks> internal static unsafe int GetFileDescriptorCountForPid(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } // Query for an estimation about the size of the buffer we will need. This seems // to add some padding from the real number, so we don't need to do that int result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, (proc_fdinfo*)null, 0); if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return 0; } proc_fdinfo[] fds; int size = (int)(result / Marshal.SizeOf<proc_fdinfo>()) + 1; // Just in case the app opened a ton of handles between when we asked and now, // make sure we retry if our buffer is filled do { fds = new proc_fdinfo[size]; fixed (proc_fdinfo* pFds = fds) { result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, pFds, Marshal.SizeOf<proc_fdinfo>() * fds.Length); } if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return 0; } else { checked { size *= 2; } } } while (result == (fds.Length * Marshal.SizeOf<proc_fdinfo>())); Debug.Assert((result % Marshal.SizeOf<proc_fdinfo>()) == 0); return (int)(result / Marshal.SizeOf<proc_fdinfo>()); } /// <summary> /// Gets the full path to the executable file identified by the specified PID /// </summary> /// <param name="pid">The PID of the running process</param> /// <param name="buffer">A pointer to an allocated block of memory that will be filled with the process path</param> /// <param name="bufferSize">The size of the buffer, should be PROC_PIDPATHINFO_MAXSIZE</param> /// <returns>Returns the length of the path returned on success</returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidpath( int pid, byte* buffer, uint bufferSize); /// <summary> /// Gets the full path to the executable file identified by the specified PID /// </summary> /// <param name="pid">The PID of the running process</param> /// <returns>Returns the full path to the process executable</returns> internal static unsafe string proc_pidpath(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid", SR.NegativePidNotSupported); } // The path is a fixed buffer size, so use that and trim it after int result = 0; byte* pBuffer = stackalloc byte[PROC_PIDPATHINFO_MAXSIZE]; result = proc_pidpath(pid, pBuffer, (uint)(PROC_PIDPATHINFO_MAXSIZE * Marshal.SizeOf<byte>())); if (result <= 0) { throw new Win32Exception(); } // OS X uses UTF-8. The conversion may not strip off all trailing \0s so remove them here return System.Text.Encoding.UTF8.GetString(pBuffer, result); } /// <summary> /// Gets the rusage information for the process identified by the PID /// </summary> /// <param name="pid">The process to retrieve the rusage for</param> /// <param name="flavor">Should be RUSAGE_SELF to specify getting the info for the specified process</param> /// <param name="rusage_info_t">A buffer to be filled with rusage_info data</param> /// <returns>Returns 0 on success; on fail, -1 and errno is set with the error code</returns> /// <remarks> /// We need to use IntPtr here for the buffer since the function signature uses /// void* and not a strong type even though it returns a rusage_info struct /// </remarks> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pid_rusage( int pid, int flavor, rusage_info_v3* rusage_info_t); /// <summary> /// Gets the rusage information for the process identified by the PID /// </summary> /// <param name="pid">The process to retrieve the rusage for</param> /// <returns>On success, returns a struct containing info about the process; on /// failure or when the caller doesn't have permissions to the process, throws a Win32Exception /// </returns> internal static unsafe rusage_info_v3 proc_pid_rusage(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid", SR.NegativePidNotSupported); } rusage_info_v3 info = new rusage_info_v3(); // Get the PIDs rusage info int result = proc_pid_rusage(pid, RUSAGE_SELF, &info); if (result <= 0) { throw new Win32Exception(SR.RUsageFailure); } Debug.Assert(result == Marshal.SizeOf<rusage_info_v3>()); return info; } } }
// ---------------------------------------------------------------------------- // <copyright company="EFC" file ="EventBroker.cs"> // All rights reserved Copyright 2015 Enterprise Foundation Classes // // </copyright> // <summary> // The <see cref="EventBroker.cs"/> file. // </summary> // --------------------------------------------------------------------------------------------- namespace EFC.Components.Events { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Threading; using EFC.Components.Exception; using EFC.Components.Validations; /// <summary> /// Component that acts as a mediator between publisher of the event and its subscriber. /// </summary> public class EventBroker : IEventBroker { #region Fields /// <summary> /// The dictionary of the event subjects. /// </summary> private readonly Dictionary<string, EventSubject> subjects = new Dictionary<string, EventSubject>(); /// <summary> /// The UI thread dispatcher. /// </summary> private readonly Dispatcher dispatcher; #endregion #region Properties /// <summary> /// Gets the registered subjects. /// </summary> /// <value>The registered subjects.</value> public IEnumerable<string> RegisteredSubjects { get { return this.subjects.Keys; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="EventBroker"/> class. /// </summary> /// <param name="dispatcher">The UI thread dispatcher.</param> public EventBroker(Dispatcher dispatcher) { Requires.NotNull(dispatcher, "dispatcher"); this.dispatcher = dispatcher; } /// <summary> /// Initializes a new instance of the <see cref="EventBroker"/> class. /// </summary> public EventBroker() { } #endregion #region Methods /// <summary> /// Registers the publisher. /// </summary> /// <param name="subject">The subject.</param> /// <param name="publisher">The publisher.</param> /// <param name="eventName">Name of the event.</param> public void RegisterPublisher(string subject, object publisher, string eventName) { lock (this.subjects) { EventSubject publishedEvent = this.GetEvent(subject); publishedEvent.AddPublication(new Publication(publishedEvent, publisher, eventName)); } } /// <summary> /// Unregisters the publisher. /// </summary> /// <param name="subject">The subject.</param> /// <param name="publisher">The publisher.</param> /// <param name="eventName">Name of the event.</param> public void UnregisterPublisher(string subject, object publisher, string eventName) { lock (this.subjects) { EventSubject publishedEvent = this.GetEvent(subject); List<Publication> publicationsToRemove = new List<Publication>( publishedEvent.Publications.Where(p => (p.EventName == eventName && p.Publisher == publisher))); foreach (Publication publication in publicationsToRemove) { publishedEvent.RemovePublication(publication); } this.RemoveEventSubjectIfEmpty(publishedEvent); } } /// <summary> /// Registers the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="subscriber">The subscriber.</param> /// <param name="handlerMethodName">Name of the handler method.</param> public void RegisterSubscriber(string subject, object subscriber, string handlerMethodName) { this.RegisterSubscriber(subject, subscriber, handlerMethodName, ThreadOption.Publisher); } /// <summary> /// Registers the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="subscriber">The subscriber.</param> /// <param name="handlerMethodName">Name of the handler method.</param> /// <param name="threadOption">The thread option.</param> public void RegisterSubscriber(string subject, object subscriber, string handlerMethodName, ThreadOption threadOption) { Requires.NotNull(subject, "subject"); Requires.NotNull(subscriber, "subscriber"); Requires.NotNullOrEmpty(handlerMethodName, "handlerMethodName"); this.VerifyThreadOption(threadOption); lock (this.subjects) { EventSubject publishedEvent = this.GetEvent(subject); publishedEvent.AddSubscription(new WeakSubscription(publishedEvent, subscriber, handlerMethodName, this.dispatcher, threadOption)); } } /// <summary> /// Registers the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> public void RegisterSubscriber(string subject, EventHandler handlerAction) { RegisterSubscriber(subject, handlerAction, ThreadOption.Publisher); } /// <summary> /// Registers the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> /// <param name="threadOption">The thread option.</param> public void RegisterSubscriber(string subject, EventHandler handlerAction, ThreadOption threadOption) { Requires.NotNull(subject, "subject"); Requires.NotNull(handlerAction, "handlerAction"); this.VerifyThreadOption(threadOption); this.AddSubscribtionFor(subject, handlerAction, threadOption); } /// <summary> /// Registers the subscriber. /// </summary> /// <typeparam name="T">Type of the event arguments.</typeparam> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> public void RegisterSubscriber<T>(string subject, EventHandler<T> handlerAction) where T : EventArgs { RegisterSubscriber(subject, handlerAction, ThreadOption.Publisher); } /// <summary> /// Registers the subscriber. /// </summary> /// <typeparam name="T">Type of the event arguments.</typeparam> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> /// <param name="threadOption">The thread option.</param> public void RegisterSubscriber<T>(string subject, EventHandler<T> handlerAction, ThreadOption threadOption) where T : EventArgs { Requires.NotNull(subject, "subject"); Requires.NotNull(handlerAction, "handlerAction"); this.VerifyThreadOption(threadOption); this.AddSubscribtionFor(subject, handlerAction, threadOption); } /// <summary> /// Unregisters the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> public void UnregisterSubscriber(string subject, EventHandler handlerAction) { this.UnregisterSubscriber(subject, (Delegate)handlerAction); } /// <summary> /// Unregisters the subscriber. /// </summary> /// <typeparam name="T">Type of event args.</typeparam> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> public void UnregisterSubscriber<T>(string subject, EventHandler<T> handlerAction) where T : EventArgs { this.UnregisterSubscriber(subject, (Delegate)handlerAction); } /// <summary> /// Unregisters the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="subscriber">The subscriber.</param> /// <param name="handlerMethodName">Name of the handler method.</param> public void UnregisterSubscriber(string subject, object subscriber, string handlerMethodName) { Requires.NotNull(subject, "subject"); Requires.NotNull(subscriber, "subscriber"); Requires.NotNullOrEmpty(handlerMethodName, "handlerMethodName"); this.RemoveSubscriptionFor(subject, s => s.Matches(subscriber, handlerMethodName)); } /// <summary> /// Unregisters the subscriber. /// </summary> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> private void UnregisterSubscriber(string subject, Delegate handlerAction) { Requires.NotNull(subject, "subject"); Requires.NotNull(handlerAction, "eventHandler"); if (handlerAction.Method.IsStatic) { this.RemoveSubscriptionFor(subject, s => s.Matches(handlerAction)); } else { this.RemoveSubscriptionFor(subject, s => s.Matches(handlerAction)); } } /// <summary> /// Gets the event. /// </summary> /// <param name="eventName">Name of the event.</param> /// <returns><see cref="EventSubject"/> for the specified event name.</returns> private EventSubject GetEvent(string eventName) { lock (this.subjects) { if (!this.subjects.ContainsKey(eventName)) { var subject = new EventSubject(eventName); this.subjects.Add(eventName, subject); return subject; } return this.subjects[eventName]; } } /// <summary> /// Registers the subscriber for. /// </summary> /// <param name="subject">The subject.</param> /// <param name="handlerAction">The handler action.</param> /// <param name="threadOption">The thread option.</param> private void AddSubscribtionFor(string subject, Delegate handlerAction, ThreadOption threadOption) { lock (this.subjects) { EventSubject publishedEvent = this.GetEvent(subject); SubscriptionBase subscription; if (handlerAction.Method.IsStatic) { subscription = new StaticSubscription(handlerAction, this.dispatcher, threadOption); } else { subscription = new WeakSubscription(publishedEvent, handlerAction, this.dispatcher, threadOption); } publishedEvent.AddSubscription(subscription); } } /// <summary> /// Unsubscribes for. /// </summary> /// <param name="subject">The subject.</param> /// <param name="predicate">The predicate.</param> private void RemoveSubscriptionFor(string subject, Func<SubscriptionBase, bool> predicate) { lock (this.subjects) { EventSubject publishedEvent = this.GetEvent(subject); SubscriptionBase subscriptionToRemove = publishedEvent.Subscriptions.LastOrDefault(predicate); if (subscriptionToRemove != null) { publishedEvent.RemoveSubscription(subscriptionToRemove); this.RemoveEventSubjectIfEmpty(publishedEvent); } } } /// <summary> /// Removes the event if empty. /// </summary> /// <param name="eventSubject">The event subject.</param> private void RemoveEventSubjectIfEmpty(EventSubject eventSubject) { if (!eventSubject.HasPublications && !eventSubject.HasSubscriptions) { this.subjects.Remove(eventSubject.Subject); } } /// <summary> /// Verifies the specified thread option. /// </summary> /// <param name="threadOption">The thread option to verify.</param> private void VerifyThreadOption(ThreadOption threadOption) { if (threadOption == ThreadOption.UserInterface && this.dispatcher == null) { throw ExceptionBuilder.ArgumentNotValid("threadOption", Messages.UserInterfaceNotSupported); } } #endregion } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Collections.Generic; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Security.Tokens; using System.Xml; using System.ServiceModel.Diagnostics; using System.Diagnostics; public class WSSecurityTokenSerializer : SecurityTokenSerializer { const int DefaultMaximumKeyDerivationOffset = 64; // bytes const int DefaultMaximumKeyDerivationLabelLength = 128; // bytes const int DefaultMaximumKeyDerivationNonceLength = 128; // bytes static WSSecurityTokenSerializer instance; readonly bool emitBspRequiredAttributes; readonly SecurityVersion securityVersion; readonly List<SerializerEntries> serializerEntries; WSSecureConversation secureConversation; readonly List<TokenEntry> tokenEntries; int maximumKeyDerivationOffset; int maximumKeyDerivationLabelLength; int maximumKeyDerivationNonceLength; KeyInfoSerializer keyInfoSerializer; public WSSecurityTokenSerializer() : this(SecurityVersion.WSSecurity11) { } public WSSecurityTokenSerializer(bool emitBspRequiredAttributes) : this(SecurityVersion.WSSecurity11, emitBspRequiredAttributes) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion) : this(securityVersion, false) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes) : this(securityVersion, emitBspRequiredAttributes, null) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer) : this(securityVersion, emitBspRequiredAttributes, samlSerializer, null, null) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes) : this(securityVersion, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, DefaultMaximumKeyDerivationOffset, DefaultMaximumKeyDerivationLabelLength, DefaultMaximumKeyDerivationNonceLength) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes) : this(securityVersion, trustVersion, secureConversationVersion, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, DefaultMaximumKeyDerivationOffset, DefaultMaximumKeyDerivationLabelLength, DefaultMaximumKeyDerivationNonceLength) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes, int maximumKeyDerivationOffset, int maximumKeyDerivationLabelLength, int maximumKeyDerivationNonceLength) : this(securityVersion, TrustVersion.Default, SecureConversationVersion.Default, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes, int maximumKeyDerivationOffset, int maximumKeyDerivationLabelLength, int maximumKeyDerivationNonceLength) { if (securityVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("securityVersion")); if (maximumKeyDerivationOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maximumKeyDerivationOffset", SR.GetString(SR.ValueMustBeNonNegative))); } if (maximumKeyDerivationLabelLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maximumKeyDerivationLabelLength", SR.GetString(SR.ValueMustBeNonNegative))); } if (maximumKeyDerivationNonceLength <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maximumKeyDerivationNonceLength", SR.GetString(SR.ValueMustBeGreaterThanZero))); } this.securityVersion = securityVersion; this.emitBspRequiredAttributes = emitBspRequiredAttributes; this.maximumKeyDerivationOffset = maximumKeyDerivationOffset; this.maximumKeyDerivationNonceLength = maximumKeyDerivationNonceLength; this.maximumKeyDerivationLabelLength = maximumKeyDerivationLabelLength; this.serializerEntries = new List<SerializerEntries>(); if (secureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005) { this.secureConversation = new WSSecureConversationFeb2005(this, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength); } else if (secureConversationVersion == SecureConversationVersion.WSSecureConversation13) { this.secureConversation = new WSSecureConversationDec2005(this, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } if (securityVersion == SecurityVersion.WSSecurity10) { this.serializerEntries.Add(new WSSecurityJan2004(this, samlSerializer)); } else if (securityVersion == SecurityVersion.WSSecurity11) { this.serializerEntries.Add(new WSSecurityXXX2005(this, samlSerializer)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("securityVersion", SR.GetString(SR.MessageSecurityVersionOutOfRange))); } this.serializerEntries.Add(this.secureConversation); IdentityModel.TrustDictionary trustDictionary; if (trustVersion == TrustVersion.WSTrustFeb2005) { this.serializerEntries.Add(new WSTrustFeb2005(this)); trustDictionary = new IdentityModel.TrustFeb2005Dictionary(new CollectionDictionary(DXD.TrustDec2005Dictionary.Feb2005DictionaryStrings)); } else if (trustVersion == TrustVersion.WSTrust13) { this.serializerEntries.Add(new WSTrustDec2005(this)); trustDictionary = new IdentityModel.TrustDec2005Dictionary(new CollectionDictionary(DXD.TrustDec2005Dictionary.Dec2005DictionaryString)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } this.tokenEntries = new List<TokenEntry>(); for (int i = 0; i < this.serializerEntries.Count; ++i) { SerializerEntries serializerEntry = this.serializerEntries[i]; serializerEntry.PopulateTokenEntries(this.tokenEntries); } IdentityModel.DictionaryManager dictionaryManager = new IdentityModel.DictionaryManager(ServiceModelDictionary.CurrentVersion); dictionaryManager.SecureConversationDec2005Dictionary = new IdentityModel.SecureConversationDec2005Dictionary(new CollectionDictionary(DXD.SecureConversationDec2005Dictionary.SecureConversationDictionaryStrings)); dictionaryManager.SecurityAlgorithmDec2005Dictionary = new IdentityModel.SecurityAlgorithmDec2005Dictionary(new CollectionDictionary(DXD.SecurityAlgorithmDec2005Dictionary.SecurityAlgorithmDictionaryStrings)); this.keyInfoSerializer = new WSKeyInfoSerializer(this.emitBspRequiredAttributes, dictionaryManager, trustDictionary, this, securityVersion, secureConversationVersion); } public static WSSecurityTokenSerializer DefaultInstance { get { if (instance == null) instance = new WSSecurityTokenSerializer(); return instance; } } public bool EmitBspRequiredAttributes { get { return this.emitBspRequiredAttributes; } } public SecurityVersion SecurityVersion { get { return this.securityVersion; } } public int MaximumKeyDerivationOffset { get { return this.maximumKeyDerivationOffset; } } public int MaximumKeyDerivationLabelLength { get { return this.maximumKeyDerivationLabelLength; } } public int MaximumKeyDerivationNonceLength { get { return this.maximumKeyDerivationNonceLength; } } internal WSSecureConversation SecureConversation { get { return this.secureConversation; } } bool ShouldWrapException(Exception e) { if (Fx.IsFatal(e)) { return false; } return ((e is ArgumentException) || (e is FormatException) || (e is InvalidOperationException)); } protected override bool CanReadTokenCore(XmlReader reader) { XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader); for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.CanReadTokenCore(localReader)) return true; } return false; } protected override SecurityToken ReadTokenCore(XmlReader reader, SecurityTokenResolver tokenResolver) { XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader); for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.CanReadTokenCore(localReader)) { try { return tokenEntry.ReadTokenCore(localReader, tokenResolver); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (!ShouldWrapException(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ErrorDeserializingTokenXml), e)); } } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CannotReadToken, reader.LocalName, reader.NamespaceURI, localReader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null)))); } protected override bool CanWriteTokenCore(SecurityToken token) { for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.SupportsCore(token.GetType())) return true; } return false; } protected override void WriteTokenCore(XmlWriter writer, SecurityToken token) { bool wroteToken = false; XmlDictionaryWriter localWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); if (token.GetType() == typeof(ProviderBackedSecurityToken)) { token = (token as ProviderBackedSecurityToken).Token; } for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.SupportsCore(token.GetType())) { try { tokenEntry.WriteTokenCore(localWriter, token); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (!ShouldWrapException(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ErrorSerializingSecurityToken), e)); } wroteToken = true; break; } } if (!wroteToken) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StandardsManagerCannotWriteObject, token.GetType()))); localWriter.Flush(); } protected override bool CanReadKeyIdentifierCore(XmlReader reader) { try { return this.keyInfoSerializer.CanReadKeyIdentifier(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader) { try { return this.keyInfoSerializer.ReadKeyIdentifier(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override bool CanWriteKeyIdentifierCore(SecurityKeyIdentifier keyIdentifier) { try { return this.keyInfoSerializer.CanWriteKeyIdentifier(keyIdentifier); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override void WriteKeyIdentifierCore(XmlWriter writer, SecurityKeyIdentifier keyIdentifier) { try { this.keyInfoSerializer.WriteKeyIdentifier(writer, keyIdentifier); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override bool CanReadKeyIdentifierClauseCore(XmlReader reader) { try { return this.keyInfoSerializer.CanReadKeyIdentifierClause(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlReader reader) { try { return this.keyInfoSerializer.ReadKeyIdentifierClause(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override bool CanWriteKeyIdentifierClauseCore(SecurityKeyIdentifierClause keyIdentifierClause) { try { return this.keyInfoSerializer.CanWriteKeyIdentifierClause(keyIdentifierClause); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override void WriteKeyIdentifierClauseCore(XmlWriter writer, SecurityKeyIdentifierClause keyIdentifierClause) { try { this.keyInfoSerializer.WriteKeyIdentifierClause(writer, keyIdentifierClause); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } internal Type[] GetTokenTypes(string tokenTypeUri) { if (tokenTypeUri != null) { for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.SupportsTokenTypeUri(tokenTypeUri)) { return tokenEntry.GetTokenTypes(); } } } return null; } protected internal virtual string GetTokenTypeUri(Type tokenType) { if (tokenType != null) { for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.SupportsCore(tokenType)) { return tokenEntry.TokenTypeUri; } } } return null; } public virtual bool TryCreateKeyIdentifierClauseFromTokenXml(XmlElement element, SecurityTokenReferenceStyle tokenReferenceStyle, out SecurityKeyIdentifierClause securityKeyIdentifierClause) { if (element == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element"); securityKeyIdentifierClause = null; try { securityKeyIdentifierClause = CreateKeyIdentifierClauseFromTokenXml(element, tokenReferenceStyle); } catch (XmlException e) { if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.Security, SR.GetString(SR.TraceCodeSecurity), null, e); } return false; } return true; } public virtual SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXml(XmlElement element, SecurityTokenReferenceStyle tokenReferenceStyle) { if (element == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element"); for (int i = 0; i < this.tokenEntries.Count; i++) { TokenEntry tokenEntry = this.tokenEntries[i]; if (tokenEntry.CanReadTokenCore(element)) { try { return tokenEntry.CreateKeyIdentifierClauseFromTokenXmlCore(element, tokenReferenceStyle); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (!ShouldWrapException(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ErrorDeserializingKeyIdentifierClauseFromTokenXml), e)); } } } // PreSharp Bug: Parameter 'element' to this public method must be validated: A null-dereference can occur here. #pragma warning suppress 56506 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CannotReadToken, element.LocalName, element.NamespaceURI, element.GetAttribute(SecurityJan2004Strings.ValueType, null)))); } internal abstract new class TokenEntry { Type[] tokenTypes = null; public virtual IAsyncResult BeginReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver, AsyncCallback callback, object state) { SecurityToken result = this.ReadTokenCore(reader, tokenResolver); return new CompletedAsyncResult<SecurityToken>(result, callback, state); } protected abstract XmlDictionaryString LocalName { get; } protected abstract XmlDictionaryString NamespaceUri { get; } public Type TokenType { get { return GetTokenTypes()[0]; } } public abstract string TokenTypeUri { get; } protected abstract string ValueTypeUri { get; } protected abstract Type[] GetTokenTypesCore(); public Type[] GetTokenTypes() { if (this.tokenTypes == null) this.tokenTypes = GetTokenTypesCore(); return this.tokenTypes; } public bool SupportsCore(Type tokenType) { Type[] tokenTypes = GetTokenTypes(); for (int i = 0; i < tokenTypes.Length; ++i) { if (tokenTypes[i].IsAssignableFrom(tokenType)) return true; } return false; } public virtual bool SupportsTokenTypeUri(string tokenTypeUri) { return (this.TokenTypeUri == tokenTypeUri); } protected static SecurityKeyIdentifierClause CreateDirectReference(XmlElement issuedTokenXml, string idAttributeLocalName, string idAttributeNamespace, Type tokenType) { string id = issuedTokenXml.GetAttribute(idAttributeLocalName, idAttributeNamespace); if (id == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, idAttributeLocalName, issuedTokenXml.LocalName))); } return new LocalIdKeyIdentifierClause(id, tokenType); } public virtual bool CanReadTokenCore(XmlElement element) { string valueTypeUri = null; if (element.HasAttribute(SecurityJan2004Strings.ValueType, null)) { valueTypeUri = element.GetAttribute(SecurityJan2004Strings.ValueType, null); } return element.LocalName == LocalName.Value && element.NamespaceURI == NamespaceUri.Value && valueTypeUri == this.ValueTypeUri; } public virtual bool CanReadTokenCore(XmlDictionaryReader reader) { return reader.IsStartElement(this.LocalName, this.NamespaceUri) && reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null) == this.ValueTypeUri; } public virtual SecurityToken EndReadTokenCore(IAsyncResult result) { return CompletedAsyncResult<SecurityToken>.End(result); } public abstract SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml, SecurityTokenReferenceStyle tokenReferenceStyle); public abstract SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver); public abstract void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token); } internal abstract new class SerializerEntries { public virtual void PopulateTokenEntries(IList<TokenEntry> tokenEntries) { } } internal class CollectionDictionary : IXmlDictionary { List<XmlDictionaryString> dictionaryStrings; public CollectionDictionary(List<XmlDictionaryString> dictionaryStrings) { if (dictionaryStrings == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("dictionaryStrings")); this.dictionaryStrings = dictionaryStrings; } public bool TryLookup(string value, out XmlDictionaryString result) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); for (int i = 0; i < this.dictionaryStrings.Count; ++i) { if (this.dictionaryStrings[i].Value.Equals(value)) { result = this.dictionaryStrings[i]; return true; } } result = null; return false; } public bool TryLookup(int key, out XmlDictionaryString result) { for (int i = 0; i < this.dictionaryStrings.Count; ++i) { if (this.dictionaryStrings[i].Key == key) { result = this.dictionaryStrings[i]; return true; } } result = null; return false; } public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); for (int i = 0; i < this.dictionaryStrings.Count; ++i) { if ((this.dictionaryStrings[i].Key == value.Key) && (this.dictionaryStrings[i].Value.Equals(value.Value))) { result = this.dictionaryStrings[i]; return true; } } result = null; return false; } } } }
using Desharp.Core; using Desharp.Renderers; using System; using System.Linq; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Routing; using System.Collections; using Desharp.Panels.Routings; using System.Threading; using System.Runtime.InteropServices; namespace Desharp.Panels { [ComVisible(true)] public class Routing: IPanel, ISessionPanel { public static string PanelName = "routing"; public int[] DefaultWindowSizes => new int[] { 350, 250 }; public string IconValue => Routing.PanelName; public string Name => Routing.PanelName; public PanelIconType PanelIconType => PanelIconType.Class; public bool AddIfEmpty => false; public PanelType PanelType => PanelType.BarBtnAndWindow; public void SessionBegin () { this._completeData(); } public void SessionEnd () {} public string[] RenderBarTitle() { this._completeData(); return new string[] { this._barText }; } public string RenderWindowContent() { this._completeData(); return this._panelContent; } private static string _defaultControllersNamespace; private static ReaderWriterLockSlim _routeTargetsLock = new ReaderWriterLockSlim(); private static volatile List<RouteTarget> _routeTargets = null; private bool _dataCompleted = false; private string _barText = String.Empty; private string _panelContent = String.Empty; private string _allRoutesTable; private string _dataTokensTable; private MatchedCompleter _matchedCompleter = new MatchedCompleter(); private static void _completeRouteTargetsAndDefaultNamespace () { Routing._defaultControllersNamespace = String.Format("{0}.Controllers", Tools.GetWebEntryAssembly().GetName().Name); Routing._routeTargets = new List<RouteTarget>(); Assembly entryAssembly = Tools.GetWebEntryAssembly(); Type systemWebMvcCtrlType = Tools.GetTypeGlobaly("System.Web.Mvc.Controller"); Type systemWebMvcNonActionAttrType = Tools.GetTypeGlobaly("System.Web.Mvc.NonActionAttribute"); if (systemWebMvcCtrlType is Type && systemWebMvcNonActionAttrType is Type) { try { IEnumerable<MethodInfo> controllersActions = entryAssembly.GetTypes() .Where(type => systemWebMvcCtrlType.IsAssignableFrom(type)) //filter controllers .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public)) .Where(method => method.IsPublic && !method.IsDefined(systemWebMvcNonActionAttrType, false)); foreach (MethodBase controllerAction in controllersActions) { ParameterInfo[] args = controllerAction.GetParameters(); Dictionary<string, RouteTargetArg> targetArgs = new Dictionary<string, RouteTargetArg>(); Type targetArgType; Type[] genericTypes; string targetArgTypeName; bool nullable; for (int i = 0, l = args.Length; i < l; i += 1) { targetArgType = args[i].ParameterType; if (targetArgType.Name.IndexOf("Nullable`") == 0) { nullable = true; targetArgTypeName = "Nullable&lt;"; genericTypes = targetArgType.GetGenericArguments(); for (int j = 0, k = genericTypes.Length; j < k; j += 1) { targetArgTypeName += (j > 0 ? ",&nbsp;" : "") + genericTypes[i].Name; } targetArgTypeName += "&gt;"; } else { nullable = false; targetArgTypeName = targetArgType.Name; } targetArgs.Add( args[i].Name, new RouteTargetArg { Type = targetArgType, DefaultValue = args[i].DefaultValue, IsNullable = nullable, HtmlName = targetArgTypeName } ); } Routing._routeTargets.Add(new RouteTarget { Namespace = controllerAction.DeclaringType.Namespace, NamespaceLower = controllerAction.DeclaringType.Namespace.ToLower(), Controller = controllerAction.DeclaringType.Name, Action = controllerAction.Name, FullName = controllerAction.DeclaringType.Namespace + "." + controllerAction.DeclaringType.Name + ":" + controllerAction.Name, Params = targetArgs }); } } catch {} } } private void _completeData () { if (this._dataCompleted) return; Routing._routeTargetsLock.EnterUpgradeableReadLock(); if (Routing._routeTargets == null) { Routing._routeTargetsLock.EnterWriteLock(); Routing._routeTargetsLock.ExitUpgradeableReadLock(); Routing._completeRouteTargetsAndDefaultNamespace(); Routing._routeTargetsLock.ExitWriteLock(); } else { Routing._routeTargetsLock.ExitUpgradeableReadLock(); } try { this._completeRoutes(); this._completeBarText(); this._completeMatchedDataTokens(); this._panelContent = @"<div class=""content" + (this._matchedCompleter.Target is RouteTarget ? "" : " nomatch") + @""">" + this._allRoutesTable + Routing._getCurrentRelExecPath() + this._dataTokensTable + "</div>"; } catch (Exception e) { Debug.Log(e); } this._dataCompleted = true; } private void _completeRoutes () { HttpContextBase httpContext = HttpContext.Current.Request.RequestContext.HttpContext; bool routeMatched; int routeMatchLevel; bool matchedRouteFound = false; StringBuilder allRouteTableRows = new StringBuilder(); Route route; RouteTarget routeTarget; foreach (RouteBase routeBase in RouteTable.Routes) { routeMatched = routeBase.GetRouteData(httpContext) != null; route = Routing._safeCastRouteBaseToRoute(routeBase); routeTarget = this._completeRouteTarget(ref route, route.Defaults); routeMatchLevel = routeMatched ? (!matchedRouteFound ? 2 : 1) : 0; if (routeMatchLevel == 2) { this._matchedCompleter.Route = route; this._matchedCompleter.Target = routeTarget; matchedRouteFound = true; } allRouteTableRows.Append(this._completeRoute( ref route, ref routeTarget, routeMatchLevel )); } this._allRoutesTable = @"<b class=""heading"">All Routes:</b><table class=""routes"">" + @"<thead><tr class=""header""><th></th><th>Pattern</th><th>Defaults</th><th>Matched as</th></tr></thead>" + @"<tbody>" + allRouteTableRows.ToString() + "</tbody></table>"; } private RouteTarget _completeRouteTarget (ref Route route, RouteValueDictionary dictionaryContainingCtrlAndAction) { RouteTarget result = new RouteTarget { Controller = "", Action = "", FullName = "", Namespaces = new string[] {}, NamespacesLower = new string[] {}, Namespace = Routing._defaultControllersNamespace, Params = new Dictionary<string, RouteTargetArg>() }; bool ctrlDefined = false; bool actionDefined = false; int ctrlNameDocPos; string namespacePartInsideControllerName; if (!(route.RouteHandler is StopRoutingHandler)) { if (route.DataTokens.ContainsKey("Namespaces")) { try { result.Namespaces = route.DataTokens["Namespaces"] as string[]; } catch { } if (result.Namespaces == null) result.Namespaces = new string[] { }; } if (dictionaryContainingCtrlAndAction.ContainsKey("controller")) { if (dictionaryContainingCtrlAndAction["controller"].GetType().Name == "UrlParameter") { result.Controller = "*"; } else { result.Controller = dictionaryContainingCtrlAndAction["controller"].ToString(); ctrlNameDocPos = result.Controller.LastIndexOf("."); if (ctrlNameDocPos > -1) { namespacePartInsideControllerName = result.Controller.Substring(0, ctrlNameDocPos); result.Controller = result.Controller.Substring(ctrlNameDocPos + 1); if (result.Namespaces.Length > 0) { for (int i = 0, l = result.Namespaces.Length; i < l; i += 1) { result.Namespaces[i] += "." + result.Controller.Substring(0, ctrlNameDocPos); } } else { result.Namespaces = new[] { Routing._defaultControllersNamespace + "." + namespacePartInsideControllerName }; } } ctrlDefined = true; } } List<string> lowerNamespaces = new List<string>(); for (int i = 0, l = result.Namespaces.Length; i < l; i += 1) { lowerNamespaces.Add(result.Namespaces[i].ToLower()); } result.NamespacesLower = lowerNamespaces.ToArray(); if (dictionaryContainingCtrlAndAction.ContainsKey("action")) { if (dictionaryContainingCtrlAndAction["action"].GetType().Name == "UrlParameter") { result.Action = "*"; } else { result.Action = dictionaryContainingCtrlAndAction["action"].ToString(); actionDefined = true; } } result.FullName = result.Controller + ":" + result.Action; if (ctrlDefined && actionDefined) { this._completeRouteTargetCompleteActionParams(ref result); } else { result.FullName += "()"; } if (result.FullName.IndexOf(Routing._defaultControllersNamespace) == 0) { result.FullName = result.FullName.Substring(Routing._defaultControllersNamespace.Length + 1); } result.FullName = result.FullName.Replace("*", @"<span class=""type"">[Optional]</span>"); } return result; } private void _completeRouteTargetCompleteActionParams (ref RouteTarget routeTarget) { RouteTarget routeTargetLocal = null; bool searchForCtrl = routeTarget.Controller != "*"; bool searchForAction = routeTarget.Action != "*"; bool searchForNamespace = routeTarget.Namespaces.Length > 0; string searchedCtrl = routeTarget.Controller + "Controller"; Routing._routeTargetsLock.EnterReadLock(); foreach (RouteTarget item in Routing._routeTargets) { if (searchForCtrl && item.Controller != searchedCtrl) continue; if (searchForAction && item.Action != routeTarget.Action) continue; if (searchForNamespace) { if (routeTarget.NamespacesLower.Contains(item.NamespaceLower)) { routeTargetLocal = item; break; } } else { routeTargetLocal = item; break; } } Routing._routeTargetsLock.ExitReadLock(); if (routeTargetLocal is RouteTarget) { List<string> targetParams = new List<string>(); Type targetParamType; foreach (var targetParamItem in routeTargetLocal.Params) { targetParamType = targetParamItem.Value.Type; targetParams.Add(targetParamItem.Value.HtmlName + " " + targetParamItem.Key); } routeTarget.FullName += "(" + String.Join(", ", targetParams) + ")"; routeTarget.Namespace = routeTargetLocal.Namespace; if (routeTarget.Namespace != Routing._defaultControllersNamespace) { routeTarget.FullName = routeTarget.Namespace + "." + routeTarget.FullName; } routeTarget.Params = routeTargetLocal.Params; } else { routeTarget.FullName += "()"; } } private string _completeRoute (ref Route route, ref RouteTarget routeTarget, int matched) { string[] rowCssClassAndFirstColumn = Routing._completeRouteCssClassAndFirstColumn(ref route, matched); string secondColumn = Routing._completeRouteSecondColumn(route); string configuredRouteName = Routing._completeRouteConfiguredRouteName(routeTarget); string routeParams = this._completeRouteParamsValuesConstraints(route); string routeMatches = String.Empty; string matchedRouteName = String.Empty; if (matched == 2) { routeMatches = this._matchedCompleter.Render(); matchedRouteName = configuredRouteName; } return String.Format( @"<tr{0}><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", rowCssClassAndFirstColumn[0], rowCssClassAndFirstColumn[1], secondColumn, configuredRouteName + routeParams, matchedRouteName + routeMatches ); } private string _completeRouteParamsValuesConstraints (Route route) { string result = ""; if (!(route.RouteHandler is StopRoutingHandler)) { result = @"<div class=""params"">"; RouteValueDictionary routeDefaults = route.Defaults; RouteValueDictionary routeConstraints = route.Constraints; if (routeConstraints == null) routeConstraints = new RouteValueDictionary(); foreach (var item in routeDefaults) { if (item.Key == "controller" || item.Key == "action") continue; result += @"<div class=""desharp-dump""><span class=""routeparam"">" + item.Key + "</span><s>:&nbsp;</s>" + Routing._renderUrlParamValue(item.Value); if (routeConstraints.ContainsKey(item.Key)) { if (routeConstraints[item.Key] != null) { if (routeConstraints[item.Key] is string) { result += @"&nbsp;<span class=""string"">""" + routeConstraints[item.Key].ToString() + @"""</span>"; } else { result += @"&nbsp;<span class=""type"">" + routeConstraints[item.Key].ToString() + @"</span>"; } } } result += "</div>"; } result += "</div>"; } return result; } private void _completeBarText () { if (this._matchedCompleter.Target is RouteTarget) { int firstBracketPos = this._matchedCompleter.Target.FullName.IndexOf("("); this._barText = this._matchedCompleter.Target.FullName.Substring(0, firstBracketPos) + " (" + RouteTable.Routes.Count + ")"; } else { this._barText = "No matched route"; } } private void _completeMatchedDataTokens () { string dataTokensTableRows = ""; RouteData routeData = HttpContext.Current.Request.RequestContext.RouteData; Route route = Routing._safeCastRouteBaseToRoute(routeData.Route); if (route == null || route.RouteHandler is StopRoutingHandler) return; if (routeData.DataTokens.Keys.Count > 0) { foreach (string key in routeData.DataTokens.Keys) { dataTokensTableRows += "<tr><td>" + key + "</td><td>" + Dumper.Dump( routeData.DataTokens[key], true, Dispatcher.DumpDepth, Dispatcher.DumpMaxLength ) + "</td></tr>"; } this._dataTokensTable = @"<b class=""heading"">Matched route data tokens:</b><table>" + "<thead><tr><th>Key</th><th>Value</th></tr></thead><tbody>" + dataTokensTableRows + @"</tbody></table>"; } else { this._dataTokensTable = "<p>Matched route has no data tokens.</p>"; } } private static Route _safeCastRouteBaseToRoute (RouteBase routeBase) { Route route = routeBase as Route; if (route == null && routeBase != null) { PropertyInfo property = routeBase.GetType().GetProperty("__DebugRoute", BindingFlags.NonPublic | BindingFlags.Instance); if (property != null) { route = property.GetValue(routeBase, null) as Route; } } return route; } private static string _renderUrlParamValue (object obj) { if (obj == null) { return Dumper.NullCode[0]; } else if (obj.GetType().Name == "UrlParameter") { return @"<span class=""type"">[Optional]</span>"; } else { Type objType = obj.GetType(); Type underlyingType = null; return Dumper.DumpPrimitiveType(ref obj, ref objType, ref underlyingType, 0, true, Dispatcher.DumpMaxLength, ""); } } private static string[] _completeRouteCssClassAndFirstColumn (ref Route route, int matched) { string rowCssClass = String.Empty; string firstColumn = String.Empty; if (matched == 2) { rowCssClass = @" class=""matched"""; firstColumn = "&#10003;"; } else if (matched == 1) { firstColumn = "&#8776;"; } else if (route.RouteHandler is StopRoutingHandler) { rowCssClass = @" class=""ignore"""; firstColumn = "&#215;"; } return new[] { rowCssClass, firstColumn }; } private static string _completeRouteSecondColumn (Route route) { string result = "~/" + route.Url; Regex r = new Regex(@"\{([a-zA-Z0-9_\*]*)\}"); return @"<div class=""pattern"">""" + r.Replace(result, @"<b>{$1}</b>") + @"""</div>"; } private static string _completeRouteConfiguredRouteName (RouteTarget routeTarget) { return routeTarget.FullName.IndexOf(":") > -1 ? @"<div class=""target"">" + routeTarget.FullName + "</div>" : routeTarget.FullName; } private static string _getCurrentRelExecPath () { HttpRequest request = HttpContext.Current.Request; Uri url = request.Url; string requestedPath = request.AppRelativeCurrentExecutionFilePath.TrimStart('~'); string requestedAndBasePath = url.LocalPath; int lastRequestPathPos = requestedAndBasePath.LastIndexOf(requestedPath); string basePath = ""; if (lastRequestPathPos > -1) basePath = requestedAndBasePath.Substring(0, lastRequestPathPos); return @"<p class=""source-url"">" + request.HttpMethod.ToUpper() + "&nbsp;" + url.Scheme + "://" + url.Host + (url.Port != 80 ? ":" + url.Port.ToString() : "") + basePath + "<span>" + requestedPath + url.Query + "</span></p>"; } } }
using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion Deflater Documentation #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion Public Constants #region Public Enum /// <summary> /// Compression Level as an enum for safer use /// </summary> public enum CompressionLevel { /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> BEST_COMPRESSION = Deflater.BEST_COMPRESSION, /// <summary> /// The worst but fastest compression level. /// </summary> BEST_SPEED = Deflater.BEST_SPEED, /// <summary> /// The default compression level. /// </summary> DEFAULT_COMPRESSION = Deflater.DEFAULT_COMPRESSION, /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> NO_COMPRESSION = Deflater.NO_COMPRESSION, /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> DEFLATED = Deflater.DEFLATED } #endregion Public Enum #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion Local Constants #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) : this(level, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noZlibHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException(nameof(level)); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending, noZlibHeaderOrFooter); this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } #endregion Constructors /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public long TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE) && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } engine.SetInput(input, offset, count); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException(nameof(level)); } if (this.level != level) { this.level = level; engine.SetLevel(level); } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// SetLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// IsNeedingInput() or IsFinished returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If Finish() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { // output header int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { // Dictionary was set header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (; ; ) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { switch (state) { case BUSY_STATE: // We need more input now return origLength - length; case FLUSHING_STATE: if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; break; case FINISHING_STATE: pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noZlibHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; break; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dictionary, index, count); } #region Instance Fields /// <summary> /// Compression level. /// </summary> private int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> private bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> private int state; /// <summary> /// The total bytes of output written. /// </summary> private long totalOut; /// <summary> /// The pending output. /// </summary> private DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> private DeflaterEngine engine; #endregion Instance Fields } }
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace SourceCode.Clay.Threading.Tests { public static class AsyncLockTests { [Fact(Timeout = 1000)] public static void AsyncLock_Acquire_Once() { using (var l = new AsyncLock()) using (AsyncLockCookie t = l.Acquire()) { Assert.True(t.IsAcquired); Assert.Equal(t.IsAcquired, t); } } [Fact(Timeout = 1000)] public static void AsyncLock_Acquire_Twice() { using (var l = new AsyncLock()) { using (AsyncLockCookie t = l.Acquire()) { Assert.True(t.IsAcquired); Assert.Equal(t.IsAcquired, t); } using (AsyncLockCookie t = l.Acquire()) { Assert.True(t.IsAcquired); } } } [Fact(Timeout = 1000)] public static void AsyncLock_Acquire_Fail() { using (var l = new AsyncLock()) { using (AsyncLockCookie t1 = l.Acquire()) { Assert.True(t1.IsAcquired); using (AsyncLockCookie t2 = l.Acquire(0)) { Assert.False(t2.IsAcquired); Assert.Equal(t2.IsAcquired, t2); } using (AsyncLockCookie t2 = l.Acquire(TimeSpan.Zero)) { Assert.False(t2.IsAcquired); Assert.Equal(t2.IsAcquired, t2); } } } } [Fact(Timeout = 1000)] public static void AsyncLock_Acquire_Wait() { using (var l = new AsyncLock()) { AsyncLockCookie t1 = l.Acquire(); Assert.True(t1.IsAcquired); var sw = Stopwatch.StartNew(); ThreadPool.QueueUserWorkItem(_ => { Thread.Sleep(500); t1.Dispose(); }); using (AsyncLockCookie t2 = l.Acquire()) { Assert.True(t2); } Assert.True(sw.Elapsed.TotalMilliseconds >= 400); } } [Fact(Timeout = 1000)] public static void AsyncLock_Acquire_Timeout() { using (var l = new AsyncLock()) { var sw = Stopwatch.StartNew(); using (AsyncLockCookie t1 = l.Acquire()) using (AsyncLockCookie t2 = l.Acquire(100)) { Assert.True(t1.IsAcquired); Assert.False(t2.IsAcquired); Assert.True(sw.Elapsed.TotalMilliseconds >= 80); } } } [Fact(Timeout = 1000)] public static void AsyncLock_Acquire_Timeout_Timespan() { using (var l = new AsyncLock()) { var sw = Stopwatch.StartNew(); using (AsyncLockCookie t1 = l.Acquire()) using (AsyncLockCookie t2 = l.Acquire(TimeSpan.FromMilliseconds(100))) { Assert.True(t1.IsAcquired); Assert.False(t2.IsAcquired); Assert.True(sw.Elapsed.TotalMilliseconds >= 80); } } } [Fact(Timeout = 1000)] public static async Task AsyncLock_AcquireAsync_Once() { using (var l = new AsyncLock()) using (AsyncLockCookie t = await l.AcquireAsync()) { Assert.True(t.IsAcquired); Assert.Equal(t.IsAcquired, t); } } [Fact(Timeout = 1000)] public static async Task AsyncLock_AcquireAsync_Twice() { using (var l = new AsyncLock()) { using (AsyncLockCookie t = await l.AcquireAsync()) { Assert.True(t.IsAcquired); Assert.Equal(t.IsAcquired, t); } using (AsyncLockCookie t = await l.AcquireAsync()) { Assert.True(t.IsAcquired); } } } [Fact(Timeout = 1000)] public static async Task AsyncLock_AcquireAsync_Fail() { using (var l = new AsyncLock()) { using (AsyncLockCookie t1 = await l.AcquireAsync()) { Assert.True(t1.IsAcquired); using (AsyncLockCookie t2 = await l.AcquireAsync(0)) { Assert.False(t2.IsAcquired); Assert.Equal(t2.IsAcquired, t2); } using (AsyncLockCookie t2 = await l.AcquireAsync(TimeSpan.Zero)) { Assert.False(t2.IsAcquired); Assert.Equal(t2.IsAcquired, t2); } } } } [Fact(Timeout = 1000)] public static async Task AsyncLock_AcquireAsync_Wait() { using (var l = new AsyncLock()) { AsyncLockCookie t1 = await l.AcquireAsync(); Assert.True(t1.IsAcquired); var sw = Stopwatch.StartNew(); ThreadPool.QueueUserWorkItem(_ => { Thread.Sleep(500); t1.Dispose(); }); using (AsyncLockCookie t2 = await l.AcquireAsync()) { Assert.True(t2); } Assert.True(sw.Elapsed.TotalMilliseconds >= 400); } } [Fact(Timeout = 1000)] public static async Task AsyncLock_AcquireAsync_Timeout() { using (var l = new AsyncLock()) { var sw = Stopwatch.StartNew(); using (AsyncLockCookie t1 = await l.AcquireAsync()) using (AsyncLockCookie t2 = await l.AcquireAsync(100)) { Assert.True(t1.IsAcquired); Assert.False(t2.IsAcquired); Assert.True(sw.Elapsed.TotalMilliseconds >= 80); } } } [Fact(Timeout = 1000)] public static async Task AsyncLock_AcquireAsync_Timeout_Timespan() { using (var l = new AsyncLock()) { var sw = Stopwatch.StartNew(); using (AsyncLockCookie t1 = await l.AcquireAsync()) using (AsyncLockCookie t2 = await l.AcquireAsync(TimeSpan.FromMilliseconds(100))) { Assert.True(t1.IsAcquired); Assert.False(t2.IsAcquired); Assert.True(sw.Elapsed.TotalMilliseconds >= 80); } } } } }
/* * RichTextBox.cs - Implementation of the * "System.Windows.Forms.RichTextBox" class. * * Copyright (C) 2003 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 */ namespace System.Windows.Forms { #if !CONFIG_COMPACT_FORMS using System; using System.ComponentModel; using System.IO; using System.Drawing; public class RichTextBox: TextBoxBase { private bool autoWordSelection; private int bulletIndent; private bool detectUrls; private int rightMargin; private RichTextBoxScrollBars scrollBars; private float zoomFactor; public event ContentsResizedEventHandler ContentsResized; public event EventHandler HScroll; public event EventHandler ImeChange; public event LinkClickedEventHandler LinkClicked; public event EventHandler Protected; public event EventHandler SelectionChanged; public event EventHandler VScroll; [TODO] public override bool AllowDrop { get { return base.AllowDrop; } set { base.AllowDrop = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public bool AutoWordSelection { get { return autoWordSelection; } set { autoWordSelection = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(0)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public int BulletIndent { get { return bulletIndent; } set { bulletIndent = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public bool CanRedo { get { return false; } } [TODO] public bool CanPaste(DataFormats.Format clipFormat) { throw new NotImplementedException("CanPaste"); } [TODO] internal override void CaretSetPosition(int position) { } [TODO] protected override void DeleteTextOp(CaretDirection dir) { } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(true)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public bool DetectUrls { get { return detectUrls; } set { detectUrls = value; } } [TODO] public int Find(char[] characterSet) { throw new NotImplementedException("Find"); } [TODO] public int Find(char[] characterSet, int start) { throw new NotImplementedException("Find"); } [TODO] public int Find(char[] characterSet, int start, int end) { throw new NotImplementedException("Find"); } [TODO] public int Find(String str) { throw new NotImplementedException("Find"); } [TODO] public int Find(String str, RichTextBoxFinds options) { throw new NotImplementedException("Find"); } [TODO] public int Find(String str, int start, RichTextBoxFinds options) { throw new NotImplementedException("Find"); } [TODO] public int Find(String str, int start, int end, RichTextBoxFinds options) { throw new NotImplementedException("Find"); } [TODO] public char GetCharFromPosition(Point pt) { throw new NotImplementedException("GetCharFromPosition"); } [TODO] public int GetCharIndexFromPosition(Point pt) { throw new NotImplementedException("GetCharIndexFromPosition"); } [TODO] public int GetLineFromCharIndex(int index) { throw new NotImplementedException("GetLineFromCharIndex"); } [TODO] public Point GetPositionFromCharIndex(int index) { throw new NotImplementedException("GetPositionFromCharIndex"); } [TODO] internal override int GetSelectionLength() { return 0; } [TODO] internal override int GetSelectionStart() { return 0; } [TODO] public override String[] Lines { get { return new String[0]; } set { } } [TODO] public void LoadFile(Stream data, RichTextBoxStreamType fileType) { throw new NotImplementedException("LoadFile"); } [TODO] public void LoadFile(String path) { throw new NotImplementedException("LoadFile"); } [TODO] public void LoadFile(String path, RichTextBoxStreamType fileType) { throw new NotImplementedException("LoadFile"); } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(2147483647)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public override int MaxLength { get { return base.MaxLength; } set { base.MaxLength = value; } } [TODO] protected override void MoveCaret(CaretDirection dir, bool extend) { } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(true)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public override bool Multiline { get { return base.Multiline; } set { base.Multiline = value; } } [TODO] protected override void OnBackColorChanged(EventArgs e) { base.OnBackColorChanged(e); } [TODO] protected virtual void OnContentsResized(ContentsResizedEventArgs e) { if (ContentsResized != null) { ContentsResized(this, e); } } [TODO] protected override void OnContextMenuChanged(EventArgs e) { base.OnContextMenuChanged(e); } [TODO] protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); } [TODO] protected override void OnHandleDestroyed(EventArgs e) { base.OnHandleDestroyed(e); } [TODO] protected virtual void OnHScroll(EventArgs e) { if (HScroll != null) { HScroll(this, e); } } [TODO] protected virtual void OnImeChange(EventArgs e) { if (ImeChange != null) { ImeChange(this, e); } } [TODO] protected virtual void OnLinkClicked(LinkClickedEventArgs e) { if (LinkClicked != null) { LinkClicked(this, e); } } [TODO] protected virtual void OnProtected(EventArgs e) { if (Protected != null) { Protected(this, e); } } [TODO] protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); } [TODO] protected virtual void OnSelectionChanged(EventArgs e) { if (SelectionChanged != null) { SelectionChanged(this, e); } } [TODO] protected override void OnSystemColorsChanged(EventArgs e) { base.OnSystemColorsChanged(e); } [TODO] protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); } [TODO] internal override void OnToggleInsertMode() { } [TODO] protected virtual void OnVScroll(EventArgs e) { if (VScroll != null) { VScroll(this, e); } } [TODO] public void Paste(DataFormats.Format clipFormat) { throw new NotImplementedException("Paste"); } [TODO] public void Redo() { throw new NotImplementedException("Redo"); } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public String RedoActionName { get { return String.Empty; } } [TODO] public RichTextBox() : base() { autoWordSelection = false; bulletIndent = 0; detectUrls = true; rightMargin = 0; scrollBars = RichTextBoxScrollBars.Both; zoomFactor = 1; base.MaxLength = 2147483647; base.Multiline = true; } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(0)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public int RightMargin { get { return rightMargin; } set { rightMargin = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(0)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public String Rtf { get { return String.Empty; } set { } } [TODO] public void SaveFile(Stream data, RichTextBoxStreamType fileType) { throw new NotImplementedException("SaveFile"); } [TODO] public void SaveFile(String path) { throw new NotImplementedException("SaveFile"); } [TODO] public void SaveFile(String path, RichTextBoxStreamType fileType) { throw new NotImplementedException("SaveFile"); } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(RichTextBoxScrollBars.Both)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public RichTextBoxScrollBars ScrollBars { get { return scrollBars; } set { scrollBars = value; } } [TODO] protected override void ScrollToCaretInternal() { } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue("")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public String SelectedRtf { get { return String.Empty; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue("")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public override String SelectedText { get { return base.SelectedText; } set { base.SelectedText = value; } } [TODO] internal override void SelectInternal(int start, int length) { } #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(HorizontalAlignment.Left)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [TODO] public HorizontalAlignment SelectionAlignment { get { return HorizontalAlignment.Left; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public bool SelectionBullet { get { return false; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public int SelectionCharOffset { get { return 0; } set { if (value < -2000 || value > 2000) { throw new ArgumentException("value"); } } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public Color SelectionColor { get { return Color.Black; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public Font SelectionFont { get { return base.Font; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(0)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public int SelectionHangingIndent { get { return 0; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(0)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public int SelectionIndent { get { return 0; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public override int SelectionLength { get { return base.SelectionLength; } set { base.SelectionLength = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public bool SelectionProtected { get { return false; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(0)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public int SelectionRightIndent { get { return 0; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public int[] SelectionTabs { get { return new int[0]; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public RichTextBoxSelectionTypes SelectionType { get { return RichTextBoxSelectionTypes.Empty; } } [TODO] protected override void SetBorderStyle(BorderStyle borderStyle) { BorderStyleInternal = borderStyle; } [TODO] internal override void SetSelectionLength(int length) { } [TODO] internal override void SetSelectionStart(int start) { } [TODO] protected override void SetTextInternal(string text) { } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public bool ShowSelectionMargin { get { return false; } set { } } [TODO] #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public override String Text { get { return base.Text; } set { base.Text = value; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public override int TextLength { get { return base.TextLength; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public String UndoActionName { get { return String.Empty; } } [TODO] #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultValue(1)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public float ZoomFactor { get { return zoomFactor; } set { zoomFactor = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); } }; // class RichTextBox #endif }; // namespace System.Windows.Forms
//#define PROFILE //#define DBG using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; using Vexe.Editor.Types; using Vexe.Runtime.Extensions; using Vexe.Runtime.Helpers; using Vexe.Runtime.Types; using UnityObject = UnityEngine.Object; namespace Vexe.Editor.Drawers { public class IDictionaryDrawer<TK, TV> : ObjectDrawer<IDictionary<TK, TV>> { private EditorMember _tempKeyMember; private List<EditorMember> _keyElements, _valueElements; private KVPList<TK, TV> _kvpList; private Attribute[] _perKeyAttributes, _perValueAttributes; private DictionaryOptions _options; private string _formatPairPattern; private bool _invalidKeyType; private TextFilter _filter; private string _originalDisplay; private int _lastUpdatedCount = -1; private TK _tempKey; public bool UpdateCount = true; protected override void Initialize() { _invalidKeyType = !typeof(TK).IsValueType && typeof(TK) != typeof(string); if (_invalidKeyType) return; _keyElements = new List<EditorMember>(); _valueElements = new List<EditorMember>(); var perKey = attributes.GetAttribute<PerKeyAttribute>(); if (perKey != null) { if (perKey.ExplicitAttributes == null) _perKeyAttributes = attributes.Where(x => !(x is PerKeyAttribute)).ToArray(); else _perKeyAttributes = attributes.Where(x => perKey.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray(); } var perValue = attributes.GetAttribute<PerValueAttribute>(); if (perValue != null) { if (perValue.ExplicitAttributes == null) _perValueAttributes = attributes.Where(x => !(x is PerValueAttribute)).ToArray(); else _perValueAttributes = attributes.Where(x => perValue.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray(); } var displayAttr = attributes.GetAttribute<DisplayAttribute>(); if (displayAttr != null) _formatPairPattern = displayAttr.FormatKVPair; _options = new DictionaryOptions(displayAttr != null ? displayAttr.DictOpt : Dict.None); if (_formatPairPattern.IsNullOrEmpty()) _formatPairPattern = "[$key, $value]"; if (_options.Readonly) displayText += " (Readonly)"; _originalDisplay = displayText; if (_options.Filter) _filter = new TextFilter(null, id, true, null); if (memberValue == null && !_options.ManualAlloc) memberValue = memberType.Instance<IDictionary<TK, TV>>(); if (memberValue != null) member.CollectionCount = memberValue.Count; if (_options.TempKey) { _tempKeyMember = EditorMember.WrapMember(GetType().GetField("_tempKey", Flags.InstanceAnyVisibility), this, unityTarget, RuntimeHelper.CombineHashCodes(id, "temp"), null); _tempKeyMember.DisplayText = string.Empty; _tempKey = GetNewKey(memberValue); } #if DBG Log("Dictionary drawer Initialized (" + dictionaryName + ")"); #endif } public override void OnGUI() { if (_invalidKeyType) { gui.HelpBox("Unsuported key type: {0}. Only Value-types and strings are, sorry!" .FormatWith(typeof(TK)), MessageType.Error); return; } if (memberValue == null) { if (_options.ManualAlloc) { using(gui.Horizontal()) { gui.Label(member.NiceName + " (Null)"); if (gui.Button("New", GUIStyles.MiniRight, Layout.sFit())) memberValue = memberType.Instance<IDictionary<TK, TV>>(); } } else memberValue = memberType.Instance<IDictionary<TK, TV>>(); } if (memberValue == null) return; member.CollectionCount = memberValue.Count; if (UpdateCount && _lastUpdatedCount != memberValue.Count) { _lastUpdatedCount = memberValue.Count; displayText = Regex.Replace(_originalDisplay, @"\$count", _lastUpdatedCount.ToString()); } if (_kvpList == null) _kvpList = new KVPList<TK, TV>(); else _kvpList.Clear(); // Read { var iter = memberValue.GetEnumerator(); while(iter.MoveNext()) { var key = iter.Current.Key; var value = iter.Current.Value; _kvpList[key] = value; } } #if PROFILE Profiler.BeginSample("DictionaryDrawer Header"); #endif // header if (!_options.HideHeader) { using (gui.Horizontal()) { if (_options.ForceExpand) gui.Label(displayText); else foldout = gui.Foldout(displayText, foldout, Layout.Auto); if (_options.Filter) _filter.Field(gui, 70f); if (!_options.Readonly) { if (_options.TempKey) { string controlName = "TempKey"; GUI.SetNextControlName(controlName); gui.Member(_tempKeyMember); var e = Event.current; if (e.type == EventType.KeyUp && e.keyCode == KeyCode.Return && GUI.GetNameOfFocusedControl() == controlName) { AddNewPair(); EditorGUI.FocusTextInControl(controlName); } } else gui.FlexibleSpace(); if (!_options.HideButtons) { using (gui.State(_kvpList.Count > 0)) { if (gui.ClearButton("dictionary")) _kvpList.Clear(); if (gui.RemoveButton("last added dictionary pair")) { if (_options.AddToLast) _kvpList.RemoveLast(); else _kvpList.RemoveFirst(); } } if (gui.AddButton("pair", MiniButtonStyle.ModRight)) AddNewPair(); } } } gui.Space(3f); } #if PROFILE Profiler.EndSample(); #endif if (!foldout && !_options.ForceExpand) return; if (memberValue.Count == 0) { using (gui.Indent()) gui.HelpBox("Dictionary is empty"); } else { #if PROFILE Profiler.BeginSample("DictionaryDrawer Pairs"); #endif using (gui.Indent()) { for (int i = 0; i < _kvpList.Count; i++) { var dKey = _kvpList.Keys[i]; var dValue = _kvpList.Values[i]; #if PROFILE Profiler.BeginSample("DictionaryDrawer KVP assignments"); #endif int entryKey = RuntimeHelper.CombineHashCodes(id, i, "entry"); string pairStr = null; if (_filter != null) { pairStr = FormatPair(dKey, dValue); #if PROFILE Profiler.BeginSample("DictionaryDrawer Filter"); #endif bool match = _filter.IsMatch(pairStr); #if PROFILE Profiler.EndSample(); #endif if (!match) continue; } if (!_options.HorizontalPairs) { if (pairStr == null) pairStr = FormatPair(dKey, dValue); foldouts[entryKey] = gui.Foldout(pairStr, foldouts[entryKey], Layout.Auto); } #if PROFILE Profiler.EndSample(); #endif if (!foldouts[entryKey] && !_options.HorizontalPairs) continue; #if PROFILE Profiler.BeginSample("DictionaryDrawer SinglePair"); #endif if (_options.HorizontalPairs) { using (gui.Horizontal()) { DrawKey(i, entryKey + 1); DrawValue(i, entryKey + 2); } } else { using (gui.Indent()) { DrawKey(i, entryKey + 1); DrawValue(i, entryKey + 2); } } #if PROFILE Profiler.EndSample(); #endif } } #if PROFILE Profiler.EndSample(); #endif #if PROFILE Profiler.BeginSample("DictionaryDrawer Write"); #endif // Write { Write(); } #if PROFILE Profiler.EndSample(); #endif } } private void Write() { memberValue.Clear(); for (int i = 0; i < _kvpList.Count; i++) { var key = _kvpList.Keys[i]; var value = _kvpList.Values[i]; try { memberValue.Add(key, value); } catch (ArgumentException) //@Todo: figure out a more forgiveful way to handle this { Log("Key already exists: " + key); } } } public void DrawKey(int index, int id) { var keyMember = GetElement(_keyElements, _kvpList.Keys, index, id + 1); using(gui.If(!_options.Readonly && typeof(TK).IsNumeric(), gui.LabelWidth(15f))) { if (_options.Readonly) { var previous = keyMember.Value; var changed = gui.Member(keyMember, @ignoreComposition: _perKeyAttributes == null); if (changed) keyMember.Value = previous; } else { gui.Member(keyMember, @ignoreComposition: _perKeyAttributes == null); } } } public void DrawValue(int index, int id) { var valueMember = GetElement(_valueElements, _kvpList.Values, index, id + 2); using(gui.If(!_options.Readonly && typeof(TV).IsNumeric(), gui.LabelWidth(15f))) { if (_options.Readonly) { var previous = valueMember.Value; var changed = gui.Member(valueMember, @ignoreComposition: _perValueAttributes == null); if (changed) valueMember.Value = previous; } else { gui.Member(valueMember, @ignoreComposition: _perValueAttributes == null); } } } private EditorMember GetElement<T>(List<EditorMember> elements, List<T> source, int index, int id) { if (index >= elements.Count) { Attribute[] attrs; if (typeof(T) == typeof(TK)) attrs = _perKeyAttributes; else attrs = _perValueAttributes; var element = EditorMember.WrapIListElement( @elementName : typeof(T).IsNumeric() && !_options.Readonly ? "~" : string.Empty, @elementType : typeof(T), @elementId : RuntimeHelper.CombineHashCodes(id, index), @attributes : attrs ); element.InitializeIList(source, index, rawTarget, unityTarget); elements.Add(element); return element; } try { var e = elements[index]; e.Write = Write; e.InitializeIList(source, index, rawTarget, unityTarget); return e; } catch (ArgumentOutOfRangeException) { Log("DictionaryDrawer: Accessing element out of range. Index: {0} Count {1}. This shouldn't really happen. Please report it with information on how to replicate it".FormatWith(index, elements.Count)); return null; } } private string FormatPair(TK key, TV value) { #if PROFILE Profiler.BeginSample("DictionaryDrawer: FormatPair"); #endif string format = formatPair(new KeyValuePair<TK, TV>(key, value)); #if PROFILE Profiler.EndSample(); #endif return format; } private Func<KeyValuePair<TK, TV>, string> _formatPair; private Func<KeyValuePair<TK, TV>, string> formatPair { get { return _formatPair ?? (_formatPair = new Func<KeyValuePair<TK, TV>, string>(pair => { var key = pair.Key; var value = pair.Value; var result = _formatPairPattern; result = Regex.Replace(result, @"\$keytype", key == null ? "null" : key.GetType().GetNiceName()); result = Regex.Replace(result, @"\$valuetype", value == null ? "null" : value.GetType().GetNiceName()); result = Regex.Replace(result, @"\$key", GetObjectString(key)); result = Regex.Replace(result, @"\$value", GetObjectString(value)); //Debug.Log("New format: " + result); return result; }).Memoize()); } } private string GetObjectString(object from) { if (from.IsObjectNull()) return "null"; var obj = from as UnityObject; if (obj != null) return obj.name + " (" + obj.GetType().Name + ")"; var toStr = from.ToString(); return toStr == null ? "null" : toStr; } TK GetNewKey(IDictionary<TK, TV> from) { TK key; if (typeof(TK) == typeof(string)) { string prefix; int postfix; if (from.Count > 0) { prefix = from.Last().Key as string; string postfixStr = ""; int i = prefix.Length - 1; for (; i >= 0; i--) { char c = prefix[i]; if (!char.IsDigit(c)) break; postfixStr = postfixStr.Insert(0, c.ToString()); } if (int.TryParse(postfixStr, out postfix)) prefix = prefix.Remove(i + 1, postfixStr.Length); } else { prefix = "New Key "; postfix = 0; } while(from.Keys.Contains((TK)(object)(prefix + postfix))) postfix++; key = (TK)(object)(prefix + postfix); } else if (typeof(TK) == typeof(int)) { var n = 0; while (from.Keys.Contains((TK)(object)(n))) n++; key = (TK)(object)n; } else if (typeof(TK).IsEnum) { var values = Enum.GetValues(typeof(TK)) as TK[]; var result = values.Except(from.Keys).ToList(); if (result.Count == 0) return default(TK); key = (TK)result[0]; } else key = default(TK); return key; } private void AddNewPair() { var key = _options.TempKey ? _tempKey : GetNewKey(_kvpList); try { var value = default(TV); if (_options.AddToLast) _kvpList.Add(key, value); else _kvpList.Insert(0, key, value); memberValue.Add(key, value); var eKey = RuntimeHelper.CombineHashCodes(id, (_kvpList.Count - 1), "entry"); foldouts[eKey] = true; foldout = true; if (_options.TempKey) _tempKey = GetNewKey(_kvpList); } catch (ArgumentException) { Log("Key already exists: " + key); } } private struct DictionaryOptions { public readonly bool Readonly; public readonly bool ForceExpand; public readonly bool HideHeader; public readonly bool HorizontalPairs; public readonly bool Filter; public readonly bool AddToLast; public readonly bool TempKey; public readonly bool ManualAlloc; public readonly bool HideButtons; public DictionaryOptions(Dict options) { Readonly = options.HasFlag(Dict.Readonly); ForceExpand = options.HasFlag(Dict.ForceExpand); HideHeader = options.HasFlag(Dict.HideHeader); HorizontalPairs = options.HasFlag(Dict.HorizontalPairs); Filter = options.HasFlag(Dict.Filter); AddToLast = options.HasFlag(Dict.AddToLast); TempKey = options.HasFlag(Dict.TempKey); ManualAlloc = options.HasFlag(Dict.ManualAlloc); HideButtons = options.HasFlag(Dict.HideButtons); } } } }
using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Diagnostics; using System.Windows.Input; using AppStudio.DataProviders; using AppStudio.Uwp.Actions; using AppStudio.Uwp.Cache; using AppStudio.Uwp.Commands; using AppStudio.Uwp.DataSync; using Windows.ApplicationModel.DataTransfer; using Windows.Devices.Input; using Windows.Graphics.Display; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using AppStudio.Uwp.Navigation; using NguyenAnNinhConfession.Config; using NguyenAnNinhConfession.Services; using Windows.ApplicationModel.Resources; using AppStudio.Uwp; namespace NguyenAnNinhConfession.ViewModels { public class DetailViewModel : PageViewModelBase { private static ResourceLoader _resourceLoader; private ComposedItemViewModel _selectedItem; private bool _isFullScreen; private bool _showInfo; private bool _showInfoLastValue; private bool _supportSlideShow; private bool _supportFullScreen; private bool _isRestoreScreenButtonVisible; private DispatcherTimer _slideShowTimer; private DispatcherTimer _mouseMovedTimer; private MouseCapabilities _mouseCapabilities; private ObservableCollection<ItemViewModel> _relatedItems = new ObservableCollection<ItemViewModel>(); private string _relatedContentTitle; private string _relatedContentStatus; private Func<ItemViewModel, Task> LoadDataInternal; private DetailViewModel() { Items = new ObservableCollection<ComposedItemViewModel>(); ShowInfo = true; IsRestoreScreenButtonVisible = false; ZoomMode = ZoomMode.Enabled; if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled) { FullScreenService.FullScreenModeChanged += FullScreenModeChanged; FullScreenService.FullScreenPlayActionsChanged += FullScreenPlayActionsChanged; if (HasMouseConnected) { MouseDevice.GetForCurrentView().MouseMoved += MouseMoved; } } } private static ResourceLoader ResourceLoader { get { if (_resourceLoader == null) { _resourceLoader = new ResourceLoader(); } return _resourceLoader; } } public static DetailViewModel CreateNew<TSchema, TRelatedSchema>(SectionConfigBase<TSchema, TRelatedSchema> sectionConfig) where TSchema : SchemaBase where TRelatedSchema : SchemaBase { var vm = new DetailViewModel { Title = sectionConfig.DetailPage.Title, SectionName = sectionConfig.Name }; vm.RelatedContentTitle = sectionConfig.RelatedContent?.ListPage?.Title; var settings = new CacheSettings { Key = sectionConfig.Name, Expiration = vm.CacheExpiration, NeedsNetwork = sectionConfig.NeedsNetwork, UseStorage = sectionConfig.NeedsNetwork, }; //we save a reference to the load delegate in order to avoid export TSchema outside the view model vm.LoadDataInternal = async (selectedItem) => { TSchema sourceSelected = null; await AppCache.LoadItemsAsync<TSchema>(settings, sectionConfig.LoadDataAsyncFunc, (content) => vm.ParseDetailItems(sectionConfig.DetailPage, content, selectedItem, out sourceSelected)); if (sectionConfig.RelatedContent != null) { var settingsRelated = new CacheSettings { Key = $"{sectionConfig.Name}_related_{selectedItem.Id}", Expiration = vm.CacheExpiration, NeedsNetwork = sectionConfig.RelatedContent.NeedsNetwork }; vm.RelatedContentStatus = ResourceLoader.GetString("LoadingRelatedContent"); await AppCache.LoadItemsAsync<TRelatedSchema>(settingsRelated, () => sectionConfig.RelatedContent.LoadDataAsync(sourceSelected), (content) => vm.ParseRelatedItems(sectionConfig.RelatedContent.ListPage, content)); if (vm.RelatedItems == null || vm.RelatedItems.Count == 0) { vm.RelatedContentStatus = ResourceLoader.GetString("ThereIsNotRelatedContent"); } else { vm.RelatedContentStatus = string.Empty; } } }; return vm; } public static DetailViewModel CreateNew<TSchema>(SectionConfigBase<TSchema> sectionConfig) where TSchema : SchemaBase { var vm = new DetailViewModel { Title = sectionConfig.DetailPage.Title, SectionName = sectionConfig.Name }; var settings = new CacheSettings { Key = sectionConfig.Name, Expiration = vm.CacheExpiration, NeedsNetwork = sectionConfig.NeedsNetwork, UseStorage = sectionConfig.NeedsNetwork, }; //we save a reference to the load delegate in order to avoid export TSchema outside the view model vm.LoadDataInternal = async (selectedItem) => { await AppCache.LoadItemsAsync<TSchema>(settings, sectionConfig.LoadDataAsyncFunc, (content) => vm.ParseDetailItems(sectionConfig.DetailPage, content, selectedItem)); }; return vm; } public async Task LoadDataAsync(ItemViewModel selectedItem) { try { HasLoadDataErrors = false; IsBusy = true; await LoadDataInternal(selectedItem); } catch (Exception ex) { HasLoadDataErrors = true; Debug.WriteLine(ex.ToString()); } finally { IsBusy = false; } } public ComposedItemViewModel SelectedItem { get { return _selectedItem; } set { SetProperty(ref _selectedItem, value); } } private ZoomMode _zoomMode; public ZoomMode ZoomMode { get { return _zoomMode; } set { SetProperty(ref _zoomMode, value); } } public ObservableCollection<ComposedItemViewModel> Items { get; protected set; } public ObservableCollection<ItemViewModel> RelatedItems { get { return _relatedItems; } private set { SetProperty(ref _relatedItems, value); } } public string RelatedContentTitle { get { return _relatedContentTitle; } set { SetProperty(ref _relatedContentTitle, value); } } public string RelatedContentStatus { get { return _relatedContentStatus; } set { SetProperty(ref _relatedContentStatus, value); } } public RelayCommand<ItemViewModel> RelatedItemClickCommand { get { return new RelayCommand<ItemViewModel>( (item) => { NavigationService.NavigateTo(item); }); } } public bool IsFullScreen { get { return _isFullScreen; } set { SetProperty(ref _isFullScreen, value); } } public bool ShowInfo { get { return _showInfo; } set { SetProperty(ref _showInfo, value); } } public bool SupportSlideShow { get { return _supportSlideShow; } set { SetProperty(ref _supportSlideShow, value); } } public bool SupportFullScreen { get { return _supportFullScreen; } set { SetProperty(ref _supportFullScreen, value); } } public bool IsRestoreScreenButtonVisible { get { return _isRestoreScreenButtonVisible; } set { SetProperty(ref _isRestoreScreenButtonVisible, value); } } public DispatcherTimer SlideShowTimer { get { if (_slideShowTimer == null) { _slideShowTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(1500) }; _slideShowTimer.Tick += PresentationTimeEvent; } return _slideShowTimer; } } public DispatcherTimer MouseMovedTimer { get { if (_mouseMovedTimer == null) { _mouseMovedTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(3000) }; _mouseMovedTimer.Tick += ((e, o) => { _mouseMovedTimer.Stop(); IsRestoreScreenButtonVisible = false; }); } return _mouseMovedTimer; } } private bool HasMouseConnected { get { if (_mouseCapabilities == null) { _mouseCapabilities = new MouseCapabilities(); } return _mouseCapabilities.MousePresent > 0; } } public ICommand FullScreenCommand { get { return new RelayCommand(() => { if (SupportFullScreen || SupportSlideShow) { FullScreenService.EnterFullScreenMode(); ZoomMode = ZoomMode.Enabled; } }); } } public ICommand ShowPresentationCommand { get { return new RelayCommand(() => { if (SupportFullScreen || SupportSlideShow) { FullScreenService.EnterFullScreenMode(true); ZoomMode = ZoomMode.Disabled; } }); } } public ICommand ShowInfoCommand { get { return new RelayCommand(() => { if (!IsFullScreen) { ShowInfo = !ShowInfo; } }); } } public ICommand DisableFullScreenCommand { get { return new RelayCommand(() => { if (SupportFullScreen) { FullScreenService.ExitFullScreenMode(); } }); } } public void ShareContent(DataRequest dataRequest, bool supportsHtml = true) { ShareContent(dataRequest, SelectedItem, supportsHtml); } private void ParseDetailItems<TSchema>(DetailPageConfig<TSchema> detailConfig, CachedContent<TSchema> content, ItemViewModel selectedItem) where TSchema : SchemaBase { TSchema sourceSelected; ParseDetailItems(detailConfig, content, selectedItem, out sourceSelected); } private void ParseDetailItems<TSchema>(DetailPageConfig<TSchema> detailConfig, CachedContent<TSchema> content, ItemViewModel selectedItem, out TSchema sourceSelected) where TSchema : SchemaBase { sourceSelected = content.Items.FirstOrDefault(i => i._id == selectedItem.Id); foreach (var item in content.Items) { var composedItem = new ComposedItemViewModel { Id = item._id }; foreach (var binding in detailConfig.LayoutBindings) { var parsedItem = new ItemViewModel { Id = item._id }; binding(parsedItem, item); composedItem.Add(parsedItem); } composedItem.Actions = detailConfig.Actions .Select(a => new ActionInfo { Command = a.Command, CommandParameter = a.CommandParameter(item), Style = a.Style, Text = a.Text, ActionType = ActionType.Primary }) .ToList(); Items.Add(composedItem); } if (selectedItem != null) { SelectedItem = Items.FirstOrDefault(i => i.Id == selectedItem.Id); } } private void ParseRelatedItems<TSchema>(ListPageConfig<TSchema> listConfig, CachedContent<TSchema> content) where TSchema : SchemaBase { var parsedItems = new List<ItemViewModel>(); foreach (var item in content.Items) { var parsedItem = new ItemViewModel { Id = item._id, NavigationInfo = listConfig.DetailNavigation(item) }; listConfig.LayoutBindings(parsedItem, item); parsedItems.Add(parsedItem); } RelatedItems.Sync(parsedItems); } private void FullScreenPlayActionsChanged(object sender, EventArgs e) { if (SupportSlideShow) { SlideShowTimer.Start(); } } private void FullScreenModeChanged(object sender, bool isFullScreen) { if (SupportFullScreen) { //this.ShowInfo = !isFullScreen; this.IsFullScreen = isFullScreen; if (isFullScreen) { this._showInfoLastValue = this.ShowInfo; this.ShowInfo = false; IsRestoreScreenButtonVisible = true; if (HasMouseConnected) { MouseMovedTimer.Start(); } } else { this.ShowInfo = this._showInfoLastValue; IsRestoreScreenButtonVisible = false; } } if (SupportSlideShow) { if (!isFullScreen) { SlideShowTimer.Stop(); ZoomMode = ZoomMode.Enabled; } } } private void PresentationTimeEvent(object sender, object e) { if (Items != null && Items.Count > 1 && SelectedItem != null) { var index = Items.IndexOf(SelectedItem); if (index < Items.Count - 1) { index++; } else { index = 0; } SelectedItem = Items[index]; } } private void MouseMoved(MouseDevice sender, MouseEventArgs args) { if (IsFullScreen) { IsRestoreScreenButtonVisible = true; MouseMovedTimer.Start(); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Net.Mime; using System.Runtime.CompilerServices; using Reinterpret.Net; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; namespace Rs317.Sharp { public sealed class Sprite : DrawingArea, ITexture { //Custom: This is a hack that allows implementations to override the image loading of the Sprite ctor that depends on SixLabors. public static Func<byte[], LoadedImagePixels> ExternalLoadImageHook { get; set; } = null; #region ITexture public int[] Pixels => pixels; public int AnimationDirection => 0; public int AnimationSpeed => 0; public bool isLoaded => true; //TODO: Implement these properly? public float UVCoordU { get; set; } public float UVCoordV { get; set; } #endregion public int[] pixels; public int width; public int height; private int offsetX; private int offsetY; public int maxWidth; public int maxHeight; public bool isValid { get; } = true; public Sprite(Archive streamLoader, String target, int archiveId, Default317Buffer optionalIndexStream = null) { try { if(target.ToLower() == "headicons") return; Default317Buffer dataStream = new Default317Buffer(streamLoader.decompressFile(target + ".dat")); Default317Buffer indexStream = optionalIndexStream != null ? optionalIndexStream : new Default317Buffer(streamLoader.decompressFile("index.dat")); indexStream.position = dataStream.getUnsignedLEShort(); maxWidth = indexStream.getUnsignedLEShort(); maxHeight = indexStream.getUnsignedLEShort(); if (!IsDataAvailable(indexStream)) { InitializeAsEmpty(); return; } int length = indexStream.getUnsignedByte(); int[] pixels = new int[length]; for(int p = 0; p < length - 1; p++) { pixels[p + 1] = indexStream.get3Bytes(); if(pixels[p + 1] == 0) pixels[p + 1] = 1; } for(int i = 0; i < archiveId; i++) { indexStream.position += 2; dataStream.position += indexStream.getUnsignedLEShort() * indexStream.getUnsignedLEShort(); indexStream.position++; } if(!IsDataAvailable(indexStream)) { InitializeAsEmpty(); return; } offsetX = indexStream.getUnsignedByte(); if(!IsDataAvailable(indexStream)) { InitializeAsEmpty(); return; } offsetY = indexStream.getUnsignedByte(); width = indexStream.getUnsignedLEShort(); height = indexStream.getUnsignedLEShort(); if(!IsDataAvailable(indexStream)) { InitializeAsEmpty(); return; } int type = indexStream.getUnsignedByte(); int pixelCount = width * height; //Custom: Below are some sanity checks that are custom but help guard against known clean cache data issues. bool isEnoughDataAvailable = pixelCount <= (dataStream.buffer.Length - dataStream.position); //Don't let corrupt image data, in default cache, cause BIG allocation (bad for WebGL) //or allocate/read for empty images. if (pixelCount <= 0 || pixelCount > int.MaxValue / 100 || !isEnoughDataAvailable || dataStream.position < 0) //sometimes happens!! { width = 0; height = 0; this.pixels = Array.Empty<int>(); return; } this.pixels = new int[pixelCount]; try { if(type == 0) { for(int p = 0; p < pixelCount; p++) this.pixels[p] = pixels[dataStream.getUnsignedByte()]; return; } } catch (Exception e) { Console.WriteLine($"Failed to read image type: {type}. PixelCount: {pixelCount} StreamLength: {dataStream.buffer.Length} Position: {dataStream.position} Reason: {e}"); throw; } try { if(type == 1) { for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) this.pixels[x + y * width] = pixels[dataStream.getUnsignedByte()]; } } } catch (Exception e) { Console.WriteLine($"Failed to read image type: {type}. PixelCount: {pixelCount} Reason: {e}"); throw; } } catch (Exception e) { isValid = false; //Don't throw, this is just a data error. Not an engine fault. throw new InvalidOperationException($"Failed to generate Sprite for: {target} id: {id}. Reason: {e.Message}\nStack: {e.StackTrace}", e); } } protected void InitializeAsEmpty() { width = 0; height = 0; this.pixels = Array.Empty<int>(); } public Sprite(byte[] abyte0, object component) //not referenced. { try { if (ExternalLoadImageHook != null) { //TODO: This ia hack to assume size LoadedImagePixels image = ExternalLoadImageHook?.Invoke(abyte0); width = image.Width; height = image.Height; maxWidth = width; maxHeight = height; offsetX = 0; offsetY = 0; pixels = image.Pixels; } else { using(Image<Rgba32> loadedImage = Image.Load(new MemoryStream(abyte0))) { width = loadedImage.Width; height = loadedImage.Height; maxWidth = width; maxHeight = height; offsetX = 0; offsetY = 0; //RS2Sharp actually maps TO Argb and then back to get the color value of the titlescreen. //TODO: Let's try to avoid an allocation here. pixels = loadedImage.GetPixelSpan().ToArray().Select(p => Color.FromArgb(p.R, p.G, p.B).ToArgb()).ToArray(); } } } catch(Exception _ex) { Console.WriteLine($"Error converting jpg. Reason: {_ex}"); } } public Sprite(int i, int j) { pixels = new int[i * j]; width = maxWidth = i; height = maxHeight = j; offsetX = offsetY = 0; } public void adjustRGB(int adjustmentR, int adjustmentG, int adjustmentB) { if(!isValid) return; for(int pixel = 0; pixel < pixels.Length; pixel++) { int originalColour = pixels[pixel]; if(originalColour != 0) { int red = originalColour >> 16 & 0xff; red += adjustmentR; if(red < 1) red = 1; else if(red > 255) red = 255; int green = originalColour >> 8 & 0xff; green += adjustmentG; if(green < 1) green = 1; else if(green > 255) green = 255; int blue = originalColour & 0xff; blue += adjustmentB; if(blue < 1) blue = 1; else if(blue > 255) blue = 255; pixels[pixel] = (red << 16) + (green << 8) + blue; } } } private void blockCopy(int destinationPointer, int copyLength, int k, int sourceBlockLength, int sourcePointer, int destinationBlockLength, int[] source, int[] destination) { if(!isValid) return; int blockCount = -(copyLength >> 2); copyLength = -(copyLength & 3); for(int i2 = -k; i2 < 0; i2++) { for(int ptr = blockCount; ptr < 0; ptr++) { destination[destinationPointer++] = source[sourcePointer++]; destination[destinationPointer++] = source[sourcePointer++]; destination[destinationPointer++] = source[sourcePointer++]; destination[destinationPointer++] = source[sourcePointer++]; } for(int ptr = copyLength; ptr < 0; ptr++) destination[destinationPointer++] = source[sourcePointer++]; destinationPointer += destinationBlockLength; sourcePointer += sourceBlockLength; } } private void blockCopyAlpha(int sourcePointer, int blockCount, int[] destination, int[] source, int sourceBlockLength, int i1, int destinationBlockLength, int alpha, int destinationPointer) { if(!isValid) return; int sourceValue; // was parameter int destinationAlpha = 256 - alpha; for(int k2 = -i1; k2 < 0; k2++) { for(int ptr = -blockCount; ptr < 0; ptr++) { sourceValue = source[sourcePointer++]; if(sourceValue != 0) { int destinationValue = destination[destinationPointer]; destination[destinationPointer++] = (int)((sourceValue & 0xff00ff) * alpha + (destinationValue & 0xff00ff) * destinationAlpha & 0xff00ff00) + ((sourceValue & 0xff00) * alpha + (destinationValue & 0xff00) * destinationAlpha & 0xff0000) >> 8; } else { destinationPointer++; } } destinationPointer += destinationBlockLength; sourcePointer += sourceBlockLength; } } private void blockCopyTransparent(int[] destination, int[] source, int sourcePointer, int destinationPointer, int copyLength, int i1, int destinationBlockLength, int sourceBlockLength) { if(!isValid) return; int value; // was parameter int blockCount = -(copyLength >> 2); copyLength = -(copyLength & 3); for(int i2 = -i1; i2 < 0; i2++) { for(int ptr = blockCount; ptr < 0; ptr++) { value = source[sourcePointer++]; if(value != 0) destination[destinationPointer++] = value; else destinationPointer++; value = source[sourcePointer++]; if(value != 0) destination[destinationPointer++] = value; else destinationPointer++; value = source[sourcePointer++]; if(value != 0) destination[destinationPointer++] = value; else destinationPointer++; value = source[sourcePointer++]; if(value != 0) destination[destinationPointer++] = value; else destinationPointer++; } for(int ptr = copyLength; ptr < 0; ptr++) { value = source[sourcePointer++]; if(value != 0) destination[destinationPointer++] = value; else destinationPointer++; } destinationPointer += destinationBlockLength; sourcePointer += sourceBlockLength; } } public void drawImage(int x, int y) { if(!isValid) return; x += offsetX; y += offsetY; int destinationOffset = x + y * DrawingArea.width; int sourceOffset = 0; int rowCount = height; int columnCount = width; int lineDestinationOffset = DrawingArea.width - columnCount; int lineSourceOffset = 0; if(y < DrawingArea.topY) { int clipHeight = DrawingArea.topY - y; rowCount -= clipHeight; y = DrawingArea.topY; sourceOffset += clipHeight * columnCount; destinationOffset += clipHeight * DrawingArea.width; } if(y + rowCount > DrawingArea.bottomY) rowCount -= (y + rowCount) - DrawingArea.bottomY; if(x < DrawingArea.topX) { int clipWidth = DrawingArea.topX - x; columnCount -= clipWidth; x = DrawingArea.topX; sourceOffset += clipWidth; destinationOffset += clipWidth; lineSourceOffset += clipWidth; lineDestinationOffset += clipWidth; } if(x + columnCount > DrawingArea.bottomX) { int clipWidth = (x + columnCount) - DrawingArea.bottomX; columnCount -= clipWidth; lineSourceOffset += clipWidth; lineDestinationOffset += clipWidth; } if(!(columnCount <= 0 || rowCount <= 0)) { blockCopyTransparent(DrawingArea.pixels, pixels, sourceOffset, destinationOffset, columnCount, rowCount, lineDestinationOffset, lineSourceOffset); } } public void drawImageAlpha(int i, int j) { if(!isValid) return; int k = 128; // was parameter i += offsetX; j += offsetY; int i1 = i + j * DrawingArea.width; int j1 = 0; int k1 = height; int l1 = width; int i2 = DrawingArea.width - l1; int j2 = 0; if(j < DrawingArea.topY) { int k2 = DrawingArea.topY - j; k1 -= k2; j = DrawingArea.topY; j1 += k2 * l1; i1 += k2 * DrawingArea.width; } if(j + k1 > DrawingArea.bottomY) k1 -= (j + k1) - DrawingArea.bottomY; if(i < DrawingArea.topX) { int l2 = DrawingArea.topX - i; l1 -= l2; i = DrawingArea.topX; j1 += l2; i1 += l2; j2 += l2; i2 += l2; } if(i + l1 > DrawingArea.bottomX) { int i3 = (i + l1) - DrawingArea.bottomX; l1 -= i3; j2 += i3; i2 += i3; } if(!(l1 <= 0 || k1 <= 0)) { blockCopyAlpha(j1, l1, DrawingArea.pixels, pixels, j2, k1, i2, k, i1); } } public void drawInverse(int i, int j) { if(!isValid) return; i += offsetX; j += offsetY; int l = i + j * DrawingArea.width; int i1 = 0; int j1 = height; int k1 = width; int l1 = DrawingArea.width - k1; int i2 = 0; if(j < DrawingArea.topY) { int j2 = DrawingArea.topY - j; j1 -= j2; j = DrawingArea.topY; i1 += j2 * k1; l += j2 * DrawingArea.width; } if(j + j1 > DrawingArea.bottomY) j1 -= (j + j1) - DrawingArea.bottomY; if(i < DrawingArea.topX) { int k2 = DrawingArea.topX - i; k1 -= k2; i = DrawingArea.topX; i1 += k2; l += k2; i2 += k2; l1 += k2; } if(i + k1 > DrawingArea.bottomX) { int l2 = (i + k1) - DrawingArea.bottomX; k1 -= l2; i2 += l2; l1 += l2; } if(k1 <= 0 || j1 <= 0) { } else { blockCopy(l, k1, j1, i2, i1, l1, pixels, DrawingArea.pixels); } } public void initDrawingArea() { if(!isValid) return; DrawingArea.initDrawingArea(height, width, pixels); } public void method354(IndexedImage background, int x, int y) { if(!isValid) return; y += offsetX; x += offsetY; int k = y + x * DrawingArea.width; int l = 0; int i1 = height; int j1 = width; int k1 = DrawingArea.width - j1; int l1 = 0; if(x < DrawingArea.topY) { int i2 = DrawingArea.topY - x; i1 -= i2; x = DrawingArea.topY; l += i2 * j1; k += i2 * DrawingArea.width; } if(x + i1 > DrawingArea.bottomY) i1 -= (x + i1) - DrawingArea.bottomY; if(y < DrawingArea.topX) { int j2 = DrawingArea.topX - y; j1 -= j2; y = DrawingArea.topX; l += j2; k += j2; l1 += j2; k1 += j2; } if(y + j1 > DrawingArea.bottomX) { int k2 = (y + j1) - DrawingArea.bottomX; j1 -= k2; l1 += k2; k1 += k2; } if(!(j1 <= 0 || i1 <= 0)) { method355(pixels, j1, background.pixels, i1, DrawingArea.pixels, 0, k1, k, l1, l); } } private void method355(int[] ai, int i, byte[] abyte0, int j, int[] ai1, int k, int l, int i1, int j1, int k1) { if(!isValid) return; int l1 = -(i >> 2); i = -(i & 3); for(int j2 = -j; j2 < 0; j2++) { for(int k2 = l1; k2 < 0; k2++) { k = ai[k1++]; if(k != 0 && abyte0[i1] == 0) ai1[i1++] = k; else i1++; k = ai[k1++]; if(k != 0 && abyte0[i1] == 0) ai1[i1++] = k; else i1++; k = ai[k1++]; if(k != 0 && abyte0[i1] == 0) ai1[i1++] = k; else i1++; k = ai[k1++]; if(k != 0 && abyte0[i1] == 0) ai1[i1++] = k; else i1++; } for(int l2 = i; l2 < 0; l2++) { k = ai[k1++]; if(k != 0 && abyte0[i1] == 0) ai1[i1++] = k; else i1++; } i1 += l; k1 += j1; } } public void rotate(int x, int y, double rotation) { if(!isValid) return; // all of the following were parameters int centreY = 15; int width = 20; int centreX = 15; int hingeSize = 256; int height = 20; // all of the previous were parameters try { int i2 = -width / 2; int j2 = -height / 2; int k2 = (int)(Math.Sin(rotation) * 65536D); int l2 = (int)(Math.Cos(rotation) * 65536D); k2 = k2 * hingeSize >> 8; l2 = l2 * hingeSize >> 8; int i3 = (centreX << 16) + (j2 * k2 + i2 * l2); int j3 = (centreY << 16) + (j2 * l2 - i2 * k2); int k3 = x + y * DrawingArea.width; for(y = 0; y < height; y++) { int l3 = k3; int i4 = i3; int j4 = j3; for(x = -width; x < 0; x++) { int k4 = pixels[(i4 >> 16) + (j4 >> 16) * this.width]; if(k4 != 0) DrawingArea.pixels[l3++] = k4; else l3++; i4 += l2; j4 -= k2; } i3 += k2; j3 += l2; k3 += DrawingArea.width; } } catch(Exception _ex) { } } public void rotate(int height, int rotation, int[] widthMap, int hingeSize, int[] ai1, int centreY, int y, int x, int width, int centreX) { if(!isValid) return; try { int negativeCentreX = -width / 2; int negativeCentreY = -height / 2; int offsetY = (int)(Math.Sin(rotation / 326.11000000000001D) * 65536D); int offsetX = (int)(Math.Cos(rotation / 326.11000000000001D) * 65536D); offsetY = offsetY * hingeSize >> 8; offsetX = offsetX * hingeSize >> 8; int j3 = (centreX << 16) + (negativeCentreY * offsetY + negativeCentreX * offsetX); int k3 = (centreY << 16) + (negativeCentreY * offsetX - negativeCentreX * offsetY); int l3 = x + y * DrawingArea.width; for(y = 0; y < height; y++) { int i4 = ai1[y]; int j4 = l3 + i4; int k4 = j3 + offsetX * i4; int l4 = k3 - offsetY * i4; for(x = -widthMap[y]; x < 0; x++) { DrawingArea.pixels[j4++] = pixels[(k4 >> 16) + (l4 >> 16) * this.width]; k4 += offsetX; l4 -= offsetY; } j3 += offsetY; k3 += offsetX; l3 += DrawingArea.width; } } catch(Exception _ex) { } } public void trim() { if(!isValid) return; int[] targetPixels = new int[maxWidth * maxHeight]; for(int _y = 0; _y < height; _y++) { System.Buffer.BlockCopy(pixels, _y * width * sizeof(int), targetPixels, (_y + offsetY * maxWidth + offsetX) * sizeof(int), width * sizeof(int)); } pixels = targetPixels; width = maxWidth; height = maxHeight; offsetX = 0; offsetY = 0; } } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\TenEllip.tcl // output file is AVTenEllip.cs /// <summary> /// The testing class derived from AVTenEllip /// </summary> public class AVTenEllipClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVTenEllip(String [] argv) { //Prefix Content is: "" // create tensor ellipsoids[] // Create the RenderWindow, Renderer and interactive renderer[] //[] ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); //[] // Create tensor ellipsoids[] //[] // generate tensors[] ptLoad = new vtkPointLoad(); ptLoad.SetLoadValue((double)100.0); ptLoad.SetSampleDimensions((int)6,(int)6,(int)6); ptLoad.ComputeEffectiveStressOn(); ptLoad.SetModelBounds((double)-10,(double)10,(double)-10,(double)10,(double)-10,(double)10); // extract plane of data[] plane = new vtkImageDataGeometryFilter(); plane.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort()); plane.SetExtent((int)2,(int)2,(int)0,(int)99,(int)0,(int)99); // Generate ellipsoids[] sphere = new vtkSphereSource(); sphere.SetThetaResolution((int)8); sphere.SetPhiResolution((int)8); ellipsoids = new vtkTensorGlyph(); ellipsoids.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort()); ellipsoids.SetSourceConnection((vtkAlgorithmOutput)sphere.GetOutputPort()); ellipsoids.SetScaleFactor((double)10); ellipsoids.ClampScalingOn(); ellipNormals = new vtkPolyDataNormals(); ellipNormals.SetInputConnection((vtkAlgorithmOutput)ellipsoids.GetOutputPort()); // Map contour[] lut = new vtkLogLookupTable(); lut.SetHueRange((double).6667,(double)0.0); ellipMapper = vtkPolyDataMapper.New(); ellipMapper.SetInputConnection((vtkAlgorithmOutput)ellipNormals.GetOutputPort()); ellipMapper.SetLookupTable((vtkScalarsToColors)lut); plane.Update(); //force update for scalar range[] ellipMapper.SetScalarRange((double)((vtkDataSet)plane.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)plane.GetOutput()).GetScalarRange()[1]); ellipActor = new vtkActor(); ellipActor.SetMapper((vtkMapper)ellipMapper); //[] // Create outline around data[] //[] outline = new vtkOutlineFilter(); outline.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort()); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)outlineMapper); outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0); //[] // Create cone indicating application of load[] //[] coneSrc = new vtkConeSource(); coneSrc.SetRadius((double).5); coneSrc.SetHeight((double)2); coneMap = vtkPolyDataMapper.New(); coneMap.SetInputConnection((vtkAlgorithmOutput)coneSrc.GetOutputPort()); coneActor = new vtkActor(); coneActor.SetMapper((vtkMapper)coneMap); coneActor.SetPosition((double)0,(double)0,(double)11); coneActor.RotateY((double)90); coneActor.GetProperty().SetColor((double)1,(double)0,(double)0); camera = new vtkCamera(); camera.SetFocalPoint((double)0.113766,(double)-1.13665,(double)-1.01919); camera.SetPosition((double)-29.4886,(double)-63.1488,(double)26.5807); camera.SetViewAngle((double)24.4617); camera.SetViewUp((double)0.17138,(double)0.331163,(double)0.927879); camera.SetClippingRange((double)1,(double)100); ren1.AddActor((vtkProp)ellipActor); ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)coneActor); ren1.SetBackground((double)1.0,(double)1.0,(double)1.0); ren1.SetActiveCamera((vtkCamera)camera); renWin.SetSize((int)400,(int)400); renWin.Render(); // prevent the tk window from showing up then start the event loop[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkPointLoad ptLoad; static vtkImageDataGeometryFilter plane; static vtkSphereSource sphere; static vtkTensorGlyph ellipsoids; static vtkPolyDataNormals ellipNormals; static vtkLogLookupTable lut; static vtkPolyDataMapper ellipMapper; static vtkActor ellipActor; static vtkOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkConeSource coneSrc; static vtkPolyDataMapper coneMap; static vtkActor coneActor; static vtkCamera camera; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPointLoad GetptLoad() { return ptLoad; } ///<summary> A Set Method for Static Variables </summary> public static void SetptLoad(vtkPointLoad toSet) { ptLoad = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageDataGeometryFilter Getplane() { return plane; } ///<summary> A Set Method for Static Variables </summary> public static void Setplane(vtkImageDataGeometryFilter toSet) { plane = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkSphereSource Getsphere() { return sphere; } ///<summary> A Set Method for Static Variables </summary> public static void Setsphere(vtkSphereSource toSet) { sphere = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTensorGlyph Getellipsoids() { return ellipsoids; } ///<summary> A Set Method for Static Variables </summary> public static void Setellipsoids(vtkTensorGlyph toSet) { ellipsoids = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataNormals GetellipNormals() { return ellipNormals; } ///<summary> A Set Method for Static Variables </summary> public static void SetellipNormals(vtkPolyDataNormals toSet) { ellipNormals = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkLogLookupTable Getlut() { return lut; } ///<summary> A Set Method for Static Variables </summary> public static void Setlut(vtkLogLookupTable toSet) { lut = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetellipMapper() { return ellipMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetellipMapper(vtkPolyDataMapper toSet) { ellipMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetellipActor() { return ellipActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetellipActor(vtkActor toSet) { ellipActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetoutlineMapper() { return outlineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineMapper(vtkPolyDataMapper toSet) { outlineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkConeSource GetconeSrc() { return coneSrc; } ///<summary> A Set Method for Static Variables </summary> public static void SetconeSrc(vtkConeSource toSet) { coneSrc = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetconeMap() { return coneMap; } ///<summary> A Set Method for Static Variables </summary> public static void SetconeMap(vtkPolyDataMapper toSet) { coneMap = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetconeActor() { return coneActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetconeActor(vtkActor toSet) { coneActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCamera Getcamera() { return camera; } ///<summary> A Set Method for Static Variables </summary> public static void Setcamera(vtkCamera toSet) { camera = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(ptLoad!= null){ptLoad.Dispose();} if(plane!= null){plane.Dispose();} if(sphere!= null){sphere.Dispose();} if(ellipsoids!= null){ellipsoids.Dispose();} if(ellipNormals!= null){ellipNormals.Dispose();} if(lut!= null){lut.Dispose();} if(ellipMapper!= null){ellipMapper.Dispose();} if(ellipActor!= null){ellipActor.Dispose();} if(outline!= null){outline.Dispose();} if(outlineMapper!= null){outlineMapper.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(coneSrc!= null){coneSrc.Dispose();} if(coneMap!= null){coneMap.Dispose();} if(coneActor!= null){coneActor.Dispose();} if(camera!= null){camera.Dispose();} } } //--- end of script --//
// // ASN1.cs: Abstract Syntax Notation 1 - micro-parser and generator // // Authors: // Sebastien Pouliot <[email protected]> // Jesper Pedersen <[email protected]> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // (C) 2004 IT+ A/S (http://www.itplus.dk) // // 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; using System.IO; using System.Text; namespace Mono.Security { // References: // a. ITU ASN.1 standards (free download) // http://www.itu.int/ITU-T/studygroups/com17/languages/ #if INSIDE_CORLIB internal #else public #endif class ASN1 { private byte m_nTag; private byte[] m_aValue; private ArrayList elist; public ASN1 () : this (0x00, null) {} public ASN1 (byte tag) : this (tag, null) {} public ASN1 (byte tag, byte[] data) { m_nTag = tag; m_aValue = data; } public ASN1 (byte[] data) { m_nTag = data [0]; int nLenLength = 0; int nLength = data [1]; if (nLength > 0x80) { // composed length nLenLength = nLength - 0x80; nLength = 0; for (int i = 0; i < nLenLength; i++) { nLength *= 256; nLength += data [i + 2]; } } else if (nLength == 0x80) { // undefined length encoding throw new NotSupportedException ("Undefined length encoding."); } m_aValue = new byte [nLength]; Buffer.BlockCopy (data, (2 + nLenLength), m_aValue, 0, nLength); if ((m_nTag & 0x20) == 0x20) { int nStart = (2 + nLenLength); Decode (data, ref nStart, data.Length); } } public int Count { get { if (elist == null) return 0; return elist.Count; } } public byte Tag { get { return m_nTag; } } public int Length { get { if (m_aValue != null) return m_aValue.Length; else return 0; } } public byte[] Value { get { if (m_aValue == null) GetBytes (); return (byte[]) m_aValue.Clone (); } set { if (value != null) m_aValue = (byte[]) value.Clone (); } } private bool CompareArray (byte[] array1, byte[] array2) { bool bResult = (array1.Length == array2.Length); if (bResult) { for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) return false; } } return bResult; } public bool Equals (byte[] asn1) { return CompareArray (this.GetBytes (), asn1); } public bool CompareValue (byte[] value) { return CompareArray (m_aValue, value); } public ASN1 Add (ASN1 asn1) { if (asn1 != null) { if (elist == null) elist = new ArrayList (); elist.Add (asn1); } return asn1; } public virtual byte[] GetBytes () { byte[] val = null; if (m_aValue != null) { val = m_aValue; } else if (Count > 0) { int esize = 0; ArrayList al = new ArrayList (); foreach (ASN1 a in elist) { byte[] item = a.GetBytes (); al.Add (item); esize += item.Length; } val = new byte [esize]; int pos = 0; for (int i=0; i < elist.Count; i++) { byte[] item = (byte[]) al[i]; Buffer.BlockCopy (item, 0, val, pos, item.Length); pos += item.Length; } } byte[] der; int nLengthLen = 0; if (val != null) { int nLength = val.Length; // special for length > 127 if (nLength > 127) { if (nLength <= Byte.MaxValue) { der = new byte [3 + nLength]; Buffer.BlockCopy (val, 0, der, 3, nLength); nLengthLen = 0x81; der[2] = (byte)(nLength); } else if (nLength <= UInt16.MaxValue) { der = new byte [4 + nLength]; Buffer.BlockCopy (val, 0, der, 4, nLength); nLengthLen = 0x82; der[2] = (byte)(nLength >> 8); der[3] = (byte)(nLength); } else if (nLength <= 0xFFFFFF) { // 24 bits der = new byte [5 + nLength]; Buffer.BlockCopy (val, 0, der, 5, nLength); nLengthLen = 0x83; der [2] = (byte)(nLength >> 16); der [3] = (byte)(nLength >> 8); der [4] = (byte)(nLength); } else { // max (Length is an integer) 32 bits der = new byte [6 + nLength]; Buffer.BlockCopy (val, 0, der, 6, nLength); nLengthLen = 0x84; der [2] = (byte)(nLength >> 24); der [3] = (byte)(nLength >> 16); der [4] = (byte)(nLength >> 8); der [5] = (byte)(nLength); } } else { // basic case (no encoding) der = new byte [2 + nLength]; Buffer.BlockCopy (val, 0, der, 2, nLength); nLengthLen = nLength; } if (m_aValue == null) m_aValue = val; } else der = new byte[2]; der[0] = m_nTag; der[1] = (byte)nLengthLen; return der; } // Note: Recursive protected void Decode (byte[] asn1, ref int anPos, int anLength) { byte nTag; int nLength; byte[] aValue; // minimum is 2 bytes (tag + length of 0) while (anPos < anLength - 1) { DecodeTLV (asn1, ref anPos, out nTag, out nLength, out aValue); ASN1 elm = Add (new ASN1 (nTag, aValue)); if ((nTag & 0x20) == 0x20) { int nConstructedPos = anPos; elm.Decode (asn1, ref nConstructedPos, nConstructedPos + nLength); } anPos += nLength; // value length } } // TLV : Tag - Length - Value protected void DecodeTLV (byte[] asn1, ref int pos, out byte tag, out int length, out byte[] content) { tag = asn1 [pos++]; length = asn1 [pos++]; // special case where L contains the Length of the Length + 0x80 if ((length & 0x80) == 0x80) { int nLengthLen = length & 0x7F; length = 0; for (int i = 0; i < nLengthLen; i++) length = length * 256 + asn1 [pos++]; } content = new byte [length]; Buffer.BlockCopy (asn1, pos, content, 0, length); } public ASN1 this [int index] { get { try { if ((elist == null) || (index >= elist.Count)) return null; return (ASN1) elist [index]; } catch (ArgumentOutOfRangeException) { return null; } } } public ASN1 Element (int index, byte anTag) { try { if ((elist == null) || (index >= elist.Count)) return null; ASN1 elm = (ASN1) elist [index]; if (elm.Tag == anTag) return elm; else return null; } catch (ArgumentOutOfRangeException) { return null; } } public override string ToString() { StringBuilder hexLine = new StringBuilder (); // Add tag hexLine.AppendFormat ("Tag: {0} {1}", m_nTag.ToString ("X2"), Environment.NewLine); // Add length hexLine.AppendFormat ("Length: {0} {1}", Value.Length, Environment.NewLine); // Add value hexLine.Append ("Value: "); hexLine.Append (Environment.NewLine); for (int i = 0; i < Value.Length; i++) { hexLine.AppendFormat ("{0} ", Value [i].ToString ("X2")); if ((i+1) % 16 == 0) hexLine.AppendFormat (Environment.NewLine); } return hexLine.ToString (); } public void SaveToFile (string filename) { if (filename == null) throw new ArgumentNullException ("filename"); using (FileStream fs = File.OpenWrite (filename)) { byte[] data = GetBytes (); fs.Write (data, 0, data.Length); fs.Flush (); fs.Close (); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; [assembly: MetadataUpdateHandler(typeof(Microsoft.Extensions.Internal.PropertyHelper))] namespace Microsoft.Extensions.Internal { internal class PropertyHelper { private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; // Delegate type for a by-ref property getter private delegate TValue ByRefFunc<TDeclaringType, TValue>(ref TDeclaringType arg); private static readonly MethodInfo CallPropertyGetterOpenGenericMethod = typeof(PropertyHelper).GetMethod(nameof(CallPropertyGetter), DeclaredOnlyLookup)!; private static readonly MethodInfo CallPropertyGetterByReferenceOpenGenericMethod = typeof(PropertyHelper).GetMethod(nameof(CallPropertyGetterByReference), DeclaredOnlyLookup)!; private static readonly MethodInfo CallNullSafePropertyGetterOpenGenericMethod = typeof(PropertyHelper).GetMethod(nameof(CallNullSafePropertyGetter), DeclaredOnlyLookup)!; private static readonly MethodInfo CallNullSafePropertyGetterByReferenceOpenGenericMethod = typeof(PropertyHelper).GetMethod(nameof(CallNullSafePropertyGetterByReference), DeclaredOnlyLookup)!; private static readonly MethodInfo CallPropertySetterOpenGenericMethod = typeof(PropertyHelper).GetMethod(nameof(CallPropertySetter), DeclaredOnlyLookup)!; // Using an array rather than IEnumerable, as target will be called on the hot path numerous times. private static readonly ConcurrentDictionary<Type, PropertyHelper[]> PropertiesCache = new(); private static readonly ConcurrentDictionary<Type, PropertyHelper[]> VisiblePropertiesCache = new(); // We need to be able to check if a type is a 'ref struct' - but we need to be able to compile // for platforms where the attribute is not defined, like net46. So we can fetch the attribute // by late binding. If the attribute isn't defined, then we assume we won't encounter any // 'ref struct' types. private static readonly Type? IsByRefLikeAttribute = Type.GetType("System.Runtime.CompilerServices.IsByRefLikeAttribute", throwOnError: false); private Action<object, object?>? _valueSetter; private Func<object, object?>? _valueGetter; /// <summary> /// Initializes a fast <see cref="PropertyHelper"/>. /// This constructor does not cache the helper. For caching, use <see cref="GetProperties(Type)"/>. /// </summary> public PropertyHelper(PropertyInfo property) { Property = property ?? throw new ArgumentNullException(nameof(property)); Name = property.Name; } /// <summary> /// Gets the backing <see cref="PropertyInfo"/>. /// </summary> public PropertyInfo Property { get; } /// <summary> /// Gets (or sets in derived types) the property name. /// </summary> public virtual string Name { get; protected set; } public static void ClearCache(Type[]? _) { PropertiesCache.Clear(); VisiblePropertiesCache.Clear(); } /// <summary> /// Gets the property value getter. /// </summary> public Func<object, object?> ValueGetter { get { if (_valueGetter == null) { _valueGetter = MakeFastPropertyGetter(Property); } return _valueGetter; } } /// <summary> /// Gets the property value setter. /// </summary> public Action<object, object?> ValueSetter { get { if (_valueSetter == null) { _valueSetter = MakeFastPropertySetter(Property); } return _valueSetter; } } /// <summary> /// Returns the property value for the specified <paramref name="instance"/>. /// </summary> /// <param name="instance">The object whose property value will be returned.</param> /// <returns>The property value.</returns> public object? GetValue(object instance) { return ValueGetter(instance); } /// <summary> /// Sets the property value for the specified <paramref name="instance" />. /// </summary> /// <param name="instance">The object whose property value will be set.</param> /// <param name="value">The property value.</param> public void SetValue(object instance, object? value) { ValueSetter(instance, value); } /// <summary> /// Creates and caches fast property helpers that expose getters for every public get property on the /// underlying type. /// </summary> /// <param name="typeInfo">The type info to extract property accessors for.</param> /// <returns>A cached array of all public properties of the specified type. /// </returns> public static PropertyHelper[] GetProperties(TypeInfo typeInfo) { return GetProperties(typeInfo.AsType()); } /// <summary> /// Creates and caches fast property helpers that expose getters for every public get property on the /// specified type. /// </summary> /// <param name="type">The type to extract property accessors for.</param> /// <returns>A cached array of all public properties of the specified type. /// </returns> public static PropertyHelper[] GetProperties(Type type) { return GetProperties(type, p => CreateInstance(p), PropertiesCache); } /// <summary> /// <para> /// Creates and caches fast property helpers that expose getters for every non-hidden get property /// on the specified type. /// </para> /// <para> /// <see cref="M:GetVisibleProperties"/> excludes properties defined on base types that have been /// hidden by definitions using the <c>new</c> keyword. /// </para> /// </summary> /// <param name="typeInfo">The type info to extract property accessors for.</param> /// <returns> /// A cached array of all public properties of the specified type. /// </returns> public static PropertyHelper[] GetVisibleProperties(TypeInfo typeInfo) { return GetVisibleProperties(typeInfo.AsType(), p => CreateInstance(p), PropertiesCache, VisiblePropertiesCache); } /// <summary> /// <para> /// Creates and caches fast property helpers that expose getters for every non-hidden get property /// on the specified type. /// </para> /// <para> /// <see cref="M:GetVisibleProperties"/> excludes properties defined on base types that have been /// hidden by definitions using the <c>new</c> keyword. /// </para> /// </summary> /// <param name="type">The type to extract property accessors for.</param> /// <returns> /// A cached array of all public properties of the specified type. /// </returns> public static PropertyHelper[] GetVisibleProperties(Type type) { return GetVisibleProperties(type, p => CreateInstance(p), PropertiesCache, VisiblePropertiesCache); } /// <summary> /// Creates a single fast property getter. The result is not cached. /// </summary> /// <param name="propertyInfo">propertyInfo to extract the getter for.</param> /// <returns>a fast getter.</returns> /// <remarks> /// This method is more memory efficient than a dynamically compiled lambda, and about the /// same speed. /// </remarks> public static Func<object, object?> MakeFastPropertyGetter(PropertyInfo propertyInfo) { Debug.Assert(propertyInfo != null); return MakeFastPropertyGetter( propertyInfo, CallPropertyGetterOpenGenericMethod, CallPropertyGetterByReferenceOpenGenericMethod); } /// <summary> /// Creates a single fast property getter which is safe for a null input object. The result is not cached. /// </summary> /// <param name="propertyInfo">propertyInfo to extract the getter for.</param> /// <returns>a fast getter.</returns> /// <remarks> /// This method is more memory efficient than a dynamically compiled lambda, and about the /// same speed. /// </remarks> public static Func<object, object?> MakeNullSafeFastPropertyGetter(PropertyInfo propertyInfo) { Debug.Assert(propertyInfo != null); return MakeFastPropertyGetter( propertyInfo, CallNullSafePropertyGetterOpenGenericMethod, CallNullSafePropertyGetterByReferenceOpenGenericMethod); } private static Func<object, object?> MakeFastPropertyGetter( PropertyInfo propertyInfo, MethodInfo propertyGetterWrapperMethod, MethodInfo propertyGetterByRefWrapperMethod) { Debug.Assert(propertyInfo != null); // Must be a generic method with a Func<,> parameter Debug.Assert(propertyGetterWrapperMethod != null); Debug.Assert(propertyGetterWrapperMethod.IsGenericMethodDefinition); Debug.Assert(propertyGetterWrapperMethod.GetParameters().Length == 2); // Must be a generic method with a ByRefFunc<,> parameter Debug.Assert(propertyGetterByRefWrapperMethod != null); Debug.Assert(propertyGetterByRefWrapperMethod.IsGenericMethodDefinition); Debug.Assert(propertyGetterByRefWrapperMethod.GetParameters().Length == 2); var getMethod = propertyInfo.GetMethod; Debug.Assert(getMethod != null); Debug.Assert(!getMethod.IsStatic); Debug.Assert(getMethod.GetParameters().Length == 0); // Instance methods in the CLR can be turned into static methods where the first parameter // is open over "target". This parameter is always passed by reference, so we have a code // path for value types and a code path for reference types. if (getMethod.DeclaringType!.IsValueType) { // Create a delegate (ref TDeclaringType) -> TValue return MakeFastPropertyGetter( typeof(ByRefFunc<,>), getMethod, propertyGetterByRefWrapperMethod); } else { // Create a delegate TDeclaringType -> TValue return MakeFastPropertyGetter( typeof(Func<,>), getMethod, propertyGetterWrapperMethod); } } private static Func<object, object?> MakeFastPropertyGetter( Type openGenericDelegateType, MethodInfo propertyGetMethod, MethodInfo openGenericWrapperMethod) { var typeInput = propertyGetMethod.DeclaringType!; var typeOutput = propertyGetMethod.ReturnType; var delegateType = openGenericDelegateType.MakeGenericType(typeInput, typeOutput); var propertyGetterDelegate = propertyGetMethod.CreateDelegate(delegateType); var wrapperDelegateMethod = openGenericWrapperMethod.MakeGenericMethod(typeInput, typeOutput); var accessorDelegate = wrapperDelegateMethod.CreateDelegate( typeof(Func<object, object?>), propertyGetterDelegate); return (Func<object, object?>)accessorDelegate; } /// <summary> /// Creates a single fast property setter for reference types. The result is not cached. /// </summary> /// <param name="propertyInfo">propertyInfo to extract the setter for.</param> /// <returns>a fast getter.</returns> /// <remarks> /// This method is more memory efficient than a dynamically compiled lambda, and about the /// same speed. This only works for reference types. /// </remarks> public static Action<object, object?> MakeFastPropertySetter(PropertyInfo propertyInfo) { Debug.Assert(propertyInfo != null); Debug.Assert(!propertyInfo.DeclaringType!.IsValueType); var setMethod = propertyInfo.SetMethod; Debug.Assert(setMethod != null); Debug.Assert(!setMethod.IsStatic); Debug.Assert(setMethod.ReturnType == typeof(void)); var parameters = setMethod.GetParameters(); Debug.Assert(parameters.Length == 1); // Instance methods in the CLR can be turned into static methods where the first parameter // is open over "target". This parameter is always passed by reference, so we have a code // path for value types and a code path for reference types. var typeInput = setMethod.DeclaringType!; var parameterType = parameters[0].ParameterType; // Create a delegate TDeclaringType -> { TDeclaringType.Property = TValue; } var propertySetterAsAction = setMethod.CreateDelegate(typeof(Action<,>).MakeGenericType(typeInput, parameterType)); var callPropertySetterClosedGenericMethod = CallPropertySetterOpenGenericMethod.MakeGenericMethod(typeInput, parameterType); var callPropertySetterDelegate = callPropertySetterClosedGenericMethod.CreateDelegate( typeof(Action<object, object?>), propertySetterAsAction); return (Action<object, object?>)callPropertySetterDelegate; } /// <summary> /// Given an object, adds each instance property with a public get method as a key and its /// associated value to a dictionary. /// /// If the object is already an <see cref="IDictionary{String, Object}"/> instance, then a copy /// is returned. /// </summary> /// <remarks> /// The implementation of PropertyHelper will cache the property accessors per-type. This is /// faster when the same type is used multiple times with ObjectToDictionary. /// </remarks> public static IDictionary<string, object?> ObjectToDictionary(object? value) { if (value is IDictionary<string, object?> dictionary) { return new Dictionary<string, object?>(dictionary, StringComparer.OrdinalIgnoreCase); } dictionary = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase); if (value is not null) { foreach (var helper in GetProperties(value.GetType())) { dictionary[helper.Name] = helper.GetValue(value); } } return dictionary; } private static PropertyHelper CreateInstance(PropertyInfo property) { return new PropertyHelper(property); } // Called via reflection private static object? CallPropertyGetter<TDeclaringType, TValue>( Func<TDeclaringType, TValue> getter, object target) { return getter((TDeclaringType)target); } // Called via reflection private static object? CallPropertyGetterByReference<TDeclaringType, TValue>( ByRefFunc<TDeclaringType, TValue> getter, object target) { var unboxed = (TDeclaringType)target; return getter(ref unboxed); } // Called via reflection private static object? CallNullSafePropertyGetter<TDeclaringType, TValue>( Func<TDeclaringType, TValue> getter, object target) { if (target == null) { return null; } return getter((TDeclaringType)target); } // Called via reflection private static object? CallNullSafePropertyGetterByReference<TDeclaringType, TValue>( ByRefFunc<TDeclaringType, TValue> getter, object target) { if (target == null) { return null; } var unboxed = (TDeclaringType)target; return getter(ref unboxed); } private static void CallPropertySetter<TDeclaringType, TValue>( Action<TDeclaringType, TValue> setter, object target, object value) { setter((TDeclaringType)target, (TValue)value); } protected static PropertyHelper[] GetVisibleProperties( Type type, Func<PropertyInfo, PropertyHelper> createPropertyHelper, ConcurrentDictionary<Type, PropertyHelper[]> allPropertiesCache, ConcurrentDictionary<Type, PropertyHelper[]> visiblePropertiesCache) { if (visiblePropertiesCache.TryGetValue(type, out var result)) { return result; } // The simple and common case, this is normal POCO object - no need to allocate. var allPropertiesDefinedOnType = true; var allProperties = GetProperties(type, createPropertyHelper, allPropertiesCache); foreach (var propertyHelper in allProperties) { if (propertyHelper.Property.DeclaringType != type) { allPropertiesDefinedOnType = false; break; } } if (allPropertiesDefinedOnType) { result = allProperties; visiblePropertiesCache.TryAdd(type, result); return result; } // There's some inherited properties here, so we need to check for hiding via 'new'. var filteredProperties = new List<PropertyHelper>(allProperties.Length); foreach (var propertyHelper in allProperties) { var declaringType = propertyHelper.Property.DeclaringType; if (declaringType == type) { filteredProperties.Add(propertyHelper); continue; } // If this property was declared on a base type then look for the definition closest to the // the type to see if we should include it. var ignoreProperty = false; // Walk up the hierarchy until we find the type that actually declares this // PropertyInfo. Type? currentType = type; while (currentType != null && currentType != declaringType) { // We've found a 'more proximal' public definition var declaredProperty = currentType.GetProperty(propertyHelper.Name, DeclaredOnlyLookup); if (declaredProperty != null) { ignoreProperty = true; break; } currentType = currentType.BaseType; } if (!ignoreProperty) { filteredProperties.Add(propertyHelper); } } result = filteredProperties.ToArray(); visiblePropertiesCache.TryAdd(type, result); return result; } protected static PropertyHelper[] GetProperties( Type type, Func<PropertyInfo, PropertyHelper> createPropertyHelper, ConcurrentDictionary<Type, PropertyHelper[]> cache) { // Unwrap nullable types. This means Nullable<T>.Value and Nullable<T>.HasValue will not be // part of the sequence of properties returned by this method. type = Nullable.GetUnderlyingType(type) ?? type; if (!cache.TryGetValue(type, out var helpers)) { // We avoid loading indexed properties using the Where statement. var properties = type.GetRuntimeProperties().Where(p => IsInterestingProperty(p)); if (type.IsInterface) { // Reflection does not return information about inherited properties on the interface itself. properties = properties.Concat(type.GetInterfaces().SelectMany( interfaceType => interfaceType.GetRuntimeProperties().Where(p => IsInterestingProperty(p)))); } helpers = properties.Select(p => createPropertyHelper(p)).ToArray(); cache.TryAdd(type, helpers); } return helpers; } private static bool IsInterestingProperty(PropertyInfo property) { // For improving application startup time, do not use GetIndexParameters() api early in this check as it // creates a copy of parameter array and also we would like to check for the presence of a get method // and short circuit asap. return property.GetMethod != null && property.GetMethod.IsPublic && !property.GetMethod.IsStatic && // PropertyHelper can't work with ref structs. !IsRefStructProperty(property) && // Indexed properties are not useful (or valid) for grabbing properties off an object. property.GetMethod.GetParameters().Length == 0; } // PropertyHelper can't really interact with ref-struct properties since they can't be // boxed and can't be used as generic types. We just ignore them. // // see: https://github.com/aspnet/Mvc/issues/8545 private static bool IsRefStructProperty(PropertyInfo property) { return IsByRefLikeAttribute != null && property.PropertyType.IsValueType && property.PropertyType.IsDefined(IsByRefLikeAttribute); } } }
using System; using System.Collections.Generic; using it.unifi.dsi.stlab.utilities.times_of_computation; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance; using System.Text; namespace it.unifi.dsi.stlab.networkreasoner.gas.system.state_visitors.summary_table { public class FluidDynamicSystemStateVisitorBuildSummaryTable : FluidDynamicSystemStateVisitorWithSystemName { #region FluidDynamicSystemStateVisitorWithSystemName implementation public string SystemName{ get; set; } public void forBareSystemState (FluidDynamicSystemStateBare fluidDynamicSystemStateBare) { throw new System.NotImplementedException (); } public void forUnsolvedSystemState (FluidDynamicSystemStateUnsolved fluidDynamicSystemStateUnsolved) { throw new System.NotImplementedException (); } public void forMathematicallySolvedState (FluidDynamicSystemStateMathematicallySolved fluidDynamicSystemStateMathematicallySolved) { onComputationFinished (SystemName, fluidDynamicSystemStateMathematicallySolved.MutationResult); } public void forNegativeLoadsCorrectedState (FluidDynamicSystemStateNegativeLoadsCorrected fluidDynamicSystemStateNegativeLoadsCorrected) { onComputationFinished (SystemName, fluidDynamicSystemStateNegativeLoadsCorrected.FluidDynamicSystemStateMathematicallySolved.MutationResult); } #endregion Dictionary<String, Dictionary<int, SummaryTableItem>> SummaryTableNodes{ get; set; } Dictionary<String, Dictionary<int, SummaryTableItem>> SummaryTableEdges{ get; set; } TimeOfComputationHandling ComputationHandlingTime{ get; set; } Dictionary<string, int> NodesPositionsByItemIdentifiers { get; set; } Dictionary<string, int> EdgesPositionsByItemIdentifiers { get; set; } public FluidDynamicSystemStateVisitorBuildSummaryTable () { SummaryTableEdges = new Dictionary<string, Dictionary<int, SummaryTableItem>> (); SummaryTableNodes = new Dictionary<string, Dictionary<int, SummaryTableItem>> (); ComputationHandlingTime = new TimeOfComputationHandlingFirstOne (); NodesPositionsByItemIdentifiers = new Dictionary<string, int> (); EdgesPositionsByItemIdentifiers = new Dictionary<string, int> (); } protected virtual int positionOfItemIn ( String tableItemIdentifier, Dictionary<string, int> positionsByIdentifiers) { return positionsByIdentifiers [tableItemIdentifier]; } protected virtual void buildColumnPositionsDictionaryOnlyOnFirstTimeThisMethodIsCalled ( OneStepMutationResults results) { var columnPositionsForTableSummaryItemsAction = new ActionTimeComputationOnFirstTime (); columnPositionsForTableSummaryItemsAction.Action = () => { assignPositionsToIdentifiers ( results.StartingUnsolvedState.Nodes, NodesPositionsByItemIdentifiers); assignPositionsToIdentifiers ( results.StartingUnsolvedState.Edges, EdgesPositionsByItemIdentifiers); }; ComputationHandlingTime.perform ( columnPositionsForTableSummaryItemsAction); } protected virtual void assignPositionsToIdentifiers<T> ( List<T> abstractComputationItems, Dictionary<string, int> positionsByIdentifiers) where T:AbstractItemForNetwonRaphsonSystem { int position = 0; abstractComputationItems.ForEach (aNode => { positionsByIdentifiers.Add (aNode.Identifier, position); position = position + 1; } ); } protected virtual void onComputationFinished ( string systemName, OneStepMutationResults results) { buildColumnPositionsDictionaryOnlyOnFirstTimeThisMethodIsCalled (results); var dimensionalUnknowns = results.makeUnknownsDimensional ().WrappedObject; var summaryTableNodesForCurrentSystem = new Dictionary<int, SummaryTableItem> (); var summaryTableEdgesForCurrentSystem = new Dictionary<int, SummaryTableItem> (); Dictionary<NodeForNetwonRaphsonSystem, double> sumOfQsByNodes = new Dictionary<NodeForNetwonRaphsonSystem, double> (); results.StartingUnsolvedState.Nodes.ForEach ( aNode => sumOfQsByNodes.Add (aNode, 0)); results.StartingUnsolvedState.Edges.ForEach ( anEdge => { double? Qvalue = null; if (results.Qvector.containsKey (anEdge)) { Qvalue = results.Qvector.valueAt (anEdge); sumOfQsByNodes [anEdge.StartNode] -= Qvalue.Value; sumOfQsByNodes [anEdge.EndNode] += Qvalue.Value; } double? VelocityValue = null; if (results.VelocityVector.containsKey (anEdge)) { VelocityValue = results.VelocityVector.valueAt (anEdge); } var edgePosition = positionOfItemIn (anEdge.Identifier, EdgesPositionsByItemIdentifiers); EdgeForSummaryTable summaryEdge = new EdgeForSummaryTable{ Identifier = anEdge.Identifier, IdentifierAsLinkNotation = anEdge.identifierUsingLinkNotation(), Qvalue = Qvalue, VelocityValue = VelocityValue, Position = edgePosition }; summaryTableEdgesForCurrentSystem.Add (edgePosition, summaryEdge); } ); foreach (var pair in sumOfQsByNodes) { int nodePosition = positionOfItemIn (pair.Key.Identifier, NodesPositionsByItemIdentifiers); NodeForSummaryTable summaryNode = new NodeForSummaryTable{ Position = nodePosition, Identifier = pair.Key.Identifier, QvalueSum = pair.Value, DimensionalPressure = dimensionalUnknowns.valueAt(pair.Key) }; summaryTableNodesForCurrentSystem.Add (nodePosition, summaryNode); } SummaryTableEdges.Add (systemName, summaryTableEdgesForCurrentSystem); SummaryTableNodes.Add (systemName, summaryTableNodesForCurrentSystem); ComputationHandlingTime = ComputationHandlingTime.advance (); } public virtual String buildSummaryContent () { StringBuilder table = new StringBuilder (); // we should check that they contains really the same items System.Diagnostics.Debug.Assert (SummaryTableEdges.Keys.Count == SummaryTableNodes.Keys.Count ); // here we've choosed SummaryTableEdges.Keys as argument to // build the strategy but its the same to use SummaryTableNodes.Keys SummaryTableBuildingStrategy strategyDependentOnRunAnalysis = buildStrategy (SummaryTableEdges.Keys); strategyDependentOnRunAnalysis.collectNodesTableUsingInto (SummaryTableNodes, table); table.AppendFormat ("\n\n"); strategyDependentOnRunAnalysis.collectEdgesTableUsingInto (SummaryTableEdges, table); return table.ToString (); } // here we consume a dictionary that is the same as the private field // since that field is private hence not accessible in a subclass. protected virtual SummaryTableBuildingStrategy buildStrategy ( ICollection<string> summaryTableItems) { SummaryTableBuildingStrategy strategy = null; if (summaryTableItems.Count == 1) { strategy = new SummaryTableBuildingStrategyForSingleRunAnalysis (); } else { strategy = new SummaryTableBuildingStrategyForMultiRunAnalysis (); } return strategy; } } }
using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Web; namespace bv.common.Core { public class Utils { public const long SEARCH_MODE_ID = -2; /// ----------------------------------------------------------------------------- /// <summary> /// Returns safe string representation of object. /// </summary> /// <param name="o"> object that should be converted to string </param> /// <returns> /// Returns string representation of passed object. If passed object is <b>Nothing</b> or <b>DBNull.Value</b> the /// method returns empty string. /// </returns> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static string Str(object o) { return Str(o, ""); } public static string Str(object o, string defaultString) { if (o == null || o == DBNull.Value) { return defaultString; } return o.ToString(); } public static double Dbl(object o) { if (o == null || o == DBNull.Value) { return 0.0; } try { return Convert.ToDouble(o); } catch (Exception) { return 0.0; } } /// ----------------------------------------------------------------------------- /// <summary> /// Checks if the passed object represents the valid typed object. /// </summary> /// <param name="o"> object to check </param> /// <returns> /// False if passed object is <b>Nothing</b> or <b>DBNull.Value</b> or its string representation is empty string /// and True in other case. /// </returns> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static bool IsEmpty(object o) { if (o == null || o == DBNull.Value) { return true; } if (string.IsNullOrWhiteSpace(o.ToString())) { return true; } return false; } /// ----------------------------------------------------------------------------- /// <summary> /// Appends the default string with other separating them with some separator /// </summary> /// <param name="s"> default string to append </param> /// <param name="val"> string that should be appended </param> /// <param name="separator"> string that should separate default and appended strings </param> /// <remarks> /// method inserts the separator between strings only if default string is not empty. /// </remarks> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static void AppendLine(ref string s, object val, string separator) { if (val == DBNull.Value || val.ToString().Trim().Length == 0) { return; } if (s.Length == 0) { s += val.ToString(); } else { s += separator + val; } } public static string Join(string separator, IEnumerable collection) { var result = new StringBuilder(); object item; foreach (object tempLoopVarItem in collection) { item = tempLoopVarItem; if (item == null || string.IsNullOrWhiteSpace(item.ToString())) { continue; } if (result.Length > 0) { result.Append(separator); } result.Append(item.ToString()); } return result.ToString(); } /// ----------------------------------------------------------------------------- /// <summary> /// Checks if directory exists and creates it if it is absent /// </summary> /// <param name="dir"> directory to check </param> /// <returns> /// Returns <b>True</b> if requested directory exists or was created successfully and <b>False</b> if requested /// directory can't be created /// </returns> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static bool ForceDirectories(string dir) { int pos = 0; try { do { pos = dir.IndexOf(Path.DirectorySeparatorChar, pos); if (pos < 0) { break; } string dirName = dir.Substring(0, pos); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } pos++; } while (true); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return Directory.Exists(dir); } catch { return false; } } public static Bitmap LoadBitmapFromResource(string resName, Type aType) { //open the executing assembly Assembly oAssembly = Assembly.GetAssembly(aType); //create stream for image (icon) in assembly Stream oStream = oAssembly.GetManifestResourceStream(resName); //create new bitmap from stream if (oStream != null) { var oBitmap = (Bitmap) (Image.FromStream(oStream)); return oBitmap; } return null; } public static bool IsGuid(object g) { string s = Str(g); if (s.Length != 36) { return false; } try { new Guid(s); return true; } catch (Exception) { return false; } } /* public static bool IsEIDSS { get { return (ApplicationContext.ApplicationName.ToLowerInvariant() == "eidss"); } } public static bool IsPACS { get { return (ApplicationContext.ApplicationName.ToLowerInvariant() == "pacs_main"); } } */ public static T CheckNotNull<T>(T param, string paramName) { if (ReferenceEquals(param, null)) { throw (new ArgumentNullException(paramName)); } return param; } public static string CheckNotNullOrEmpty(string param, string paramName) { if (CheckNotNull(param, paramName) == string.Empty) { throw (new ArgumentException(paramName + " cannot be empty string")); } return param; } public static string GetParentDirectoryPath(string dirName) { string appLocation = GetExecutingPath(); dirName = dirName.ToLowerInvariant(); var dir = new DirectoryInfo(Path.GetDirectoryName(appLocation)); while (dir != null && dir.Name.ToLowerInvariant() != dirName) { foreach (DirectoryInfo subDir in dir.GetDirectories()) { if (subDir.Name.ToLower(CultureInfo.InvariantCulture) == dirName) { return subDir.FullName + "\\"; } } dir = dir.Parent; } if (dir != null) { return string.Format("{0}\\", dir.FullName); } return null; } //It is assumed that assembly is placed in the project that is located in solution directory; public static string GetSolutionPath() { string binPath = GetParentDirectoryPath("bin"); var dir = new DirectoryInfo(Path.GetDirectoryName(binPath)); return string.Format("{0}\\", dir.Parent.Parent.FullName); } public static string GetDesktopExecutingPath() { DirectoryInfo appDir; Assembly asm = Assembly.GetExecutingAssembly(); if (!asm.GetName().Name.StartsWith("nunit")) { appDir = new DirectoryInfo(Path.GetDirectoryName(GetAssemblyLocation(asm))); return string.Format("{0}\\", appDir.FullName); } asm = Assembly.GetCallingAssembly(); appDir = new DirectoryInfo(Path.GetDirectoryName(GetAssemblyLocation(asm))); return string.Format("{0}\\", appDir.FullName); } public static string GetExecutingPath() { DirectoryInfo appDir; if (HttpContext.Current != null) { try { appDir = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath); if (Directory.Exists(appDir.FullName)) { return string.Format("{0}", appDir.FullName); } } catch { } } return GetDesktopExecutingPath(); } public static string GetAssemblyLocation(Assembly asm) { if (asm.CodeBase.StartsWith("file:///")) { return asm.CodeBase.Substring(8).Replace("/", "\\"); } return asm.Location; } public static string GetFilePathNearAssembly(Assembly asm, string fileName) { string location = ConvertFileName(asm.Location); string locationFileName = string.Format(@"{0}\{1}", Path.GetDirectoryName(location), fileName); if (File.Exists(locationFileName)) { return locationFileName; } string codeBase = ConvertFileName(asm.CodeBase); string codeBaseFileName = string.Format(@"{0}\{1}", Path.GetDirectoryName(codeBase), fileName); if (File.Exists(codeBaseFileName)) { return codeBaseFileName; } throw new FileNotFoundException( string.Format("Could not find file placed neither {0} nor {1}", locationFileName, codeBaseFileName), fileName); } public static string ConvertFileName(string fileName) { if (fileName.StartsWith("file:///")) { return fileName.Substring(8).Replace("/", "\\"); } return fileName; } public static string GetConfigFileName() { if (HttpContext.Current != null) { return "Web.config"; } Assembly asm = Assembly.GetEntryAssembly(); if (asm != null) { return Path.GetFileName(asm.Location) + ".config"; } return ""; } public static long? ToNullableLong(object val) { if (IsEmpty(val)) { return null; } long res; if (long.TryParse(val.ToString(), out res)) return res; return null; } public static int? ToNullableInt(object val) { if (IsEmpty(val)) { return null; } int res; if (int.TryParse(val.ToString(), out res)) return res; return null; } public static bool IsCalledFromUnitTest() { var stack = new StackTrace(); int frameCount = stack.FrameCount - 1; for (int frame = 0; frame <= frameCount; frame++) { StackFrame stackFrame = stack.GetFrame(frame); if (stackFrame != null) { MethodBase method = stackFrame.GetMethod(); if (method != null) { string moduleName = method.Module.Name; if (moduleName.Contains("tests")) { return true; } } } } return false; } private static string GetAssemblyCodeBaseLocation(Assembly asm) { if (asm.CodeBase.StartsWith("file:///")) { return asm.CodeBase.Substring(8).Replace("/", "\\"); } return asm.Location; } public static string GetExecutingAssembly() { string app; if (HttpContext.Current != null) { return HttpContext.Current.Request.PhysicalApplicationPath; } Assembly asm = Assembly.GetEntryAssembly(); if (asm == null) { asm = Assembly.GetExecutingAssembly(); } if (!asm.GetName().Name.StartsWith("nunit")) { app = GetAssemblyCodeBaseLocation(asm); if (app != null) { return app; } } asm = Assembly.GetCallingAssembly(); app = GetAssemblyCodeBaseLocation(asm); if (app != null) { return app; } return null; } public static object ToDbValue(object val) { if (val == null) { return DBNull.Value; } return val; } public static long ToLong(object o, long defValue = 0) { if (o == null || o == DBNull.Value) { return defValue; } try { return Convert.ToInt64(o); } catch (Exception) { return defValue; } } public static long ToInt(object o, int defValue = 0) { if (o == null || o == DBNull.Value) { return defValue; } try { return Convert.ToInt32(o); } catch (Exception) { return defValue; } } public static string GetCurrentMethodName() { return GetMethodName(2); } public static string GetPreviousMethodName() { return GetMethodName(3); } private static string GetMethodName(int index) { var stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(index); string name = stackFrame != null ? stackFrame.GetMethod().Name : "CANNOT_GET_METHOD_NAME"; return name; } public static object SafeDate(object date) { return IsEmpty(date) ? "..." : date; } public static DateTime? ToDateNullable(string date) { if(IsEmpty(date)) return null; DateTime res; if (DateTime.TryParse(date, out res)) return res; return null; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ToolPackage; using Microsoft.Extensions.EnvironmentAbstractions; using System.Text.Json.Serialization; using NuGet.Frameworks; using NuGet.Versioning; using System.Text.Json; using System.Text; using System.Buffers; namespace Microsoft.DotNet.ToolManifest { internal class ToolManifestEditor : IToolManifestEditor { private readonly IDangerousFileDetector _dangerousFileDetector; private readonly IFileSystem _fileSystem; private const int SupportedToolManifestFileVersion = 1; private const int DefaultToolManifestFileVersion = 1; private const string JsonPropertyVersion = "version"; private const string JsonPropertyIsRoot = "isRoot"; private const string JsonPropertyCommands = "commands"; private const string JsonPropertyTools = "tools"; public ToolManifestEditor(IFileSystem fileSystem = null, IDangerousFileDetector dangerousFileDetector = null) { _dangerousFileDetector = dangerousFileDetector ?? new DangerousFileDetector(); _fileSystem = fileSystem ?? new FileSystemWrapper(); } public void Add( FilePath manifest, PackageId packageId, NuGetVersion nuGetVersion, ToolCommandName[] toolCommandNames) { SerializableLocalToolsManifest deserializedManifest = DeserializeLocalToolsManifest(manifest); List<ToolManifestPackage> toolManifestPackages = GetToolManifestPackageFromOneManifestFile(deserializedManifest, manifest, manifest.GetDirectoryPath()); var existing = toolManifestPackages.Where(t => t.PackageId.Equals(packageId)).ToArray(); if (existing.Any()) { var existingPackage = existing.Single(); if (existingPackage.PackageId.Equals(packageId) && existingPackage.Version == nuGetVersion && CommandNamesEqual(existingPackage.CommandNames, toolCommandNames)) { return; } throw new ToolManifestException(string.Format( LocalizableStrings.ManifestPackageIdCollision, existingPackage.Version.ToNormalizedString(), existingPackage.PackageId.ToString(), manifest.Value, nuGetVersion.ToNormalizedString())); } if (deserializedManifest.Tools == null) { deserializedManifest.Tools = new List<SerializableLocalToolSinglePackage>(); } deserializedManifest.Tools.Add( new SerializableLocalToolSinglePackage { PackageId = packageId.ToString(), Version = nuGetVersion.ToNormalizedString(), Commands = toolCommandNames.Select(c => c.Value).ToArray() }); _fileSystem.File.WriteAllText(manifest.Value, deserializedManifest.ToJson()); } public void Edit( FilePath manifest, PackageId packageId, NuGetVersion newNuGetVersion, ToolCommandName[] newToolCommandNames) { SerializableLocalToolsManifest deserializedManifest = DeserializeLocalToolsManifest(manifest); List<ToolManifestPackage> toolManifestPackages = GetToolManifestPackageFromOneManifestFile(deserializedManifest, manifest, manifest.GetDirectoryPath()); var existing = toolManifestPackages.Where(t => t.PackageId.Equals(packageId)).ToArray(); if (existing.Any()) { var existingPackage = existing.Single(); if (existingPackage.PackageId.Equals(packageId)) { var toEdit = deserializedManifest.Tools.Single(t => new PackageId(t.PackageId).Equals(packageId)); toEdit.Version = newNuGetVersion.ToNormalizedString(); toEdit.Commands = newToolCommandNames.Select(c => c.Value).ToArray(); } } else { throw new ArgumentException($"Manifest {manifest.Value} does not contain package id '{packageId}'."); } _fileSystem.File.WriteAllText(manifest.Value, deserializedManifest.ToJson()); } public (List<ToolManifestPackage> content, bool isRoot) Read(FilePath manifest, DirectoryPath correspondingDirectory) { if (_dangerousFileDetector.IsDangerous(manifest.Value)) { throw new ToolManifestException( string.Format(LocalizableStrings.ManifestHasMarkOfTheWeb, manifest.Value)); } SerializableLocalToolsManifest deserializedManifest = DeserializeLocalToolsManifest(manifest); List<ToolManifestPackage> toolManifestPackages = GetToolManifestPackageFromOneManifestFile( deserializedManifest, manifest, correspondingDirectory); return (toolManifestPackages, deserializedManifest.IsRoot.Value); } private SerializableLocalToolsManifest DeserializeLocalToolsManifest(FilePath possibleManifest) { var serializableLocalToolsManifest = new SerializableLocalToolsManifest(); try { using (Stream jsonStream = _fileSystem.File.OpenRead(possibleManifest.Value)) using (JsonDocument doc = JsonDocument.Parse(jsonStream)) { JsonElement root = doc.RootElement; if (root.TryGetInt32Value(JsonPropertyVersion, out var version)) { serializableLocalToolsManifest.Version = version; } if (root.TryGetBooleanValue(JsonPropertyIsRoot, out var isRoot)) { serializableLocalToolsManifest.IsRoot = isRoot; } if (root.TryGetProperty(JsonPropertyTools, out var tools)) { serializableLocalToolsManifest.Tools = new List<SerializableLocalToolSinglePackage>(); if (tools.ValueKind != JsonValueKind.Object) { throw new ToolManifestException( string.Format(LocalizableStrings.UnexpectedTypeInJson, JsonValueKind.Object.ToString(), JsonPropertyTools)); } foreach (var toolJson in tools.EnumerateObject()) { var serializableLocalToolSinglePackage = new SerializableLocalToolSinglePackage(); serializableLocalToolSinglePackage.PackageId = toolJson.Name; if (toolJson.Value.TryGetStringValue(JsonPropertyVersion, out var versionJson)) { serializableLocalToolSinglePackage.Version = versionJson; } var commands = new List<string>(); if (toolJson.Value.TryGetProperty(JsonPropertyCommands, out var commandsJson)) { if (commandsJson.ValueKind != JsonValueKind.Array) { throw new ToolManifestException( string.Format(LocalizableStrings.UnexpectedTypeInJson, JsonValueKind.Array.ToString(), JsonPropertyCommands)); } foreach (var command in commandsJson.EnumerateArray()) { if (command.ValueKind != JsonValueKind.String) { throw new ToolManifestException( string.Format(LocalizableStrings.UnexpectedTypeInJson, JsonValueKind.String.ToString(), "command")); } commands.Add(command.GetString()); } serializableLocalToolSinglePackage.Commands = commands.ToArray(); } serializableLocalToolsManifest.Tools.Add(serializableLocalToolSinglePackage); } } } return serializableLocalToolsManifest; } catch (Exception e) when ( e is JsonException || e is FormatException) { throw new ToolManifestException(string.Format(LocalizableStrings.JsonParsingError, possibleManifest.Value, e.Message)); } } private List<ToolManifestPackage> GetToolManifestPackageFromOneManifestFile( SerializableLocalToolsManifest deserializedManifest, FilePath path, DirectoryPath correspondingDirectory) { List<ToolManifestPackage> result = new List<ToolManifestPackage>(); var errors = new List<string>(); ValidateVersion(deserializedManifest, errors); if (!deserializedManifest.IsRoot.HasValue) { errors.Add(string.Format(LocalizableStrings.ManifestMissingIsRoot, path.Value)); } if (deserializedManifest.Tools != null && deserializedManifest.Tools.Count > 0) { var duplicateKeys = deserializedManifest.Tools.GroupBy(x => x.PackageId) .Where(group => group.Count() > 1) .Select(group => group.Key); if (duplicateKeys.Any()) { errors.Add(string.Format(LocalizableStrings.MultipleSamePackageId, string.Join(", ", duplicateKeys))); } } foreach (var tools in deserializedManifest.Tools ?? new List<SerializableLocalToolSinglePackage>()) { var packageLevelErrors = new List<string>(); var packageIdString = tools.PackageId; var packageId = new PackageId(packageIdString); string versionString = tools.Version; NuGetVersion version = null; if (versionString is null) { packageLevelErrors.Add(LocalizableStrings.ToolMissingVersion); } else { if (!NuGetVersion.TryParse(versionString, out version)) { packageLevelErrors.Add(string.Format(LocalizableStrings.VersionIsInvalid, versionString)); } } if (tools.Commands == null || (tools.Commands != null && tools.Commands.Length == 0)) { packageLevelErrors.Add(LocalizableStrings.FieldCommandsIsMissing); } if (packageLevelErrors.Any()) { var joinedWithIndentation = string.Join(Environment.NewLine, packageLevelErrors.Select(e => "\t\t" + e)); errors.Add(string.Format(LocalizableStrings.InPackage, packageId.ToString(), joinedWithIndentation)); } else { result.Add(new ToolManifestPackage( packageId, version, ToolCommandName.Convert(tools.Commands), correspondingDirectory)); } } if (errors.Any()) { throw new ToolManifestException( string.Format(LocalizableStrings.InvalidManifestFilePrefix, path.Value, string.Join(Environment.NewLine, errors.Select(e => "\t" + e)))); } return result; } private static void ValidateVersion(SerializableLocalToolsManifest deserializedManifest, List<string> errors) { var deserializedManifestVersion = deserializedManifest.Version; if (deserializedManifestVersion == null) { deserializedManifestVersion = DefaultToolManifestFileVersion; } if (deserializedManifestVersion == 0) { errors.Add(LocalizableStrings.ManifestVersion0); } if (deserializedManifestVersion > SupportedToolManifestFileVersion) { errors.Add( string.Format( LocalizableStrings.ManifestVersionHigherThanSupported, deserializedManifestVersion, SupportedToolManifestFileVersion)); } } private class SerializableLocalToolSinglePackage { public string PackageId { get; set; } public string Version { get; set; } public string[] Commands { get; set; } } private static bool CommandNamesEqual(ToolCommandName[] left, ToolCommandName[] right) { if (left == null) { return right == null; } if (right == null) { return false; } return left.SequenceEqual(right); } private class SerializableLocalToolsManifest { public int? Version { get; set; } public bool? IsRoot { get; set; } public List<SerializableLocalToolSinglePackage> Tools { get; set; } public string ToJson() { var arrayBufferWriter = new ArrayBufferWriter<byte>(); using (var writer = new Utf8JsonWriter(arrayBufferWriter, new JsonWriterOptions { Indented = true })) { writer.WriteStartObject(); if (Version.HasValue) { writer.WriteNumber(propertyName: JsonPropertyVersion, value: Version.Value); } if (IsRoot.HasValue) { writer.WriteBoolean(JsonPropertyIsRoot, IsRoot.Value); } writer.WriteStartObject(JsonPropertyTools); foreach (var tool in Tools) { writer.WriteStartObject(tool.PackageId); writer.WriteString(JsonPropertyVersion, tool.Version); writer.WriteStartArray(JsonPropertyCommands); foreach (var toolCommandName in tool.Commands) { writer.WriteStringValue(toolCommandName); } writer.WriteEndArray(); writer.WriteEndObject(); } writer.WriteEndObject(); writer.WriteEndObject(); writer.Flush(); return Encoding.UTF8.GetString(arrayBufferWriter.WrittenMemory.ToArray()); } } } public void Remove(FilePath manifest, PackageId packageId) { SerializableLocalToolsManifest serializableLocalToolsManifest = DeserializeLocalToolsManifest(manifest); List<ToolManifestPackage> toolManifestPackages = GetToolManifestPackageFromOneManifestFile( serializableLocalToolsManifest, manifest, manifest.GetDirectoryPath()); if (!toolManifestPackages.Any(t => t.PackageId.Equals(packageId))) { throw new ToolManifestException(string.Format( LocalizableStrings.CannotFindPackageIdInManifest, packageId)); } if (serializableLocalToolsManifest.Tools == null) { throw new InvalidOperationException( $"Invalid state {nameof(serializableLocalToolsManifest)} if out of sync with {nameof(toolManifestPackages)}. " + $"{nameof(serializableLocalToolsManifest)} cannot be null when " + $"the package id can be found in {nameof(toolManifestPackages)}."); } serializableLocalToolsManifest.Tools = serializableLocalToolsManifest.Tools .Where(package => !package.PackageId.Equals(packageId.ToString(), StringComparison.Ordinal)) .ToList(); _fileSystem.File.WriteAllText( manifest.Value, serializableLocalToolsManifest.ToJson()); } } }
using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Codecs.BlockTerms { /* * 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. */ /// <summary> /// Handles a terms dict, but decouples all details of /// doc/freqs/positions reading to an instance of /// <see cref="PostingsReaderBase"/>. This class is reusable for /// codecs that use a different format for /// docs/freqs/positions (though codecs are also free to /// make their own terms dict impl). /// <para/> /// This class also interacts with an instance of /// <see cref="TermsIndexReaderBase"/>, to abstract away the specific /// implementation of the terms dict index. /// <para/> /// @lucene.experimental /// </summary> public class BlockTermsReader : FieldsProducer { // Open input to the main terms dict file (_X.tis) private readonly IndexInput input; // Reads the terms dict entries, to gather state to // produce DocsEnum on demand private readonly PostingsReaderBase postingsReader; private readonly IDictionary<string, FieldReader> fields = new JCG.SortedDictionary<string, FieldReader>(StringComparer.Ordinal); // Reads the terms index private TermsIndexReaderBase indexReader; // keeps the dirStart offset private long dirOffset; private readonly int version; /// <summary> /// Used as a key for the terms cache /// </summary> private class FieldAndTerm : DoubleBarrelLRUCache.CloneableKey { public string Field { get; set; } private BytesRef Term { get; set; } public FieldAndTerm() { } private FieldAndTerm(FieldAndTerm other) { Field = other.Field; Term = BytesRef.DeepCopyOf(other.Term); } public override bool Equals(object other) { var o = (FieldAndTerm)other; return o.Field.Equals(Field, StringComparison.Ordinal) && Term.BytesEquals(o.Term); } public override object Clone() { return new FieldAndTerm(this); } public override int GetHashCode() { return Field.GetHashCode() * 31 + Term.GetHashCode(); } } // private string segment; public BlockTermsReader(TermsIndexReaderBase indexReader, Directory dir, FieldInfos fieldInfos, SegmentInfo info, PostingsReaderBase postingsReader, IOContext context, string segmentSuffix) { this.postingsReader = postingsReader; // this.segment = segment; input = dir.OpenInput(IndexFileNames.SegmentFileName(info.Name, segmentSuffix, BlockTermsWriter.TERMS_EXTENSION), context); bool success = false; try { version = ReadHeader(input); // Have PostingsReader init itself postingsReader.Init(input); // Read per-field details SeekDir(input, dirOffset); int numFields = input.ReadVInt32(); if (numFields < 0) { throw new CorruptIndexException("invalid number of fields: " + numFields + " (resource=" + input + ")"); } for (int i = 0; i < numFields; i++) { int field = input.ReadVInt32(); long numTerms = input.ReadVInt64(); Debug.Assert(numTerms >= 0); long termsStartPointer = input.ReadVInt64(); FieldInfo fieldInfo = fieldInfos.FieldInfo(field); long sumTotalTermFreq = fieldInfo.IndexOptions == IndexOptions.DOCS_ONLY ? -1 : input.ReadVInt64(); long sumDocFreq = input.ReadVInt64(); int docCount = input.ReadVInt32(); int longsSize = version >= BlockTermsWriter.VERSION_META_ARRAY ? input.ReadVInt32() : 0; if (docCount < 0 || docCount > info.DocCount) { // #docs with field must be <= #docs throw new CorruptIndexException("invalid docCount: " + docCount + " maxDoc: " + info.DocCount + " (resource=" + input + ")"); } if (sumDocFreq < docCount) { // #postings must be >= #docs with field throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount + " (resource=" + input + ")"); } if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq + " (resource=" + input + ")"); } FieldReader previous = fields.Put(fieldInfo.Name, new FieldReader(this, fieldInfo, numTerms, termsStartPointer, sumTotalTermFreq, sumDocFreq, docCount, longsSize)); if (previous != null) { throw new CorruptIndexException("duplicate fields: " + fieldInfo.Name + " (resource=" + input + ")"); } } success = true; } finally { if (!success) { input.Dispose(); } } this.indexReader = indexReader; } private int ReadHeader(DataInput input) { int version = CodecUtil.CheckHeader(input, BlockTermsWriter.CODEC_NAME, BlockTermsWriter.VERSION_START, BlockTermsWriter.VERSION_CURRENT); if (version < BlockTermsWriter.VERSION_APPEND_ONLY) { dirOffset = input.ReadInt64(); } return version; } private void SeekDir(IndexInput input, long dirOffset) { if (version >= BlockTermsWriter.VERSION_CHECKSUM) { input.Seek(input.Length - CodecUtil.FooterLength() - 8); dirOffset = input.ReadInt64(); } else if (version >= BlockTermsWriter.VERSION_APPEND_ONLY) { input.Seek(input.Length - 8); dirOffset = input.ReadInt64(); } input.Seek(dirOffset); } protected override void Dispose(bool disposing) { if (disposing) { try { try { if (indexReader != null) { indexReader.Dispose(); } } finally { // null so if an app hangs on to us (ie, we are not // GCable, despite being closed) we still free most // ram indexReader = null; if (input != null) { input.Dispose(); } } } finally { if (postingsReader != null) { postingsReader.Dispose(); } } } } public override IEnumerator<string> GetEnumerator() { return fields.Keys.GetEnumerator(); // LUCENENET NOTE: enumerators are not writable in .NET } public override Terms GetTerms(string field) { Debug.Assert(field != null); FieldReader result; fields.TryGetValue(field, out result); return result; } public override int Count => fields.Count; private class FieldReader : Terms { private readonly BlockTermsReader outerInstance; private readonly long numTerms; private readonly FieldInfo fieldInfo; private readonly long termsStartPointer; private readonly long sumTotalTermFreq; private readonly long sumDocFreq; private readonly int docCount; private readonly int longsSize; public FieldReader(BlockTermsReader outerInstance, FieldInfo fieldInfo, long numTerms, long termsStartPointer, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize) { Debug.Assert(numTerms > 0); this.outerInstance = outerInstance; this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.termsStartPointer = termsStartPointer; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; } public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer; public override TermsEnum GetIterator(TermsEnum reuse) { return new SegmentTermsEnum(this); } public override bool HasFreqs => fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; public override bool HasOffsets => fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; public override bool HasPositions => fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; public override bool HasPayloads => fieldInfo.HasPayloads; public override long Count => numTerms; public override long SumTotalTermFreq => sumTotalTermFreq; public override long SumDocFreq => sumDocFreq; public override int DocCount => docCount; // Iterates through terms in this field private class SegmentTermsEnum : TermsEnum { private readonly FieldReader outerInstance; private readonly IndexInput input; private readonly BlockTermState state; private readonly bool doOrd; private readonly FieldAndTerm fieldTerm = new FieldAndTerm(); private readonly TermsIndexReaderBase.FieldIndexEnum indexEnum; private readonly BytesRef term = new BytesRef(); /* This is true if indexEnum is "still" seek'd to the index term for the current term. We set it to true on seeking, and then it remains valid until next() is called enough times to load another terms block: */ private bool indexIsCurrent; /* True if we've already called .next() on the indexEnum, to "bracket" the current block of terms: */ private bool didIndexNext; /* Next index term, bracketing the current block of terms; this is only valid if didIndexNext is true: */ private BytesRef nextIndexTerm; /* True after seekExact(TermState), do defer seeking. If the app then calls next() (which is not "typical"), then we'll do the real seek */ private bool seekPending; /* How many blocks we've read since last seek. Once this is >= indexEnum.getDivisor() we set indexIsCurrent to false (since the index can no long bracket seek-within-block). */ private int blocksSinceSeek; private byte[] termSuffixes; private readonly ByteArrayDataInput termSuffixesReader = new ByteArrayDataInput(); /* Common prefix used for all terms in this block. */ private int termBlockPrefix; /* How many terms in current block */ private int blockTermCount; private byte[] docFreqBytes; private readonly ByteArrayDataInput freqReader = new ByteArrayDataInput(); private int metaDataUpto; private readonly long[] longs; private byte[] bytes; private ByteArrayDataInput bytesReader; public SegmentTermsEnum(FieldReader outerInstance) { this.outerInstance = outerInstance; input = (IndexInput)outerInstance.outerInstance.input.Clone(); input.Seek(outerInstance.termsStartPointer); indexEnum = outerInstance.outerInstance.indexReader.GetFieldEnum(outerInstance.fieldInfo); doOrd = outerInstance.outerInstance.indexReader.SupportsOrd; fieldTerm.Field = outerInstance.fieldInfo.Name; state = outerInstance.outerInstance.postingsReader.NewTermState(); state.TotalTermFreq = -1; state.Ord = -1; termSuffixes = new byte[128]; docFreqBytes = new byte[64]; //System.out.println("BTR.enum init this=" + this + " postingsReader=" + postingsReader); longs = new long[outerInstance.longsSize]; } public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer; /// <remarks> /// TODO: we may want an alternate mode here which is /// "if you are about to return NOT_FOUND I won't use /// the terms data from that"; eg FuzzyTermsEnum will /// (usually) just immediately call seek again if we /// return NOT_FOUND so it's a waste for us to fill in /// the term that was actually NOT_FOUND /// </remarks> public override SeekStatus SeekCeil(BytesRef target) { if (indexEnum == null) { throw new InvalidOperationException("terms index was not loaded"); } //System.out.println("BTR.seek seg=" + segment + " target=" + fieldInfo.name + ":" + target.utf8ToString() + " " + target + " current=" + term().utf8ToString() + " " + term() + " indexIsCurrent=" + indexIsCurrent + " didIndexNext=" + didIndexNext + " seekPending=" + seekPending + " divisor=" + indexReader.getDivisor() + " this=" + this); if (didIndexNext) { if (nextIndexTerm == null) { //System.out.println(" nextIndexTerm=null"); } else { //System.out.println(" nextIndexTerm=" + nextIndexTerm.utf8ToString()); } } bool doSeek = true; // See if we can avoid seeking, because target term // is after current term but before next index term: if (indexIsCurrent) { int cmp = BytesRef.UTF8SortedAsUnicodeComparer.Compare(term, target); if (cmp == 0) { // Already at the requested term return SeekStatus.FOUND; } else if (cmp < 0) { // Target term is after current term if (!didIndexNext) { if (indexEnum.Next() == -1) { nextIndexTerm = null; } else { nextIndexTerm = indexEnum.Term; } //System.out.println(" now do index next() nextIndexTerm=" + (nextIndexTerm == null ? "null" : nextIndexTerm.utf8ToString())); didIndexNext = true; } if (nextIndexTerm == null || BytesRef.UTF8SortedAsUnicodeComparer.Compare(target, nextIndexTerm) < 0) { // Optimization: requested term is within the // same term block we are now in; skip seeking // (but do scanning): doSeek = false; //System.out.println(" skip seek: nextIndexTerm=" + (nextIndexTerm == null ? "null" : nextIndexTerm.utf8ToString())); } } } if (doSeek) { //System.out.println(" seek"); // Ask terms index to find biggest indexed term (= // first term in a block) that's <= our text: input.Seek(indexEnum.Seek(target)); bool result = NextBlock(); // Block must exist since, at least, the indexed term // is in the block: Debug.Assert(result); indexIsCurrent = true; didIndexNext = false; blocksSinceSeek = 0; if (doOrd) { state.Ord = indexEnum.Ord - 1; } term.CopyBytes(indexEnum.Term); //System.out.println(" seek: term=" + term.utf8ToString()); } else { //System.out.println(" skip seek"); if (state.TermBlockOrd == blockTermCount && !NextBlock()) { indexIsCurrent = false; return SeekStatus.END; } } seekPending = false; int common = 0; // Scan within block. We could do this by calling // _next() and testing the resulting term, but this // is wasteful. Instead, we first confirm the // target matches the common prefix of this block, // and then we scan the term bytes directly from the // termSuffixesreader's byte[], saving a copy into // the BytesRef term per term. Only when we return // do we then copy the bytes into the term. while (true) { // First, see if target term matches common prefix // in this block: if (common < termBlockPrefix) { int cmp = (term.Bytes[common] & 0xFF) - (target.Bytes[target.Offset + common] & 0xFF); if (cmp < 0) { // TODO: maybe we should store common prefix // in block header? (instead of relying on // last term of previous block) // Target's prefix is after the common block // prefix, so term cannot be in this block // but it could be in next block. We // must scan to end-of-block to set common // prefix for next block: if (state.TermBlockOrd < blockTermCount) { while (state.TermBlockOrd < blockTermCount - 1) { state.TermBlockOrd++; state.Ord++; termSuffixesReader.SkipBytes(termSuffixesReader.ReadVInt32()); } int suffix = termSuffixesReader.ReadVInt32(); term.Length = termBlockPrefix + suffix; if (term.Bytes.Length < term.Length) { term.Grow(term.Length); } termSuffixesReader.ReadBytes(term.Bytes, termBlockPrefix, suffix); } state.Ord++; if (!NextBlock()) { indexIsCurrent = false; return SeekStatus.END; } common = 0; } else if (cmp > 0) { // Target's prefix is before the common prefix // of this block, so we position to start of // block and return NOT_FOUND: Debug.Assert(state.TermBlockOrd == 0); int suffix = termSuffixesReader.ReadVInt32(); term.Length = termBlockPrefix + suffix; if (term.Bytes.Length < term.Length) { term.Grow(term.Length); } termSuffixesReader.ReadBytes(term.Bytes, termBlockPrefix, suffix); return SeekStatus.NOT_FOUND; } else { common++; } continue; } // Test every term in this block while (true) { state.TermBlockOrd++; state.Ord++; int suffix = termSuffixesReader.ReadVInt32(); // We know the prefix matches, so just compare the new suffix: int termLen = termBlockPrefix + suffix; int bytePos = termSuffixesReader.Position; bool next = false; int limit = target.Offset + (termLen < target.Length ? termLen : target.Length); int targetPos = target.Offset + termBlockPrefix; while (targetPos < limit) { int cmp = (termSuffixes[bytePos++] & 0xFF) - (target.Bytes[targetPos++] & 0xFF); if (cmp < 0) { // Current term is still before the target; // keep scanning next = true; break; } else if (cmp > 0) { // Done! Current term is after target. Stop // here, fill in real term, return NOT_FOUND. term.Length = termBlockPrefix + suffix; if (term.Bytes.Length < term.Length) { term.Grow(term.Length); } termSuffixesReader.ReadBytes(term.Bytes, termBlockPrefix, suffix); //System.out.println(" NOT_FOUND"); return SeekStatus.NOT_FOUND; } } if (!next && target.Length <= termLen) { term.Length = termBlockPrefix + suffix; if (term.Bytes.Length < term.Length) { term.Grow(term.Length); } termSuffixesReader.ReadBytes(term.Bytes, termBlockPrefix, suffix); if (target.Length == termLen) { // Done! Exact match. Stop here, fill in // real term, return FOUND. //System.out.println(" FOUND"); return SeekStatus.FOUND; } else { //System.out.println(" NOT_FOUND"); return SeekStatus.NOT_FOUND; } } if (state.TermBlockOrd == blockTermCount) { // Must pre-fill term for next block's common prefix term.Length = termBlockPrefix + suffix; if (term.Bytes.Length < term.Length) { term.Grow(term.Length); } termSuffixesReader.ReadBytes(term.Bytes, termBlockPrefix, suffix); break; } else { termSuffixesReader.SkipBytes(suffix); } } // The purpose of the terms dict index is to seek // the enum to the closest index term before the // term we are looking for. So, we should never // cross another index term (besides the first // one) while we are scanning: Debug.Assert(indexIsCurrent); if (!NextBlock()) { //System.out.println(" END"); indexIsCurrent = false; return SeekStatus.END; } common = 0; } } public override BytesRef Next() { //System.out.println("BTR.next() seekPending=" + seekPending + " pendingSeekCount=" + state.termBlockOrd); // If seek was previously called and the term was cached, // usually caller is just going to pull a D/&PEnum or get // docFreq, etc. But, if they then call next(), // this method catches up all internal state so next() // works properly: if (seekPending) { Debug.Assert(!indexIsCurrent); input.Seek(state.BlockFilePointer); int pendingSeekCount = state.TermBlockOrd; bool result = NextBlock(); long savOrd = state.Ord; // Block must exist since seek(TermState) was called w/ a // TermState previously returned by this enum when positioned // on a real term: Debug.Assert(result); while (state.TermBlockOrd < pendingSeekCount) { BytesRef nextResult = _next(); Debug.Assert(nextResult != null); } seekPending = false; state.Ord = savOrd; } return _next(); } /// <summary> /// Decodes only the term bytes of the next term. If caller then asks for /// metadata, ie docFreq, totalTermFreq or pulls a D/P Enum, we then (lazily) /// decode all metadata up to the current term /// </summary> /// <returns></returns> private BytesRef _next() { //System.out.println("BTR._next seg=" + segment + " this=" + this + " termCount=" + state.termBlockOrd + " (vs " + blockTermCount + ")"); if (state.TermBlockOrd == blockTermCount && !NextBlock()) { //System.out.println(" eof"); indexIsCurrent = false; return null; } // TODO: cutover to something better for these ints! simple64? int suffix = termSuffixesReader.ReadVInt32(); //System.out.println(" suffix=" + suffix); term.Length = termBlockPrefix + suffix; if (term.Bytes.Length < term.Length) { term.Grow(term.Length); } termSuffixesReader.ReadBytes(term.Bytes, termBlockPrefix, suffix); state.TermBlockOrd++; // NOTE: meaningless in the non-ord case state.Ord++; //System.out.println(" return term=" + fieldInfo.name + ":" + term.utf8ToString() + " " + term + " tbOrd=" + state.termBlockOrd); return term; } public override BytesRef Term => term; public override int DocFreq { get { //System.out.println("BTR.docFreq"); DecodeMetaData(); //System.out.println(" return " + state.docFreq); return state.DocFreq; } } public override long TotalTermFreq { get { DecodeMetaData(); return state.TotalTermFreq; } } public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { //System.out.println("BTR.docs this=" + this); DecodeMetaData(); //System.out.println("BTR.docs: state.docFreq=" + state.docFreq); return outerInstance.outerInstance.postingsReader.Docs(outerInstance.fieldInfo, state, liveDocs, reuse, flags); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { if (outerInstance.fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) { // Positions were not indexed: return null; } DecodeMetaData(); return outerInstance.outerInstance.postingsReader.DocsAndPositions(outerInstance.fieldInfo, state, liveDocs, reuse, flags); } public override void SeekExact(BytesRef target, TermState otherState) { //System.out.println("BTR.seekExact termState target=" + target.utf8ToString() + " " + target + " this=" + this); Debug.Assert(otherState != null && otherState is BlockTermState); Debug.Assert(!doOrd || ((BlockTermState)otherState).Ord < outerInstance.numTerms); state.CopyFrom(otherState); seekPending = true; indexIsCurrent = false; term.CopyBytes(target); } public override TermState GetTermState() { //System.out.println("BTR.termState this=" + this); DecodeMetaData(); TermState ts = (TermState)state.Clone(); //System.out.println(" return ts=" + ts); return ts; } public override void SeekExact(long ord) { //System.out.println("BTR.seek by ord ord=" + ord); if (indexEnum == null) { throw new InvalidOperationException("terms index was not loaded"); } Debug.Assert(ord < outerInstance.numTerms); // TODO: if ord is in same terms block and // after current ord, we should avoid this seek just // like we do in the seek(BytesRef) case input.Seek(indexEnum.Seek(ord)); bool result = NextBlock(); // Block must exist since ord < numTerms: Debug.Assert(result); indexIsCurrent = true; didIndexNext = false; blocksSinceSeek = 0; seekPending = false; state.Ord = indexEnum.Ord - 1; Debug.Assert(state.Ord >= -1, "Ord=" + state.Ord); term.CopyBytes(indexEnum.Term); // Now, scan: int left = (int)(ord - state.Ord); while (left > 0) { BytesRef term = _next(); Debug.Assert(term != null); left--; Debug.Assert(indexIsCurrent); } } public override long Ord { get { if (!doOrd) { throw new NotSupportedException(); } return state.Ord; } } // Does initial decode of next block of terms; this // doesn't actually decode the docFreq, totalTermFreq, // postings details (frq/prx offset, etc.) metadata; // it just loads them as byte[] blobs which are then // decoded on-demand if the metadata is ever requested // for any term in this block. This enables terms-only // intensive consumes (eg certain MTQs, respelling) to // not pay the price of decoding metadata they won't // use. private bool NextBlock() { // TODO: we still lazy-decode the byte[] for each // term (the suffix), but, if we decoded // all N terms up front then seeking could do a fast // bsearch w/in the block... //System.out.println("BTR.nextBlock() fp=" + in.getFilePointer() + " this=" + this); state.BlockFilePointer = input.GetFilePointer(); blockTermCount = input.ReadVInt32(); //System.out.println(" blockTermCount=" + blockTermCount); if (blockTermCount == 0) { return false; } termBlockPrefix = input.ReadVInt32(); // term suffixes: int len = input.ReadVInt32(); if (termSuffixes.Length < len) { termSuffixes = new byte[ArrayUtil.Oversize(len, 1)]; } //System.out.println(" termSuffixes len=" + len); input.ReadBytes(termSuffixes, 0, len); termSuffixesReader.Reset(termSuffixes, 0, len); // docFreq, totalTermFreq len = input.ReadVInt32(); if (docFreqBytes.Length < len) { docFreqBytes = new byte[ArrayUtil.Oversize(len, 1)]; } //System.out.println(" freq bytes len=" + len); input.ReadBytes(docFreqBytes, 0, len); freqReader.Reset(docFreqBytes, 0, len); // metadata len = input.ReadVInt32(); if (bytes == null) { bytes = new byte[ArrayUtil.Oversize(len, 1)]; bytesReader = new ByteArrayDataInput(); } else if (bytes.Length < len) { bytes = new byte[ArrayUtil.Oversize(len, 1)]; } input.ReadBytes(bytes, 0, len); bytesReader.Reset(bytes, 0, len); metaDataUpto = 0; state.TermBlockOrd = 0; blocksSinceSeek++; indexIsCurrent = indexIsCurrent && (blocksSinceSeek < outerInstance.outerInstance.indexReader.Divisor); //System.out.println(" indexIsCurrent=" + indexIsCurrent); return true; } private void DecodeMetaData() { //System.out.println("BTR.decodeMetadata mdUpto=" + metaDataUpto + " vs termCount=" + state.termBlockOrd + " state=" + state); if (!seekPending) { // TODO: cutover to random-access API // here.... really stupid that we have to decode N // wasted term metadata just to get to the N+1th // that we really need... // lazily catch up on metadata decode: int limit = state.TermBlockOrd; bool absolute = metaDataUpto == 0; // TODO: better API would be "jump straight to term=N"??? while (metaDataUpto < limit) { //System.out.println(" decode mdUpto=" + metaDataUpto); // TODO: we could make "tiers" of metadata, ie, // decode docFreq/totalTF but don't decode postings // metadata; this way caller could get // docFreq/totalTF w/o paying decode cost for // postings // TODO: if docFreq were bulk decoded we could // just skipN here: // docFreq, totalTermFreq state.DocFreq = freqReader.ReadVInt32(); //System.out.println(" dF=" + state.docFreq); if (outerInstance.fieldInfo.IndexOptions != IndexOptions.DOCS_ONLY) { state.TotalTermFreq = state.DocFreq + freqReader.ReadVInt64(); //System.out.println(" totTF=" + state.totalTermFreq); } // metadata for (int i = 0; i < longs.Length; i++) { longs[i] = bytesReader.ReadVInt64(); } outerInstance.outerInstance.postingsReader.DecodeTerm(longs, bytesReader, outerInstance.fieldInfo, state, absolute); metaDataUpto++; absolute = false; } } else { //System.out.println(" skip! seekPending"); } } } } public override long RamBytesUsed() { long sizeInBytes = (postingsReader != null) ? postingsReader.RamBytesUsed() : 0; sizeInBytes += (indexReader != null) ? indexReader.RamBytesUsed() : 0; return sizeInBytes; } public override void CheckIntegrity() { // verify terms if (version >= BlockTermsWriter.VERSION_CHECKSUM) { CodecUtil.ChecksumEntireFile(input); } // verify postings postingsReader.CheckIntegrity(); } } }
// 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.Diagnostics; using System.Linq.Expressions; using System.Reflection; namespace Microsoft.CSharp.RuntimeBinder { internal static class RuntimeBinderExtensions { public static bool IsNullableType(this Type type) { return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } // This method is intended as a means to detect when MemberInfos are the same, // modulo the fact that they can appear to have different but equivalent local // No-PIA types. It is by the symbol table to determine whether // or not members have been added to an AggSym or not. public static bool IsEquivalentTo(this MemberInfo mi1, MemberInfo mi2) { if (mi1 == null || mi2 == null) { return mi1 == null && mi2 == null; } if (mi1.Equals(mi2)) { return true; } if (mi1 is MethodInfo method1) { if (!(mi2 is MethodInfo method2) || method1.IsGenericMethod != method2.IsGenericMethod) { return false; } if (method1.IsGenericMethod) { method1 = method1.GetGenericMethodDefinition(); method2 = method2.GetGenericMethodDefinition(); if (method1.GetGenericArguments().Length != method2.GetGenericArguments().Length) { return false; // Methods of different arity are not equivalent. } } return method1 != method2 && method1.CallingConvention == method2.CallingConvention && method1.Name == method2.Name && method1.DeclaringType.IsGenericallyEqual(method2.DeclaringType) && method1.ReturnType.IsGenericallyEquivalentTo(method2.ReturnType, method1, method2) && method1.AreParametersEquivalent(method2); } if (mi1 is ConstructorInfo ctor1) { return mi2 is ConstructorInfo ctor2 && ctor1 != ctor2 && ctor1.CallingConvention == ctor2.CallingConvention && ctor1.DeclaringType.IsGenericallyEqual(ctor2.DeclaringType) && ctor1.AreParametersEquivalent(ctor2); } return mi1 is PropertyInfo prop1 && mi2 is PropertyInfo prop2 && prop1 != prop2 && prop1.Name == prop2.Name && prop1.DeclaringType.IsGenericallyEqual(prop2.DeclaringType) && prop1.PropertyType.IsGenericallyEquivalentTo(prop2.PropertyType, prop1, prop2) && prop1.GetGetMethod(true).IsEquivalentTo(prop2.GetGetMethod(true)) && prop1.GetSetMethod(true).IsEquivalentTo(prop2.GetSetMethod(true)); } private static bool AreParametersEquivalent(this MethodBase method1, MethodBase method2) { ParameterInfo[] pis1 = method1.GetParameters(); ParameterInfo[] pis2 = method2.GetParameters(); if (pis1.Length != pis2.Length) { return false; } for (int i = 0; i < pis1.Length; ++i) { if (!pis1[i].IsEquivalentTo(pis2[i], method1, method2)) { return false; } } return true; } private static bool IsEquivalentTo(this ParameterInfo pi1, ParameterInfo pi2, MethodBase method1, MethodBase method2) { if (pi1 == null || pi2 == null) { return pi1 == null && pi2 == null; } if (pi1.Equals(pi2)) { return true; } return pi1.ParameterType.IsGenericallyEquivalentTo(pi2.ParameterType, method1, method2); } private static bool IsGenericallyEqual(this Type t1, Type t2) { if (t1 == null || t2 == null) { return t1 == null && t2 == null; } if (t1.Equals(t2)) { return true; } if (t1.IsConstructedGenericType || t2.IsConstructedGenericType) { Type t1def = t1.IsConstructedGenericType ? t1.GetGenericTypeDefinition() : t1; Type t2def = t2.IsConstructedGenericType ? t2.GetGenericTypeDefinition() : t2; return t1def.Equals(t2def); } return false; } // Compares two types and calls them equivalent if a type parameter equals a type argument. // i.e if the inputs are (T, int, C<T>, C<int>) then this will return true. private static bool IsGenericallyEquivalentTo(this Type t1, Type t2, MemberInfo member1, MemberInfo member2) { Debug.Assert(!(member1 is MethodBase) || !((MethodBase)member1).IsGenericMethod || (((MethodBase)member1).IsGenericMethodDefinition && ((MethodBase)member2).IsGenericMethodDefinition)); if (t1.Equals(t2)) { return true; } // If one of them is a type param and then the other is a real type, then get the type argument in the member // or it's declaring type that corresponds to the type param and compare that to the other type. if (t1.IsGenericParameter) { if (t2.IsGenericParameter) { // If member's declaring type is not type parameter's declaring type, we assume that it is used as a type argument if (t1.DeclaringMethod == null && member1.DeclaringType.Equals(t1.DeclaringType)) { if (!(t2.DeclaringMethod == null && member2.DeclaringType.Equals(t2.DeclaringType))) { return t1.IsTypeParameterEquivalentToTypeInst(t2, member2); } } else if (t2.DeclaringMethod == null && member2.DeclaringType.Equals(t2.DeclaringType)) { return t2.IsTypeParameterEquivalentToTypeInst(t1, member1); } // If both of these are type params but didn't compare to be equal then one of them is likely bound to another // open type. Simply disallow such cases. return false; } return t1.IsTypeParameterEquivalentToTypeInst(t2, member2); } else if (t2.IsGenericParameter) { return t2.IsTypeParameterEquivalentToTypeInst(t1, member1); } // Recurse in for generic types arrays, byref and pointer types. if (t1.IsGenericType && t2.IsGenericType) { Type[] args1 = t1.GetGenericArguments(); Type[] args2 = t2.GetGenericArguments(); if (args1.Length == args2.Length) { if (!t1.IsGenericallyEqual(t2)) { return false; } for (int i = 0; i < args1.Length; i++) { if (!args1[i].IsGenericallyEquivalentTo(args2[i], member1, member2)) { return false; } } return true; } } if (t1.IsArray && t2.IsArray) { return t1.GetArrayRank() == t2.GetArrayRank() && t1.GetElementType().IsGenericallyEquivalentTo(t2.GetElementType(), member1, member2); } if ((t1.IsByRef && t2.IsByRef) || (t1.IsPointer && t2.IsPointer)) { return t1.GetElementType().IsGenericallyEquivalentTo(t2.GetElementType(), member1, member2); } return false; } private static bool IsTypeParameterEquivalentToTypeInst(this Type typeParam, Type typeInst, MemberInfo member) { Debug.Assert(typeParam.IsGenericParameter); if (typeParam.DeclaringMethod != null) { // The type param is from a generic method. Since only methods can be generic, anything else // here means they are not equivalent. if (!(member is MethodBase)) { return false; } MethodBase method = (MethodBase)member; int position = typeParam.GenericParameterPosition; Type[] args = method.IsGenericMethod ? method.GetGenericArguments() : null; return args != null && args.Length > position && args[position].Equals(typeInst); } else { return member.DeclaringType.GetGenericArguments()[typeParam.GenericParameterPosition].Equals(typeInst); } } // s_MemberEquivalence will replace itself with one version or another // depending on what works at run time private static Func<MemberInfo, MemberInfo, bool> s_MemberEquivalence = (m1, m2) => { try { Type memberInfo = typeof(MemberInfo); // First, try the actual API. (Post .NetCore 2.0) The api is the only one that gets it completely right on frameworks without MetadataToken. MethodInfo apiMethod = memberInfo.GetMethod( "HasSameMetadataDefinitionAs", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding, binder: null, types: new Type[] { typeof(MemberInfo) }, modifiers: null); if (apiMethod != null) { Func<MemberInfo, MemberInfo, bool> apiDelegate = (Func<MemberInfo, MemberInfo, bool>)(apiMethod.CreateDelegate(typeof(Func<MemberInfo, MemberInfo, bool>))); try { bool result = apiDelegate(m1, m2); // it worked, so publish it s_MemberEquivalence = apiDelegate; return result; } catch { // Api found but apparently stubbed as not supported. Continue on to the next fallback... } } // See if MetadataToken property is available. PropertyInfo property = memberInfo.GetProperty("MetadataToken", typeof(int), Array.Empty<Type>()); if ((object)property != null && property.CanRead) { // (parameter1, parameter2) => parameter1.MetadataToken == parameter2.MetadataToken var parameter1 = Expression.Parameter(memberInfo); var parameter2 = Expression.Parameter(memberInfo); var memberEquivalence = Expression.Lambda<Func<MemberInfo, MemberInfo, bool>>( Expression.Equal( Expression.Property(parameter1, property), Expression.Property(parameter2, property)), parameter1, parameter2).Compile(); var result = memberEquivalence(m1, m2); // it worked, so publish it s_MemberEquivalence = memberEquivalence; return result; } } catch { // Platform might not allow access to the property } // MetadataToken is not available in some contexts. Looks like this is one of those cases. // fallback to "IsEquivalentTo" Func<MemberInfo, MemberInfo, bool> fallbackMemberEquivalence = (m1param, m2param) => m1param.IsEquivalentTo(m2param); // fallback must work s_MemberEquivalence = fallbackMemberEquivalence; return fallbackMemberEquivalence(m1, m2); }; public static bool HasSameMetadataDefinitionAs(this MemberInfo mi1, MemberInfo mi2) { return mi1.Module.Equals(mi2.Module) && s_MemberEquivalence(mi1, mi2); } public static string GetIndexerName(this Type type) { Debug.Assert(type != null); string name = GetTypeIndexerName(type); if (name == null && type.IsInterface) { foreach (Type iface in type.GetInterfaces()) { name = GetTypeIndexerName(iface); if (name != null) { break; } } } return name; } private static string GetTypeIndexerName(Type type) { Debug.Assert(type != null); string name = type.GetCustomAttribute<DefaultMemberAttribute>()?.MemberName; if (name != null) { foreach (PropertyInfo p in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) { if (p.Name == name && p.GetIndexParameters().Length != 0) { return name; } } } 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.Collections.Generic; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition { internal static class TransparentTestCase { public static int GetMetadataView_IMetadataViewWithDefaultedIntInTranparentType(ITrans_MetadataViewWithDefaultedInt view) { return view.MyInt; } } [MetadataViewImplementation(typeof(MetadataViewWithImplementation))] public interface IMetadataViewWithImplementation { string String1 { get; } string String2 { get; } } public class MetadataViewWithImplementation : IMetadataViewWithImplementation { public MetadataViewWithImplementation(IDictionary<string, object> metadata) { this.String1 = (string)metadata["String1"]; this.String2 = (string)metadata["String2"]; } public string String1 { get; private set; } public string String2 { get; private set; } } [MetadataViewImplementation(typeof(MetadataViewWithImplementationNoInterface))] public interface IMetadataViewWithImplementationNoInterface { string String1 { get; } string String2 { get; } } public class MetadataViewWithImplementationNoInterface { public MetadataViewWithImplementationNoInterface(IDictionary<string, object> metadata) { this.String1 = (string)metadata["String1"]; this.String2 = (string)metadata["String2"]; } public string String1 { get; private set; } public string String2 { get; private set; } } public class MetadataViewProviderTests { [Fact] public void GetMetadataView_InterfaceWithPropertySetter_ShouldThrowNotSupported() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; Assert.Throws<NotSupportedException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataViewWithPropertySetter>(metadata); }); } [Fact] public void GetMetadataView_InterfaceWithMethod_ShouldThrowNotSupportedException() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; Assert.Throws<NotSupportedException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataViewWithMethod>(metadata); }); } [Fact] public void GetMetadataView_InterfaceWithEvent_ShouldThrowNotSupportedException() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; Assert.Throws<NotSupportedException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataViewWithEvent>(metadata); }); } [Fact] public void GetMetadataView_InterfaceWithIndexer_ShouldThrowNotSupportedException() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; Assert.Throws<NotSupportedException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataViewWithIndexer>(metadata); }); } [Fact] public void GetMetadataView_AbstractClass_ShouldThrowMissingMethodException() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; Assert.Throws<CompositionContractMismatchException>(() => { MetadataViewProvider.GetMetadataView<AbstractClassMetadataView>(metadata); }); } [Fact] [ActiveIssue(25498, TargetFrameworkMonikers.UapAot)] public void GetMetadataView_AbstractClassWithConstructor_ShouldThrowMemberAccessException() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; Assert.Throws<MemberAccessException>(() => { MetadataViewProvider.GetMetadataView<AbstractClassWithConstructorMetadataView>(metadata); }); } [Fact] public void GetMetadataView_IDictionaryAsTMetadataViewTypeArgument_ShouldReturnMetadata() { var metadata = new Dictionary<string, object>(); var result = MetadataViewProvider.GetMetadataView<IDictionary<string, object>>(metadata); Assert.Same(metadata, result); } [Fact] public void GetMetadataView_IEnumerableAsTMetadataViewTypeArgument_ShouldReturnMetadata() { var metadata = new Dictionary<string, object>(); var result = MetadataViewProvider.GetMetadataView<IEnumerable<KeyValuePair<string, object>>>(metadata); Assert.Same(metadata, result); } [Fact] public void GetMetadataView_DictionaryAsTMetadataViewTypeArgument_ShouldNotThrow() { var metadata = new Dictionary<string, object>(); MetadataViewProvider.GetMetadataView<Dictionary<string, object>>(metadata); } [Fact] public void GetMetadataView_PrivateInterfaceAsTMetadataViewTypeArgument_ShouldhrowNotSupportedException() { var metadata = new Dictionary<string, object>(); metadata["CanActivate"] = true; Assert.Throws<NotSupportedException>(() => { MetadataViewProvider.GetMetadataView<IActivator>(metadata); }); } [Fact] public void GetMetadataView_DictionaryWithUncastableValueAsMetadataArgument_ShouldThrowCompositionContractMismatchException() { var metadata = new Dictionary<string, object>(); metadata["Value"] = true; Assert.Throws<CompositionContractMismatchException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataView>(metadata); }); } [Fact] public void GetMetadataView_InterfaceWithTwoPropertiesWithSameNameDifferentTypeAsTMetadataViewArgument_ShouldThrowContractMismatch() { var metadata = new Dictionary<string, object>(); metadata["Value"] = 10; Assert.Throws<CompositionContractMismatchException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataView2>(metadata); }); } [Fact] public void GetMetadataView_RawMetadata() { var metadata = new Dictionary<string, object>(); metadata["Value"] = 10; var view = MetadataViewProvider.GetMetadataView<RawMetadata>(new Dictionary<string, object>(metadata)); Assert.True(view.Count == metadata.Count); Assert.True(view["Value"] == metadata["Value"]); } [Fact] public void GetMetadataView_InterfaceInheritance() { var metadata = new Dictionary<string, object>(); metadata["Value"] = "value"; metadata["Value2"] = "value2"; var view = MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataView3>(metadata); Assert.Equal("value", view.Value); Assert.Equal("value2", view.Value2); } [Fact] public void GetMetadataView_CachesViewType() { var metadata1 = new Dictionary<string, object>(); metadata1["Value"] = "value1"; var view1 = MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataView>(metadata1); Assert.Equal("value1", view1.Value); var metadata2 = new Dictionary<string, object>(); metadata2["Value"] = "value2"; var view2 = MetadataViewProvider.GetMetadataView<ITrans_MetadataTests_MetadataView>(metadata2); Assert.Equal("value2", view2.Value); Assert.Equal(view1.GetType(), view2.GetType()); } private interface IActivator { bool CanActivate { get; } } public class RawMetadata : Dictionary<string, object> { public RawMetadata(IDictionary<string, object> dictionary) : base(dictionary) { } } public abstract class AbstractClassMetadataView { public abstract object Value { get; } } public abstract class AbstractClassWithConstructorMetadataView { public AbstractClassWithConstructorMetadataView(IDictionary<string, object> metadata) { } public abstract object Value { get; } } [Fact] public void GetMetadataView_IMetadataViewWithDefaultedInt() { var view = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedInt>(new Dictionary<string, object>()); Assert.Equal(120, view.MyInt); } [Fact] public void GetMetadataView_IMetadataViewWithDefaultedIntInTranparentType() { var view = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedInt>(new Dictionary<string, object>()); int result = TransparentTestCase.GetMetadataView_IMetadataViewWithDefaultedIntInTranparentType(view); Assert.Equal(120, result); } [Fact] public void GetMetadataView_IMetadataViewWithDefaultedIntAndInvalidMetadata() { Dictionary<string, object> metadata = new Dictionary<string, object>(); metadata = new Dictionary<string, object>(); metadata.Add("MyInt", 1.2); var view1 = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedInt>(metadata); Assert.Equal(120, view1.MyInt); metadata = new Dictionary<string, object>(); metadata.Add("MyInt", "Hello, World"); var view2 = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedInt>(metadata); Assert.Equal(120, view2.MyInt); } [Fact] public void GetMetadataView_MetadataViewWithImplementation() { Dictionary<string, object> metadata = new Dictionary<string, object>(); metadata = new Dictionary<string, object>(); metadata.Add("String1", "One"); metadata.Add("String2", "Two"); var view1 = MetadataViewProvider.GetMetadataView<IMetadataViewWithImplementation>(metadata); Assert.Equal("One", view1.String1); Assert.Equal("Two", view1.String2); Assert.Equal(view1.GetType(), typeof(MetadataViewWithImplementation)); } [Fact] public void GetMetadataView_MetadataViewWithImplementationNoInterface() { var exception = Assert.Throws<CompositionContractMismatchException>(() => { Dictionary<string, object> metadata = new Dictionary<string, object>(); metadata = new Dictionary<string, object>(); metadata.Add("String1", "One"); metadata.Add("String2", "Two"); var view1 = MetadataViewProvider.GetMetadataView<IMetadataViewWithImplementationNoInterface>(metadata); }); } [Fact] public void GetMetadataView_IMetadataViewWithDefaultedBool() { var view = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedBool>(new Dictionary<string, object>()); Assert.Equal(false, view.MyBool); } [Fact] public void GetMetadataView_IMetadataViewWithDefaultedInt64() { var view = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedInt64>(new Dictionary<string, object>()); Assert.Equal(long.MaxValue, view.MyInt64); } [Fact] public void GetMetadataView_IMetadataViewWithDefaultedString() { var view = MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithDefaultedString>(new Dictionary<string, object>()); Assert.Equal("MyString", view.MyString); } [Fact] public void GetMetadataView_IMetadataViewWithTypeMismatchDefaultValue() { var exception = Assert.Throws<CompositionContractMismatchException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithTypeMismatchDefaultValue>(new Dictionary<string, object>()); }); Assert.IsType<TargetInvocationException>(exception.InnerException); } [Fact] public void GetMetadataView_IMetadataViewWithTypeMismatchOnUnbox() { var metadata = new Dictionary<string, object>(); metadata["Value"] = (short)9999; var exception = Assert.Throws<CompositionContractMismatchException>(() => { MetadataViewProvider.GetMetadataView<ITrans_MetadataViewWithTypeMismatchDefaultValue>(new Dictionary<string, object>()); }); Assert.IsType<TargetInvocationException>(exception.InnerException); } [Fact] public void TestMetadataIntConversion() { var metadata = new Dictionary<string, object>(); metadata["Value"] = (long)45; var exception = Assert.Throws<CompositionContractMismatchException>(() => { MetadataViewProvider.GetMetadataView<ITrans_HasInt64>(metadata); }); } } }
//----------------------------------------------------------------------------- //Based on... // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. // http://create.msdn.com/en-US/education/catalog/sample/normal_mapping //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Adapted from the code by... // Jorge Adriano Luna // http://jcoluna.wordpress.com //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.IO; using RenderingSystem.RendererImpl; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using Henge3D.Physics; using Henge3D; using Henge3D.Pipeline; namespace Xna_Game_Model { /// <summary> /// Code based upon: /// http://create.msdn.com/en-US/education/catalog/sample/normal_mapping /// </summary> [ContentProcessor(DisplayName = "Xna Game Model")] public class GameProcessor : ModelProcessor { protected bool _isSkinned = false; // These are the keys for the maps in the model file. // It was a solid idea although I don't know how it works with blender. public const string NormalMapKey = "NormalMap"; public const string DiffuseMapKey = "DiffuseMap"; public const string SpecularMapKey = "SpecularMap"; public const string EmissiveMapKey = "EmissiveMap"; public const string SecondNormalMapKey = "SecondNormalMap"; public const string SecondDiffuseMapKey = "SecondDiffuseMap"; public const string SecondSpecularMapKey = "SecondSpecularMap"; public const string ReflectionMapKey = "ReflectionMap"; const string TYPE_ATTR_NAME = "type"; const string ELASTICITY_ATTR_NAME = "elasticity"; const string ROUGHNESS_ATTR_NAME = "roughness"; const string DENSITY_ATTR_NAME = "density"; const string SHAPE_ATTR_NAME = "shape"; #region Physics Stuff private PhysicalShape _defaultShape = PhysicalShape.Polyhedron; private float _defaultDensity = 1f, _defaultElasticity = 0f, _defaultRoughness = 0.5f; private WindingOrder _windingOrder = WindingOrder.Clockwise; protected bool _processPhysics = true; [DefaultValue(PhysicalShape.Polyhedron)] [DisplayName("Default Shape")] [Description("The default shape type to use for meshes without a shape attribute.")] public PhysicalShape DefaultShape { get { return _defaultShape; } set { _defaultShape = value; } } [DefaultValue(1f)] [DisplayName("Default Density")] [Description("The default density of all meshes, used when calculating mass properties.")] public float DefaultDensity { get { return _defaultDensity; } set { _defaultDensity = value; } } [DefaultValue(0f)] [DisplayName("Default Elasticity")] [Description("The default elasticity of all meshes, used when calculating collision response.")] public float DefaultElasticity { get { return _defaultElasticity; } set { _defaultElasticity = value; } } [DefaultValue(0.5f)] [DisplayName("Default Roughness")] [Description("The default roughness of all meshes, used when calculating friction.")] public float DefaultRoughness { get { return _defaultRoughness; } set { _defaultRoughness = value; } } [DefaultValue(WindingOrder.Clockwise)] [DisplayName("Vertex Winding Order")] [Description("The winding order that the processor should expect (after SwapWindingOrder is applied, if set to true).")] public WindingOrder WindingOrder { get { return _windingOrder; } set { _windingOrder = value; } } [DefaultValue(true)] [DisplayName("Process Physics")] [Description("Whether to process for physics")] public virtual bool ProcessPhysics { get { return _processPhysics; } set { _processPhysics = value; } } #endregion private string s_customFx = ""; private List<string> _normalMapFilenames = new List<string>(); private List<string> _diffuseMapFilenames = new List<string>(); private List<string> _specularMapFilenames = new List<string>(); private RenderingSystem.RendererImpl.MeshData.RenderQueueType _renderQueue = MeshData.RenderQueueType.Default; public RenderingSystem.RendererImpl.MeshData.RenderQueueType RenderQueue { get { return _renderQueue; } set { _renderQueue = value; } } private bool _castShadows = true; /// <summary> /// The name of the custom fx file the model wants to use. /// If there is one. /// </summary> public string CustomFx { get { return s_customFx; } set { s_customFx = value; } } public bool CastShadows { get { return _castShadows; } set { _castShadows = value; } } public override ModelContent Process(NodeContent input, ContentProcessorContext context) { if (input == null) { throw new ArgumentNullException("input"); } //we always want to generate tangent frames, as we use tangent space normal mapping GenerateTangentFrames = true; //merge transforms MeshHelper.TransformScene(input, input.Transform); input.Transform = Matrix.Identity; if (!_isSkinned) MergeTransforms(input); if (_processPhysics) { // This type of mesh is ment for a static object. #region Physics Loading var attributes = input.Children.ToDictionary(n => n.Name, n => n.OpaqueData); var nodesToRemove = (from node in input.Children where node.OpaqueData.GetAttribute(TYPE_ATTR_NAME, MeshType.Both) == MeshType.Physical select node).ToArray(); MeshHelper.TransformScene(input, input.Transform); input.Transform = Matrix.Identity; MergeTransforms(input); ModelContent model = base.Process(input, context); var parts = new List<CompiledPart>(); var materials = new List<Material>(); var mass = new MassProperties(); var centerOfMass = Vector3.Zero; foreach (var mesh in model.Meshes) { MeshType type = MeshType.Both; PhysicalShape shape = PhysicalShape.Mesh; float elasticity = _defaultElasticity, roughness = _defaultRoughness, density = _defaultDensity; if (attributes.ContainsKey(mesh.Name)) { type = attributes[mesh.Name].GetAttribute(TYPE_ATTR_NAME, MeshType.Both); if (type == MeshType.Visual) continue; elasticity = attributes[mesh.Name].GetAttribute(ELASTICITY_ATTR_NAME, _defaultElasticity); roughness = attributes[mesh.Name].GetAttribute(ROUGHNESS_ATTR_NAME, _defaultRoughness); density = attributes[mesh.Name].GetAttribute(DENSITY_ATTR_NAME, _defaultDensity); shape = attributes[mesh.Name].GetAttribute(SHAPE_ATTR_NAME, _defaultShape); } var meshCenterOfMass = Vector3.Zero; var meshMass = MassProperties.Immovable; CompiledPart meshPart = null; if (mesh.MeshParts.Count < 1) { continue; } int[] indices = mesh.MeshParts[0].IndexBuffer.Skip(mesh.MeshParts[0].StartIndex).Take(mesh.MeshParts[0].PrimitiveCount * 3).ToArray(); Vector3[] vertices = MeshToVertexArray(context.TargetPlatform, mesh); if (_windingOrder == WindingOrder.Clockwise) { ReverseWindingOrder(indices); } switch (shape) { case PhysicalShape.Mesh: { meshPart = new CompiledMesh(vertices, indices); meshMass = MassProperties.Immovable; meshCenterOfMass = GetMeshTranslation(mesh); } break; case PhysicalShape.Polyhedron: { var hull = new ConvexHull3D(vertices); meshPart = hull.ToPolyhedron(); meshMass = MassProperties.FromTriMesh(density, vertices, indices, out meshCenterOfMass); } break; case PhysicalShape.Sphere: { Sphere s; Sphere.Fit(vertices, out s); meshPart = new CompiledSphere(s.Center, s.Radius); meshMass = MassProperties.FromSphere(density, s.Center, s.Radius); meshCenterOfMass = s.Center; } break; case PhysicalShape.Capsule: { Capsule c; Capsule.Fit(vertices, out c); meshPart = new CompiledCapsule(c.P1, c.P2, c.Radius); meshMass = MassProperties.FromCapsule(density, c.P1, c.P2, c.Radius, out meshCenterOfMass); } break; } parts.Add(meshPart); materials.Add(new Material(elasticity, roughness)); Vector3.Multiply(ref meshCenterOfMass, meshMass.Mass, out meshCenterOfMass); Vector3.Add(ref centerOfMass, ref meshCenterOfMass, out centerOfMass); mass.Mass += meshMass.Mass; meshMass.Inertia.M44 = 0f; Matrix.Add(ref mass.Inertia, ref meshMass.Inertia, out mass.Inertia); } // compute mass properties Vector3.Divide(ref centerOfMass, mass.Mass, out centerOfMass); mass.Inertia.M44 = 1f; MassProperties.TranslateInertiaTensor(ref mass.Inertia, -mass.Mass, centerOfMass, out mass.Inertia); if (centerOfMass.Length() >= Constants.Epsilon) { var transform = Matrix.CreateTranslation(-centerOfMass.X, -centerOfMass.Y, -centerOfMass.Z); foreach (var p in parts) { p.Transform(ref transform); } transform = model.Root.Transform; transform.M41 -= centerOfMass.X; transform.M42 -= centerOfMass.Y; transform.M43 -= centerOfMass.Z; model.Root.Transform = transform; } mass = new MassProperties(mass.Mass, mass.Inertia); //rbi.MassProperties = mass; //rbi.Materials = materials.ToArray(); //rbi.Parts = parts.ToArray(); // remove non-visual nodes if (nodesToRemove.Length > 0) { foreach (var node in nodesToRemove) input.Children.Remove(node); model = base.Process(input, context); } #endregion BaseLogic.RigidBodyInfo rbi = new BaseLogic.RigidBodyInfo(); rbi.MassProperties = mass; rbi.Materials = materials.ToArray(); rbi.Parts = parts.ToArray(); MeshData metadata = new MeshData(); BoundingBox aabb = new BoundingBox(); metadata.BoundingBox = ComputeBoundingBox(input, ref aabb, metadata); rbi.Metadata = metadata; if (_normalMapFilenames.Count != _diffuseMapFilenames.Count || _normalMapFilenames.Count != _specularMapFilenames.Count) throw new ArgumentException("Number of normal, diffuse, and specular maps don't match up."); rbi.DiffuseMapFilenames = _diffuseMapFilenames.ToArray(); rbi.NormalMapFilenames = _normalMapFilenames.ToArray(); rbi.SpecularMapFilenames = _specularMapFilenames.ToArray(); //assign it to our Tag model.Tag = (object)rbi; return model; } else { // While this type of mesh is ment for the mesh class in the rendering system implementation. ModelContent model = base.Process(input, context); MeshData metadata = new MeshData(); BoundingBox aabb = new BoundingBox(); metadata.BoundingBox = ComputeBoundingBox(input, ref aabb, metadata); model.Tag = (object)metadata; return model; } } private void MergeTransforms(NodeContent input) { if (input is MeshContent) { MeshContent mc = (MeshContent) input; MeshHelper.TransformScene(mc, mc.Transform); mc.Transform = Matrix.Identity; MeshHelper.OptimizeForCache(mc); } foreach (NodeContent c in input.Children) { MergeTransforms(c); } } private BoundingBox ComputeBoundingBox(NodeContent input, ref BoundingBox aabb, MeshData metadata) { BoundingBox boundingBox; if (input is MeshContent) { MeshContent mc = (MeshContent)input; MeshHelper.TransformScene(mc, mc.Transform); mc.Transform = Matrix.Identity; boundingBox = BoundingBox.CreateFromPoints(mc.Positions); //create sub mesh information MeshData.SubMeshData subMeshMetadata = new MeshData.SubMeshData(); subMeshMetadata.BoundingBox = boundingBox; subMeshMetadata.RenderQueue = _renderQueue; subMeshMetadata.CastShadows = CastShadows; metadata.AddSubMeshData(subMeshMetadata); if (metadata.SubMeshesMetadata.Count > 1) boundingBox = BoundingBox.CreateMerged(boundingBox, aabb); } else { boundingBox = aabb; } foreach (NodeContent c in input.Children) { boundingBox = BoundingBox.CreateMerged(boundingBox, ComputeBoundingBox(c, ref boundingBox, metadata)); } return boundingBox; } protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) { EffectMaterialContent lppMaterial = new EffectMaterialContent(); OpaqueDataDictionary processorParameters = new OpaqueDataDictionary(); processorParameters["ColorKeyColor"] = this.ColorKeyColor; processorParameters["ColorKeyEnabled"] = false; processorParameters["TextureFormat"] = this.TextureFormat; processorParameters["GenerateMipmaps"] = this.GenerateMipmaps; processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo; processorParameters["PremultiplyTextureAlpha"] = false; processorParameters["ColorKeyEnabled"] = false; lppMaterial.Effect = new ExternalReference<EffectContent>(s_customFx.Length == 0 ? "shaders/MainEffect.fx" : s_customFx); lppMaterial.CompiledEffect = context.BuildAsset<EffectContent, CompiledEffectContent>(lppMaterial.Effect, "EffectProcessor"); // copy the textures in the original material to the new lpp // material ExtractTextures(lppMaterial, material); //extract the extra parameters ExtractDefines(lppMaterial, material, context); // and convert the material using the NormalMappingMaterialProcessor, // who has something special in store for the normal map. return context.Convert<MaterialContent, MaterialContent> (lppMaterial, typeof(GameMaterialProcessor).Name, processorParameters); } /// <summary> /// Extract any defines we need from the original material, like alphaMasked, fresnel, reflection, etc, and pass it into /// the opaque data /// </summary> /// <param name="lppMaterial"></param> /// <param name="material"></param> /// <param name="context"></param> private void ExtractDefines(EffectMaterialContent lppMaterial, MaterialContent material, ContentProcessorContext context) { string defines = ""; if (material.OpaqueData.ContainsKey("alphaMasked") && material.OpaqueData["alphaMasked"].ToString() == "True") { context.Logger.LogMessage("Alpha masked material found"); lppMaterial.OpaqueData.Add("AlphaReference", (float)material.OpaqueData["AlphaReference"]); defines += "ALPHA_MASKED;"; } if (material.OpaqueData.ContainsKey("reflectionEnabled") && material.OpaqueData["reflectionEnabled"].ToString() == "True") { context.Logger.LogMessage("Reflection enabled"); defines += "REFLECTION_ENABLED;"; } if (_isSkinned) { context.Logger.LogMessage("Skinned mesh found"); defines += "SKINNED_MESH;"; } if (material.OpaqueData.ContainsKey("dualLayerEnabled") && material.OpaqueData["dualLayerEnabled"].ToString() == "True") { context.Logger.LogMessage("Dual layer material found"); defines += "DUAL_LAYER;"; } if (!String.IsNullOrEmpty(defines)) lppMaterial.OpaqueData.Add("Defines", defines); } private void ExtractTextures(EffectMaterialContent lppMaterial, MaterialContent material) { string diffuseMapFilename = null, specularMapFilename = null, normalMapFilename = null; foreach (KeyValuePair<String, ExternalReference<TextureContent>> texture in material.Textures) { if (texture.Key.ToLower().Equals("diffusemap") || texture.Key.ToLower().Equals("texture")) { lppMaterial.Textures.Add(DiffuseMapKey, texture.Value); diffuseMapFilename = texture.Value.Filename; } else if (texture.Key.ToLower().Equals("normalmap")) { lppMaterial.Textures.Add(NormalMapKey, texture.Value); normalMapFilename = texture.Value.Filename; } else if (texture.Key.ToLower().Equals("specularmap")) { lppMaterial.Textures.Add(SpecularMapKey, texture.Value); specularMapFilename = texture.Value.Filename; } else if (texture.Key.ToLower().Equals("emissivemap")) lppMaterial.Textures.Add(EmissiveMapKey, texture.Value); else if (texture.Key.ToLower().Equals("seconddiffusemap")) lppMaterial.Textures.Add(SecondDiffuseMapKey, texture.Value); else if (texture.Key.ToLower().Equals("secondnormalmap")) lppMaterial.Textures.Add(SecondNormalMapKey, texture.Value); else if (texture.Key.ToLower().Equals("secondspecularmap")) lppMaterial.Textures.Add(SecondSpecularMapKey, texture.Value); else if (texture.Key.ToLower().Equals("reflectionmap")) lppMaterial.Textures.Add(ReflectionMapKey, texture.Value); } ExternalReference<TextureContent> externalRef; if (!lppMaterial.Textures.TryGetValue(DiffuseMapKey, out externalRef)) { lppMaterial.Textures[DiffuseMapKey] = new ExternalReference<TextureContent>("images/default_diffuse.tga"); } if (!lppMaterial.Textures.TryGetValue(NormalMapKey, out externalRef)) { lppMaterial.Textures[NormalMapKey] = new ExternalReference<TextureContent>("images/default_normal.tga"); } if (!lppMaterial.Textures.TryGetValue(SpecularMapKey, out externalRef)) { lppMaterial.Textures[SpecularMapKey] = new ExternalReference<TextureContent>("images/default_specular.tga"); } if (!lppMaterial.Textures.TryGetValue(EmissiveMapKey, out externalRef)) { lppMaterial.Textures[EmissiveMapKey] = new ExternalReference<TextureContent>("images/default_emissive.tga"); } _diffuseMapFilenames.Add(diffuseMapFilename); _specularMapFilenames.Add(specularMapFilename); _normalMapFilenames.Add(normalMapFilename); } public static float GetMaxDistance(Vector3 center, IList<Vector3> vertices) { float maxDist = 0f; for (int i = 0; i < vertices.Count; i++) { var p = vertices[i]; float dist; Vector3.DistanceSquared(ref center, ref p, out dist); if (dist > maxDist) maxDist = dist; } return (float)Math.Sqrt(maxDist); } public static Vector3 GetMeshTranslation(ModelMeshContent mesh) { var pos = Vector3.Zero; var bone = mesh.ParentBone; while (bone != null) { pos += bone.Transform.Translation; bone = bone.Parent; } return pos; } public static Vector3[] MeshToVertexArray(TargetPlatform platform, ModelMeshContent mesh) { MemoryStream ms; var buffer = mesh.MeshParts[0].VertexBuffer; // if (platform == TargetPlatform.Xbox360) // { // ms = new MemoryStream(ReverseByteOrder(buffer.VertexData)); // } // else // { ms = new MemoryStream(buffer.VertexData); // } BinaryReader reader = new BinaryReader(ms); var elems = buffer.VertexDeclaration.VertexElements; int count = mesh.MeshParts[0].NumVertices; ms.Seek(mesh.MeshParts[0].VertexOffset * buffer.VertexDeclaration.VertexStride.Value, SeekOrigin.Begin); var vertices = new Vector3[count]; for (int i = 0; i < count; i++) { foreach (var elType in elems) { if (elType.VertexElementUsage == VertexElementUsage.Position) { vertices[i].X = reader.ReadSingle(); vertices[i].Y = reader.ReadSingle(); vertices[i].Z = reader.ReadSingle(); } else { switch (elType.VertexElementFormat) { case VertexElementFormat.Color: reader.ReadUInt32(); break; case VertexElementFormat.Vector2: reader.ReadSingle(); reader.ReadSingle(); break; case VertexElementFormat.Vector3: reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); break; case VertexElementFormat.Single: reader.ReadSingle(); break; case VertexElementFormat.Byte4: reader.ReadBytes(4); break; case VertexElementFormat.Vector4: reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); break; default: throw new InvalidContentException("Unrecognized element type in vertex buffer: " + elType.ToString()); } } } } var transforms = new Stack<Matrix>(); var bone = mesh.ParentBone; while (bone != null) { transforms.Push(bone.Transform); bone = bone.Parent; } var transform = Matrix.Identity; while (transforms.Count > 0) { transform *= transforms.Pop(); } Vector3.Transform(vertices, ref transform, vertices); return vertices; } public static byte[] ReverseByteOrder(byte[] source) { byte[] dest = new byte[source.Length]; for (int i = 0; i < source.Length; i += 4) { dest[i] = source[i + 3]; dest[i + 1] = source[i + 2]; dest[i + 2] = source[i + 1]; dest[i + 3] = source[i]; } return dest; } public static void ReverseWindingOrder(int[] indices) { for (int i = 0; i < indices.Length; i += 3) { indices[i + 1] = indices[i + 1] ^ indices[i + 2]; indices[i + 2] = indices[i + 1] ^ indices[i + 2]; indices[i + 1] = indices[i + 1] ^ indices[i + 2]; } } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using Ctrip.Log4.ObjectRenderer; using Ctrip.Log4.Core; using Ctrip.Log4.Util; using Ctrip.Log4.Plugin; namespace Ctrip.Log4.Repository { /// <summary> /// Base implementation of <see cref="ILoggerRepository"/> /// </summary> /// <remarks> /// <para> /// Default abstract implementation of the <see cref="ILoggerRepository"/> interface. /// </para> /// <para> /// Skeleton implementation of the <see cref="ILoggerRepository"/> interface. /// All <see cref="ILoggerRepository"/> types can extend this type. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class LoggerRepositorySkeleton : ILoggerRepository { #region Member Variables private string m_name; private RendererMap m_rendererMap; private PluginMap m_pluginMap; private LevelMap m_levelMap; private Level m_threshold; private bool m_configured; private ICollection m_configurationMessages; private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; private PropertiesDictionary m_properties; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <remarks> /// <para> /// Initializes the repository with default (empty) properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton() : this(new PropertiesDictionary()) { } /// <summary> /// Construct the repository using specific properties /// </summary> /// <param name="properties">the properties to set for this repository</param> /// <remarks> /// <para> /// Initializes the repository with specified properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton(PropertiesDictionary properties) { m_properties = properties; m_rendererMap = new RendererMap(); m_pluginMap = new PluginMap(this); m_levelMap = new LevelMap(); m_configurationMessages = EmptyCollection.Instance; m_configured = false; AddBuiltinLevels(); // Don't disable any levels by default. m_threshold = Level.All; } #endregion #region Implementation of ILoggerRepository /// <summary> /// The name of the repository /// </summary> /// <value> /// The string name of the repository /// </value> /// <remarks> /// <para> /// The name of this repository. The name is /// used to store and lookup the repositories /// stored by the <see cref="IRepositorySelector"/>. /// </para> /// </remarks> virtual public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// The threshold for all events in this repository /// </summary> /// <value> /// The threshold for all events in this repository /// </value> /// <remarks> /// <para> /// The threshold for all events in this repository /// </para> /// </remarks> virtual public Level Threshold { get { return m_threshold; } set { if (value != null) { m_threshold = value; } else { // Must not set threshold to null LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); m_threshold = Level.All; } } } /// <summary> /// RendererMap accesses the object renderer map for this repository. /// </summary> /// <value> /// RendererMap accesses the object renderer map for this repository. /// </value> /// <remarks> /// <para> /// RendererMap accesses the object renderer map for this repository. /// </para> /// <para> /// The RendererMap holds a mapping between types and /// <see cref="IObjectRenderer"/> objects. /// </para> /// </remarks> virtual public RendererMap RendererMap { get { return m_rendererMap; } } /// <summary> /// The plugin map for this repository. /// </summary> /// <value> /// The plugin map for this repository. /// </value> /// <remarks> /// <para> /// The plugin map holds the <see cref="IPlugin"/> instances /// that have been attached to this repository. /// </para> /// </remarks> virtual public PluginMap PluginMap { get { return m_pluginMap; } } /// <summary> /// Get the level map for the Repository. /// </summary> /// <remarks> /// <para> /// Get the level map for the Repository. /// </para> /// <para> /// The level map defines the mappings between /// level names and <see cref="Level"/> objects in /// this repository. /// </para> /// </remarks> virtual public LevelMap LevelMap { get { return m_levelMap; } } /// <summary> /// Test if logger exists /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> /// <remarks> /// <para> /// Check if the named logger exists in the repository. If so return /// its reference, otherwise returns <c>null</c>. /// </para> /// </remarks> abstract public ILogger Exists(string name); /// <summary> /// Returns all the currently defined loggers in the repository /// </summary> /// <returns>All the defined loggers</returns> /// <remarks> /// <para> /// Returns all the currently defined loggers in the repository as an Array. /// </para> /// </remarks> abstract public ILogger[] GetCurrentLoggers(); /// <summary> /// Return a new logger instance /// </summary> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> /// <remarks> /// <para> /// Return a new logger instance. /// </para> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children. /// </para> /// </remarks> abstract public ILogger GetLogger(string name); /// <summary> /// Shutdown the repository /// </summary> /// <remarks> /// <para> /// Shutdown the repository. Can be overridden in a subclass. /// This base class implementation notifies the <see cref="ShutdownEvent"/> /// listeners and all attached plugins of the shutdown event. /// </para> /// </remarks> virtual public void Shutdown() { // Shutdown attached plugins foreach(IPlugin plugin in PluginMap.AllPlugins) { plugin.Shutdown(); } // Notify listeners OnShutdown(null); } /// <summary> /// Reset the repositories configuration to a default state /// </summary> /// <remarks> /// <para> /// Reset all values contained in this instance to their /// default state. /// </para> /// <para> /// Existing loggers are not removed. They are just reset. /// </para> /// <para> /// This method should be used sparingly and with care as it will /// block all logging until it is completed. /// </para> /// </remarks> virtual public void ResetConfiguration() { // Clear internal data structures m_rendererMap.Clear(); m_levelMap.Clear(); m_configurationMessages = EmptyCollection.Instance; // Add the predefined levels to the map AddBuiltinLevels(); Configured = false; // Notify listeners OnConfigurationReset(null); } /// <summary> /// Log the logEvent through this repository. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="M:Ctrip.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> abstract public void Log(LoggingEvent logEvent); /// <summary> /// Flag indicates if this repository has been configured. /// </summary> /// <value> /// Flag indicates if this repository has been configured. /// </value> /// <remarks> /// <para> /// Flag indicates if this repository has been configured. /// </para> /// </remarks> virtual public bool Configured { get { return m_configured; } set { m_configured = value; } } /// <summary> /// Contains a list of internal messages captures during the /// last configuration. /// </summary> virtual public ICollection ConfigurationMessages { get { return m_configurationMessages; } set { m_configurationMessages = value; } } /// <summary> /// Event to notify that the repository has been shutdown. /// </summary> /// <value> /// Event to notify that the repository has been shutdown. /// </value> /// <remarks> /// <para> /// Event raised when the repository has been shutdown. /// </para> /// </remarks> public event LoggerRepositoryShutdownEventHandler ShutdownEvent { add { m_shutdownEvent += value; } remove { m_shutdownEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration reset. /// </summary> /// <value> /// Event to notify that the repository has had its configuration reset. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been /// reset to default. /// </para> /// </remarks> public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset { add { m_configurationResetEvent += value; } remove { m_configurationResetEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration changed. /// </summary> /// <value> /// Event to notify that the repository has had its configuration changed. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been changed. /// </para> /// </remarks> public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged { add { m_configurationChangedEvent += value; } remove { m_configurationChangedEvent -= value; } } /// <summary> /// Repository specific properties /// </summary> /// <value> /// Repository specific properties /// </value> /// <remarks> /// These properties can be specified on a repository specific basis /// </remarks> public PropertiesDictionary Properties { get { return m_properties; } } /// <summary> /// Returns all the Appenders that are configured as an Array. /// </summary> /// <returns>All the Appenders</returns> /// <remarks> /// <para> /// Returns all the Appenders that are configured as an Array. /// </para> /// </remarks> abstract public Ctrip.Log4.Appender.IAppender[] GetAppenders(); #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the LoggerRepositorySkeleton class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LoggerRepositorySkeleton); #endregion Private Static Fields private void AddBuiltinLevels() { // Add the predefined levels to the map m_levelMap.Add(Level.Off); // Unrecoverable errors m_levelMap.Add(Level.Emergency); m_levelMap.Add(Level.Fatal); m_levelMap.Add(Level.Alert); // Recoverable errors m_levelMap.Add(Level.Critical); m_levelMap.Add(Level.Severe); m_levelMap.Add(Level.Error); m_levelMap.Add(Level.Warn); // Information m_levelMap.Add(Level.Notice); m_levelMap.Add(Level.Info); // Debug m_levelMap.Add(Level.Debug); m_levelMap.Add(Level.Fine); m_levelMap.Add(Level.Trace); m_levelMap.Add(Level.Finer); m_levelMap.Add(Level.Verbose); m_levelMap.Add(Level.Finest); m_levelMap.Add(Level.All); } /// <summary> /// Adds an object renderer for a specific class. /// </summary> /// <param name="typeToRender">The type that will be rendered by the renderer supplied.</param> /// <param name="rendererInstance">The object renderer used to render the object.</param> /// <remarks> /// <para> /// Adds an object renderer for a specific class. /// </para> /// </remarks> virtual public void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) { if (typeToRender == null) { throw new ArgumentNullException("typeToRender"); } if (rendererInstance == null) { throw new ArgumentNullException("rendererInstance"); } m_rendererMap.Put(typeToRender, rendererInstance); } /// <summary> /// Notify the registered listeners that the repository is shutting down /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository is shutting down. /// </para> /// </remarks> protected virtual void OnShutdown(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryShutdownEventHandler handler = m_shutdownEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration reset /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has been reset. /// </para> /// </remarks> protected virtual void OnConfigurationReset(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationResetEventHandler handler = m_configurationResetEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration changed /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has changed. /// </para> /// </remarks> protected virtual void OnConfigurationChanged(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationChangedEventHandler handler = m_configurationChangedEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Raise a configuration changed event on this repository /// </summary> /// <param name="e">EventArgs.Empty</param> /// <remarks> /// <para> /// Applications that programmatically change the configuration of the repository should /// raise this event notification to notify listeners. /// </para> /// </remarks> public void RaiseConfigurationChanged(EventArgs e) { OnConfigurationChanged(e); } } }
/* * 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 Lucene.Net.Codecs.BlockTerms { using System; using System.Collections.Generic; using System.Diagnostics; using Codecs; using Index; using Store; using Util; using Util.Fst; /// <summary> /// Selects index terms according to provided pluggable /// {@link IndexTermSelector}, and stores them in a prefix trie that's /// loaded entirely in RAM stored as an FST. This terms /// index only supports unsigned byte term sort order /// (unicode codepoint order when the bytes are UTF8). /// /// @lucene.experimental /// </summary> public class VariableGapTermsIndexWriter : TermsIndexWriterBase { protected IndexOutput Output; /** Extension of terms index file */ public const String TERMS_INDEX_EXTENSION = "tiv"; public const String CODEC_NAME = "VARIABLE_GAP_TERMS_INDEX"; public const int VERSION_START = 0; public const int VERSION_APPEND_ONLY = 1; public const int VERSION_CHECKSUM = 2; public const int VERSION_CURRENT = VERSION_CHECKSUM; private readonly List<FstFieldWriter> _fields = new List<FstFieldWriter>(); private readonly IndexTermSelector _policy; /// <summary> /// Hook for selecting which terms should be placed in the terms index /// /// IsIndexTerm for each term in that field /// NewField is called at the start of each new field /// /// @lucene.experimental /// </summary> public abstract class IndexTermSelector { /// <summary> /// Called sequentially on every term being written /// returning true if this term should be indexed /// </summary> public abstract bool IsIndexTerm(BytesRef term, TermStats stats); /// <summary>Called when a new field is started</summary> public abstract void NewField(FieldInfo fieldInfo); } /// <remarks> /// Same policy as {@link FixedGapTermsIndexWriter} /// </remarks> public class EveryNTermSelector : IndexTermSelector { private int _count; private readonly int _interval; public EveryNTermSelector(int interval) { _interval = interval; _count = interval; // First term is first indexed term } public override bool IsIndexTerm(BytesRef term, TermStats stats) { if (_count >= _interval) { _count = 1; return true; } _count++; return false; } public override void NewField(FieldInfo fieldInfo) { _count = _interval; } } /// <summary> /// Sets an index term when docFreq >= docFreqThresh, or /// every interval terms. This should reduce seek time /// to high docFreq terms. /// </summary> public class EveryNOrDocFreqTermSelector : IndexTermSelector { private int _count; private readonly int _docFreqThresh; private readonly int _interval; public EveryNOrDocFreqTermSelector(int docFreqThresh, int interval) { _interval = interval; _docFreqThresh = docFreqThresh; _count = interval; // First term is first indexed term } public override bool IsIndexTerm(BytesRef term, TermStats stats) { if (stats.DocFreq >= _docFreqThresh || _count >= _interval) { _count = 1; return true; } _count++; return false; } public override void NewField(FieldInfo fieldInfo) { _count = _interval; } } // TODO: it'd be nice to let the FST builder prune based // on term count of each node (the prune1/prune2 that it // accepts), and build the index based on that. This // should result in a more compact terms index, more like // a prefix trie than the other selectors, because it // only stores enough leading bytes to get down to N // terms that may complete that prefix. It becomes // "deeper" when terms are dense, and "shallow" when they // are less dense. // // However, it's not easy to make that work this this // API, because that pruning doesn't immediately know on // seeing each term whether that term will be a seek point // or not. It requires some non-causality in the API, ie // only on seeing some number of future terms will the // builder decide which past terms are seek points. // Somehow the API'd need to be able to return a "I don't // know" value, eg like a Future, which only later on is // flipped (frozen) to true or false. // // We could solve this with a 2-pass approach, where the // first pass would build an FSA (no outputs) solely to // determine which prefixes are the 'leaves' in the // pruning. The 2nd pass would then look at this prefix // trie to mark the seek points and build the FST mapping // to the true output. // // But, one downside to this approach is that it'd result // in uneven index term selection. EG with prune1=10, the // resulting index terms could be as frequent as every 10 // terms or as rare as every <maxArcCount> * 10 (eg 2560), // in the extremes. public VariableGapTermsIndexWriter(SegmentWriteState state, IndexTermSelector policy) { string indexFileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, TERMS_INDEX_EXTENSION); Output = state.Directory.CreateOutput(indexFileName, state.Context); bool success = false; try { _policy = policy; WriteHeader(Output); success = true; } finally { if (!success) IOUtils.CloseWhileHandlingException(Output); } } private static void WriteHeader(IndexOutput output) { CodecUtil.WriteHeader(output, CODEC_NAME, VERSION_CURRENT); } public override FieldWriter AddField(FieldInfo field, long termsFilePointer) { _policy.NewField(field); var writer = new FstFieldWriter(field, termsFilePointer, this); _fields.Add(writer); return writer; } /// <remarks> /// Note: If your codec does not sort in unicode code point order, /// you must override this method to simplly return IndexedTerm.Length /// </remarks> protected int IndexedTermPrefixLength(BytesRef priorTerm, BytesRef indexedTerm) { // As long as codec sorts terms in unicode codepoint // order, we can safely strip off the non-distinguishing // suffix to save RAM in the loaded terms index. int idxTermOffset = indexedTerm.Offset; int priorTermOffset = priorTerm.Offset; int limit = Math.Min(priorTerm.Length, indexedTerm.Length); for (int byteIdx = 0; byteIdx < limit; byteIdx++) { if (priorTerm.Bytes[priorTermOffset + byteIdx] != indexedTerm.Bytes[idxTermOffset + byteIdx]) { return byteIdx + 1; } } return Math.Min(1 + priorTerm.Length, indexedTerm.Length); } private class FstFieldWriter : FieldWriter { private readonly Builder<long?> _fstBuilder; private readonly long _startTermsFilePointer; private readonly BytesRef _lastTerm = new BytesRef(); private readonly IntsRef _scratchIntsRef = new IntsRef(); private readonly VariableGapTermsIndexWriter _vgtiw; private bool _first = true; public long IndexStart { get; private set; } public FieldInfo FieldInfo { get; private set; } public FST<long?> Fst { get; private set; } public FstFieldWriter(FieldInfo fieldInfo, long termsFilePointer, VariableGapTermsIndexWriter vgtiw) { _vgtiw = vgtiw; FieldInfo = fieldInfo; PositiveIntOutputs fstOutputs = PositiveIntOutputs.Singleton; _fstBuilder = new Builder<long?>(FST.INPUT_TYPE.BYTE1, fstOutputs); IndexStart = _vgtiw.Output.FilePointer; // Always put empty string in _fstBuilder.Add(new IntsRef(), termsFilePointer); _startTermsFilePointer = termsFilePointer; } public override bool CheckIndexTerm(BytesRef text, TermStats stats) { // NOTE: we must force the first term per field to be // indexed, in case policy doesn't: if (_vgtiw._policy.IsIndexTerm(text, stats) || _first) { _first = false; return true; } _lastTerm.CopyBytes(text); return false; } public override void Add(BytesRef text, TermStats stats, long termsFilePointer) { if (text.Length == 0) { // We already added empty string in ctor Debug.Assert(termsFilePointer == _startTermsFilePointer); return; } int lengthSave = text.Length; text.Length = _vgtiw.IndexedTermPrefixLength(_lastTerm, text); try { _fstBuilder.Add(Util.ToIntsRef(text, _scratchIntsRef), termsFilePointer); } finally { text.Length = lengthSave; } _lastTerm.CopyBytes(text); } public override void Finish(long termsFilePointer) { Fst = _fstBuilder.Finish(); if (Fst != null) Fst.Save(_vgtiw.Output); } } public override void Dispose() { if (Output == null) return; try { long dirStart = Output.FilePointer; int fieldCount = _fields.Count; int nonNullFieldCount = 0; for (int i = 0; i < fieldCount; i++) { FstFieldWriter field = _fields[i]; if (field.Fst != null) { nonNullFieldCount++; } } Output.WriteVInt(nonNullFieldCount); for (int i = 0; i < fieldCount; i++) { FstFieldWriter field = _fields[i]; if (field.Fst != null) { Output.WriteVInt(field.FieldInfo.Number); Output.WriteVLong(field.IndexStart); } } WriteTrailer(dirStart); CodecUtil.WriteFooter(Output); } finally { Output.Dispose(); Output = null; } } private void WriteTrailer(long dirStart) { Output.WriteLong(dirStart); } } }
/*************************************************************************** * Dap.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.IO; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Banshee.Gui; using Banshee.Base; using Banshee.Widgets; using Banshee.Sources; using Banshee.Plugins; using Banshee.AudioProfiles; namespace Banshee.Dap { public abstract class DapDevice : IPlugin, IEnumerable<TrackInfo>, IEnumerable { public class Property { private string name; private string val; public string Name { get { return name; } internal set { name = value; } } public string Value { get { return val; } internal set { val = value; } } } public class PropertyTable : IEnumerable { private ArrayList properties = new ArrayList(); private Property Find(string name) { foreach(Property property in properties) { if(property.Name == name) { return property; } } return null; } public void Add(string name, string value) { if(value == null || value.Trim() == String.Empty) { return; } Property property = Find(name); if(property != null) { property.Value = value; return; } property = new Property(); property.Name = name; property.Value = value; properties.Add(property); } public string this [string name] { get { Property property = Find(name); return property == null ? null : property.Value; } } public IEnumerator GetEnumerator() { foreach(Property property in properties) { yield return property; } } } private static uint current_uid = 1; private static uint NextUid { get { return current_uid++; } } private uint uid; private PropertyTable properties = new PropertyTable(); private ActiveUserEvent save_report_event; private bool is_syncing = false; private bool can_cancel_save = true; private DapProperties type_properties; protected List<TrackInfo> tracks = new List<TrackInfo>(); public event DapTrackListUpdatedHandler TrackAdded; public event DapTrackListUpdatedHandler TrackRemoved; public event EventHandler TracksCleared; public event EventHandler PropertiesChanged; public event EventHandler Ejected; public event EventHandler SaveStarted; public event EventHandler SaveFinished; public event EventHandler Reactivate; public Hal.Device HalDevice; private DapSource source; public virtual InitializeResult Initialize(Hal.Device halDevice) { Attribute [] dap_attrs = Attribute.GetCustomAttributes(GetType(), typeof(DapProperties)); if(dap_attrs != null && dap_attrs.Length >= 1) { type_properties = dap_attrs[0] as DapProperties; } uid = NextUid; source = new DapSource(this); SourceManager.AddSource(source); return InitializeResult.Valid; } protected InitializeResult WaitForVolumeMount(Hal.Device halDevice) { DapCore.QueueWaitForVolumeMount(halDevice); return InitializeResult.WaitForVolumeMount; } public uint Uid { get { return uid; } } public DapSource Source { get { return source; } } IEnumerator IEnumerable.GetEnumerator() { return tracks.GetEnumerator(); } public IEnumerator<TrackInfo> GetEnumerator() { return tracks.GetEnumerator(); } protected void OnPropertiesChanged() { EventHandler handler = PropertiesChanged; if(handler != null) { handler(this, new EventArgs()); } } protected void OnReactivate() { EventHandler handler = Reactivate; if(handler != null) { handler(this, new EventArgs()); } } protected void InstallProperty(string name, string value) { properties.Add(name, value); OnPropertiesChanged(); } public virtual void AddTrack(TrackInfo track) { if(track == null) { return; } tracks.Add(track); OnTrackAdded(track); } public void RemoveTrack(TrackInfo track) { tracks.Remove(track); OnTrackRemoved(track); DapTrackListUpdatedHandler handler = TrackRemoved; if(handler != null) { handler(this, new DapTrackListUpdatedArgs(track)); } } public virtual void Dispose() { if(source != null) { SourceManager.RemoveSource(source); } } public void ClearTracks() { ClearTracks(true); } protected void ClearTracks(bool notify) { tracks.Clear(); if(notify) { OnTracksCleared(); EventHandler handler = TracksCleared; if(handler != null) { handler(this, new EventArgs()); } } } protected virtual void OnTrackAdded (TrackInfo track) { DapTrackListUpdatedHandler handler = TrackAdded; if(handler != null) { handler(this, new DapTrackListUpdatedArgs(track)); } } protected virtual void OnTrackRemoved(TrackInfo track) { } protected virtual void OnTracksCleared() { } public virtual void Activate() { } public virtual void Eject() { EventHandler handler = Ejected; if(handler != null) { handler(this, new EventArgs()); } } private string ToLower(string str) { return str == null ? null : str.ToLower(); } private bool TrackCompare(TrackInfo a, TrackInfo b) { return ToLower(a.Title) == ToLower(b.Title) && ToLower(a.Album) == ToLower(b.Album) && ToLower(a.Artist) == ToLower(b.Artist) && a.Year == b.Year && a.TrackNumber == b.TrackNumber; } protected bool TrackExistsInList(TrackInfo track, ICollection<TrackInfo> list) { try { foreach(TrackInfo track_b in list) { if(TrackCompare(track, track_b)) { return true; } } } catch(Exception) { } return false; } public void Save(ICollection<TrackInfo> library) { Queue remove_queue = new Queue(); foreach(TrackInfo ti in Tracks) { if(TrackExistsInList(ti, library)) { continue; } remove_queue.Enqueue(ti); } while(remove_queue.Count > 0) { RemoveTrack(remove_queue.Dequeue() as TrackInfo); } foreach(TrackInfo ti in library) { if(TrackExistsInList(ti, Tracks) || ti.Uri == null) { continue; } AddTrack(ti); } Save(); } public void Save() { is_syncing = true; EventHandler handler = SaveStarted; if(handler != null) { handler(this, new EventArgs()); } string aue_name = Name == null || Name == String.Empty ? Catalog.GetString("Device") : Name; string aue_title = String.Format(Catalog.GetString("Synchronizing {0}"), aue_name); save_report_event = new ActiveUserEvent(aue_title); save_report_event.Header = aue_title; save_report_event.Message = Catalog.GetString("Waiting for transcoder..."); save_report_event.Icon = GetIcon(22); save_report_event.CanCancel = can_cancel_save; ThreadAssist.Spawn(Transcode); } protected bool ShouldCancelSave { get { return save_report_event.IsCancelRequested; } } protected bool CanCancelSave { set { can_cancel_save = value; } } protected void UpdateSaveProgress(string header, string message, double progress) { save_report_event.Header = header; save_report_event.Message = message; save_report_event.Progress = progress; } protected void FinishSave() { is_syncing = false; ThreadAssist.ProxyToMain(delegate { save_report_event.Dispose(); save_report_event = null; EventHandler handler = SaveFinished; if(handler != null) { handler(this, new EventArgs()); } }); } private BatchTranscoder encoder = null; private void Transcode() { Profile profile = Globals.AudioProfileManager.GetConfiguredActiveProfile(ID, SupportedPlaybackMimeTypes); Queue remove_queue = new Queue(); foreach(TrackInfo track in Tracks) { if(track == null || track.Uri == null) { continue; } string cached_filename = GetCachedSongFileName(track.Uri); if(cached_filename == null) { if(profile == null) { remove_queue.Enqueue(track); continue; } SafeUri old_uri = track.Uri; try { track.Uri = ConvertSongFileName(track.Uri, profile.OutputFileExtension); } catch { continue; } if(encoder == null) { encoder = new BatchTranscoder(profile, type_properties.PipelineName); encoder.FileFinished += OnFileEncodeComplete; encoder.BatchFinished += OnFileEncodeBatchFinished; encoder.Canceled += OnFileEncodeCanceled; } encoder.AddTrack(old_uri, track.Uri); } else { if(System.IO.File.Exists(cached_filename)) { track.Uri = new SafeUri(cached_filename); } else { remove_queue.Enqueue(track); } } } while(remove_queue.Count > 0) { RemoveTrack(remove_queue.Dequeue() as TrackInfo); } if(encoder == null) { save_report_event.Message = Catalog.GetString("Processing..."); Synchronize(); } else { encoder.Start(); } } private bool encoder_canceled = false; private void OnFileEncodeCanceled(object o, EventArgs args) { encoder_canceled = true; } private void OnFileEncodeComplete(object o, FileCompleteArgs args) { } private void OnFileEncodeBatchFinished(object o, EventArgs args) { if(!encoder_canceled) { save_report_event.Message = Catalog.GetString("Processing..."); BatchTranscoder encoder = o as BatchTranscoder; if(encoder.ErrorCount > 0) { ThreadAssist.ProxyToMain(delegate { HandleTranscodeErrors(encoder); }); } else { ChainSynchronize(); } } else { FinishSave(); } } private void HandleTranscodeErrors(BatchTranscoder encoder) { ErrorListDialog dialog = new ErrorListDialog(); dialog.IconNameStock = Gtk.Stock.DialogError; dialog.Header = Catalog.GetString("Could not encode some files"); dialog.Message = Catalog.GetString( "Some files could not be encoded to the proper format. " + "They will not be saved to the device if you continue." ); dialog.AddStockButton(Gtk.Stock.Cancel, Gtk.ResponseType.Cancel); dialog.AddButton(Catalog.GetString("Continue synchronizing"), Gtk.ResponseType.Ok); foreach(BatchTranscoder.QueueItem item in encoder.ErrorList) { if(item.Source is TrackInfo) { TrackInfo track = item.Source as TrackInfo; dialog.AppendString(String.Format("{0} - {1}", track.Artist, track.Title)); } else if(item.Source is SafeUri) { SafeUri uri = item.Source as SafeUri; dialog.AppendString(System.IO.Path.GetFileName(uri.LocalPath)); } else { dialog.AppendString(item.Source.ToString()); } } try { if(dialog.Run() == Gtk.ResponseType.Ok) { ChainSynchronize(); } else { FinishSave(); } } finally { dialog.Destroy(); } } private void ChainSynchronize() { if(ThreadAssist.InMainThread) { ThreadAssist.Spawn(Synchronize); } else { Synchronize(); } } private string [] supported_extensions = null; protected string [] SupportedExtensions { get { if(supported_extensions != null) { return supported_extensions; } Attribute [] attrs = Attribute.GetCustomAttributes(GetType(), typeof(SupportedCodec)); ArrayList extensions = new ArrayList(); foreach(SupportedCodec codec in attrs) { foreach(string extension in CodecType.GetExtensions(codec.CodecType)) { extensions.Add(extension); } } supported_extensions = extensions.ToArray(typeof(string)) as string []; return supported_extensions; } set { supported_extensions = value; } } protected string PipelineCodecFilter { get { string filter = String.Empty; for(int i = 0, n = SupportedExtensions.Length; i < n; i++) { filter += String.Format("{0}{1}", SupportedExtensions[i], (i < n - 1) ? "," : ""); } return filter; } } private bool ValidSongFormat(string filename) { string ext = Path.GetExtension(filename).ToLower().Trim(); foreach(string vext in SupportedExtensions) { if(ext == "." + vext) { return true; } } return false; } private string GetCachedSongFileName(SafeUri uri) { string filename = uri.LocalPath; if(ValidSongFormat(filename)) { return filename; } string path = PathUtil.MakeFileNameKey(uri); string dir = Path.GetDirectoryName(path); string file = Path.GetFileNameWithoutExtension(filename); foreach(string vext in SupportedExtensions) { string newfile = dir + Path.DirectorySeparatorChar + ".banshee-dap-" + file + "." + vext; if(File.Exists(newfile)) { return newfile; } } foreach(string vext in SupportedExtensions) { string newfile = path + "." + vext; if(File.Exists(newfile)) { return newfile; } } return null; } private SafeUri ConvertSongFileName(SafeUri uri, string newext) { string filename = uri.LocalPath; string path = PathUtil.MakeFileNameKey(uri); string dir = Path.GetDirectoryName(path); string file = Path.GetFileNameWithoutExtension(filename); return new SafeUri(dir + Path.DirectorySeparatorChar + ".banshee-dap-" + file + "." + newext); } public virtual Gdk.Pixbuf GetIcon(int size) { Gdk.Pixbuf pixbuf = IconThemeUtils.LoadIcon("multimedia-player", size); if(pixbuf == null) { return IconThemeUtils.LoadIcon("gnome-dev-ipod", size); } return pixbuf; } public virtual void SetName(string name) { } public virtual void SetOwner(string owner) { } public PropertyTable Properties { get { return properties; } } public TrackInfo this [int index] { get { return tracks[index]; } } public int TrackCount { get { return tracks.Count; } } public IList<TrackInfo> Tracks { get { return tracks; } } public bool IsSyncing { get { return is_syncing; } } public virtual string GenericName { get { return "DAP"; } } public string HalUdi { get { return HalDevice.Udi; } } public bool CanSetName { get { return ReflectionUtil.IsVirtualMethodImplemented(GetType(), "SetName"); } } public bool CanSetOwner { get { return ReflectionUtil.IsVirtualMethodImplemented(GetType(), "SetOwner"); } } public virtual bool CanSynchronize { get { return true; } } public virtual string Owner { get { return Catalog.GetString("Unknown"); } } public virtual Gtk.Widget ViewWidget { get { return null; } } private string [] supported_playback_mime_types; public string [] SupportedPlaybackMimeTypes { get { if(supported_playback_mime_types == null) { List<string> types = new List<string>(); foreach(object attr in GetType().GetCustomAttributes(true)) { if(attr is SupportedCodec) { foreach(string mimetype in (attr as SupportedCodec).MimeTypes) { types.Add(mimetype); } } } supported_playback_mime_types = types.ToArray(); } return supported_playback_mime_types; } protected set { supported_playback_mime_types = value; } } private string id; public string ID { get { if(id == null) { string [] parts = HalUdi.Split('/'); id = parts[parts.Length - 1]; } return id; } } public abstract void Synchronize(); public abstract string Name { get; } public abstract ulong StorageCapacity { get; } public abstract ulong StorageUsed { get; } public abstract bool IsReadOnly { get; } public abstract bool IsPlaybackSupported { get; } } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.EventSystems; using System.Linq; using MoonSharp.Interpreter; namespace Fungus { /// <summary> /// Presents multiple choice buttons to the players. /// </summary> public class MenuDialog : MonoBehaviour { [Tooltip("Automatically select the first interactable button when the menu is shown.")] [SerializeField] protected bool autoSelectFirstButton = false; protected Button[] cachedButtons; protected Slider cachedSlider; private int nextOptionIndex; #region Public members /// <summary> /// Currently active Menu Dialog used to display Menu options /// </summary> public static MenuDialog ActiveMenuDialog { get; set; } /// <summary> /// A cached list of button objects in the menu dialog. /// </summary> /// <value>The cached buttons.</value> public virtual Button[] CachedButtons { get { return cachedButtons; } } /// <summary> /// A cached slider object used for the timer in the menu dialog. /// </summary> /// <value>The cached slider.</value> public virtual Slider CachedSlider { get { return cachedSlider; } } /// <summary> /// Sets the active state of the Menu Dialog gameobject. /// </summary> public virtual void SetActive(bool state) { gameObject.SetActive(state); } /// <summary> /// Returns a menu dialog by searching for one in the scene or creating one if none exists. /// </summary> public static MenuDialog GetMenuDialog() { if (ActiveMenuDialog == null) { // Use first Menu Dialog found in the scene (if any) var md = GameObject.FindObjectOfType<MenuDialog>(); if (md != null) { ActiveMenuDialog = md; } if (ActiveMenuDialog == null) { // Auto spawn a menu dialog object from the prefab GameObject prefab = Resources.Load<GameObject>("Prefabs/MenuDialog"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.SetActive(false); go.name = "MenuDialog"; ActiveMenuDialog = go.GetComponent<MenuDialog>(); } } } return ActiveMenuDialog; } protected virtual void Awake() { Button[] optionButtons = GetComponentsInChildren<Button>(); cachedButtons = optionButtons; Slider timeoutSlider = GetComponentInChildren<Slider>(); cachedSlider = timeoutSlider; if (Application.isPlaying) { // Don't auto disable buttons in the editor Clear(); } CheckEventSystem(); } // There must be an Event System in the scene for Say and Menu input to work. // This method will automatically instantiate one if none exists. protected virtual void CheckEventSystem() { EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>(); if (eventSystem == null) { // Auto spawn an Event System from the prefab GameObject prefab = Resources.Load<GameObject>("Prefabs/EventSystem"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.name = "EventSystem"; } } } protected virtual void OnEnable() { // The canvas may fail to update if the menu dialog is enabled in the first game frame. // To fix this we just need to force a canvas update when the object is enabled. Canvas.ForceUpdateCanvases(); } protected virtual IEnumerator WaitForTimeout(float timeoutDuration, Block targetBlock) { float elapsedTime = 0; Slider timeoutSlider = CachedSlider; while (elapsedTime < timeoutDuration) { if (timeoutSlider != null) { float t = 1f - elapsedTime / timeoutDuration; timeoutSlider.value = t; } elapsedTime += Time.deltaTime; yield return null; } Clear(); gameObject.SetActive(false); HideSayDialog(); if (targetBlock != null) { targetBlock.StartExecution(); } } protected IEnumerator CallBlock(Block block) { yield return new WaitForEndOfFrame(); block.StartExecution(); } protected IEnumerator CallLuaClosure(LuaEnvironment luaEnv, Closure callback) { yield return new WaitForEndOfFrame(); if (callback != null) { luaEnv.RunLuaFunction(callback, true); } } /// <summary> /// Clear all displayed options in the Menu Dialog. /// </summary> public virtual void Clear() { StopAllCoroutines(); //if something was shown notify that we are ending if(nextOptionIndex != 0) MenuSignals.DoMenuEnd(this); nextOptionIndex = 0; var optionButtons = CachedButtons; for (int i = 0; i < optionButtons.Length; i++) { var button = optionButtons[i]; button.onClick.RemoveAllListeners(); } for (int i = 0; i < optionButtons.Length; i++) { var button = optionButtons[i]; if (button != null) { button.transform.SetSiblingIndex(i); button.gameObject.SetActive(false); } } Slider timeoutSlider = CachedSlider; if (timeoutSlider != null) { timeoutSlider.gameObject.SetActive(false); } } /// <summary> /// Hides any currently displayed Say Dialog. /// </summary> public virtual void HideSayDialog() { var sayDialog = SayDialog.GetSayDialog(); if (sayDialog != null) { sayDialog.FadeWhenDone = true; } } /// <summary> /// Adds the option to the list of displayed options. Calls a Block when selected. /// Will cause the Menu dialog to become visible if it is not already visible. /// </summary> /// <returns><c>true</c>, if the option was added successfully.</returns> /// <param name="text">The option text to display on the button.</param> /// <param name="interactable">If false, the option is displayed but is not selectable.</param> /// <param name="hideOption">If true, the option is not displayed but the menu knows that option can or did exist</param> /// <param name="targetBlock">Block to execute when the option is selected.</param> public virtual bool AddOption(string text, bool interactable, bool hideOption, Block targetBlock) { var block = targetBlock; UnityEngine.Events.UnityAction action = delegate { EventSystem.current.SetSelectedGameObject(null); StopAllCoroutines(); // Stop timeout Clear(); HideSayDialog(); if (block != null) { var flowchart = block.GetFlowchart(); gameObject.SetActive(false); // Use a coroutine to call the block on the next frame // Have to use the Flowchart gameobject as the MenuDialog is now inactive flowchart.StartCoroutine(CallBlock(block)); } }; return AddOption(text, interactable, hideOption, action); } /// <summary> /// Adds the option to the list of displayed options, calls a Lua function when selected. /// Will cause the Menu dialog to become visible if it is not already visible. /// </summary> /// <returns><c>true</c>, if the option was added successfully.</returns> public virtual bool AddOption(string text, bool interactable, LuaEnvironment luaEnv, Closure callBack) { if (!gameObject.activeSelf) { gameObject.SetActive(true); } // Copy to local variables LuaEnvironment env = luaEnv; Closure call = callBack; UnityEngine.Events.UnityAction action = delegate { StopAllCoroutines(); // Stop timeout Clear(); HideSayDialog(); // Use a coroutine to call the callback on the next frame StartCoroutine(CallLuaClosure(env, call)); }; return AddOption(text, interactable, false, action); } /// <summary> /// Adds the option to the list of displayed options. Calls a Block when selected. /// Will cause the Menu dialog to become visible if it is not already visible. /// </summary> /// <returns><c>true</c>, if the option was added successfully.</returns> /// <param name="text">The option text to display on the button.</param> /// <param name="interactable">If false, the option is displayed but is not selectable.</param> /// <param name="hideOption">If true, the option is not displayed but the menu knows that option can or did exist</param> /// <param name="action">Action attached to the button on the menu item</param> private bool AddOption(string text, bool interactable, bool hideOption, UnityEngine.Events.UnityAction action) { if (nextOptionIndex >= CachedButtons.Length) { Debug.LogWarning("Unable to add menu item, not enough buttons: " + text); return false; } //if first option notify that a menu has started if(nextOptionIndex == 0) MenuSignals.DoMenuStart(this); var button = cachedButtons[nextOptionIndex]; //move forward for next call nextOptionIndex++; //don't need to set anything on it if (hideOption) return true; button.gameObject.SetActive(true); button.interactable = interactable; if (interactable && autoSelectFirstButton && !cachedButtons.Select(x => x.gameObject).Contains(EventSystem.current.currentSelectedGameObject)) { EventSystem.current.SetSelectedGameObject(button.gameObject); } TextAdapter textAdapter = new TextAdapter(); textAdapter.InitFromGameObject(button.gameObject, true); if (textAdapter.HasTextObject()) { text = TextVariationHandler.SelectVariations(text); textAdapter.Text = text; } button.onClick.AddListener(action); return true; } /// <summary> /// Show a timer during which the player can select an option. Calls a Block when the timer expires. /// </summary> /// <param name="duration">The duration during which the player can select an option.</param> /// <param name="targetBlock">Block to execute if the player does not select an option in time.</param> public virtual void ShowTimer(float duration, Block targetBlock) { if (cachedSlider != null) { cachedSlider.gameObject.SetActive(true); gameObject.SetActive(true); StopAllCoroutines(); StartCoroutine(WaitForTimeout(duration, targetBlock)); } else { Debug.LogWarning("Unable to show timer, no slider set"); } } /// <summary> /// Show a timer during which the player can select an option. Calls a Lua function when the timer expires. /// </summary> public virtual IEnumerator ShowTimer(float duration, LuaEnvironment luaEnv, Closure callBack) { if (CachedSlider == null || duration <= 0f) { yield break; } CachedSlider.gameObject.SetActive(true); StopAllCoroutines(); float elapsedTime = 0; Slider timeoutSlider = CachedSlider; while (elapsedTime < duration) { if (timeoutSlider != null) { float t = 1f - elapsedTime / duration; timeoutSlider.value = t; } elapsedTime += Time.deltaTime; yield return null; } Clear(); gameObject.SetActive(false); HideSayDialog(); if (callBack != null) { luaEnv.RunLuaFunction(callBack, true); } } /// <summary> /// Returns true if the Menu Dialog is currently displayed. /// </summary> public virtual bool IsActive() { return gameObject.activeInHierarchy; } /// <summary> /// Returns the number of currently displayed options. /// </summary> public virtual int DisplayedOptionsCount { get { int count = 0; for (int i = 0; i < cachedButtons.Length; i++) { var button = cachedButtons[i]; if (button.gameObject.activeSelf) { count++; } } return count; } } /// <summary> /// Shuffle the parent order of the cached buttons, allows for randomising button order, buttons are auto reordered when cleared /// </summary> public void Shuffle(System.Random r) { for (int i = 0; i < CachedButtons.Length; i++) { CachedButtons[i].transform.SetSiblingIndex(r.Next(CachedButtons.Length)); } } #endregion } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Globalization; using System.Security.Cryptography; using System.Text; namespace Mono.Cecil { public class AssemblyNameReference : IMetadataScope { string name; string culture; Version version; uint attributes; byte [] public_key; byte [] public_key_token; AssemblyHashAlgorithm hash_algorithm; byte [] hash; internal MetadataToken token; string full_name; public string Name { get { return name; } set { name = value; full_name = null; } } public string Culture { get { return culture; } set { culture = value; full_name = null; } } public Version Version { get { return version; } set { version = value; full_name = null; } } public AssemblyAttributes Attributes { get { return (AssemblyAttributes) attributes; } set { attributes = (uint) value; } } public bool HasPublicKey { get { return attributes.GetAttributes ((uint) AssemblyAttributes.PublicKey); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.PublicKey, value); } } public bool IsSideBySideCompatible { get { return attributes.GetAttributes ((uint) AssemblyAttributes.SideBySideCompatible); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.SideBySideCompatible, value); } } public bool IsRetargetable { get { return attributes.GetAttributes ((uint) AssemblyAttributes.Retargetable); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.Retargetable, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes ((uint) AssemblyAttributes.WindowsRuntime); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.WindowsRuntime, value); } } public byte [] PublicKey { get { return public_key ?? Empty<byte>.Array; } set { public_key = value; HasPublicKey = !public_key.IsNullOrEmpty (); public_key_token = Empty<byte>.Array; full_name = null; } } public byte [] PublicKeyToken { get { if (public_key_token.IsNullOrEmpty () && !public_key.IsNullOrEmpty ()) { var hash = HashPublicKey (); // we need the last 8 bytes in reverse order var local_public_key_token = new byte [8]; Array.Copy (hash, (hash.Length - 8), local_public_key_token, 0, 8); Array.Reverse (local_public_key_token, 0, 8); public_key_token = local_public_key_token; // publish only once finished (required for thread-safety) } return public_key_token ?? Empty<byte>.Array; } set { public_key_token = value; full_name = null; } } byte [] HashPublicKey () { HashAlgorithm algorithm; switch (hash_algorithm) { case AssemblyHashAlgorithm.Reserved: #if SILVERLIGHT throw new NotSupportedException (); #else algorithm = MD5.Create (); break; #endif default: // None default to SHA1 #if SILVERLIGHT algorithm = new SHA1Managed (); break; #else algorithm = SHA1.Create (); break; #endif } using (algorithm) return algorithm.ComputeHash (public_key); } public virtual MetadataScopeType MetadataScopeType { get { return MetadataScopeType.AssemblyNameReference; } } public string FullName { get { if (full_name != null) return full_name; const string sep = ", "; var builder = new StringBuilder (); builder.Append (name); if (version != null) { builder.Append (sep); builder.Append ("Version="); builder.Append (version.ToString ()); } builder.Append (sep); builder.Append ("Culture="); builder.Append (string.IsNullOrEmpty (culture) ? "neutral" : culture); builder.Append (sep); builder.Append ("PublicKeyToken="); var pk_token = PublicKeyToken; if (!pk_token.IsNullOrEmpty () && pk_token.Length > 0) { for (int i = 0 ; i < pk_token.Length ; i++) { builder.Append (pk_token [i].ToString ("x2")); } } else builder.Append ("null"); return full_name = builder.ToString (); } } public static AssemblyNameReference Parse (string fullName) { if (fullName == null) throw new ArgumentNullException ("fullName"); if (fullName.Length == 0) throw new ArgumentException ("Name can not be empty"); var name = new AssemblyNameReference (); var tokens = fullName.Split (','); for (int i = 0; i < tokens.Length; i++) { var token = tokens [i].Trim (); if (i == 0) { name.Name = token; continue; } var parts = token.Split ('='); if (parts.Length != 2) throw new ArgumentException ("Malformed name"); switch (parts [0].ToLowerInvariant ()) { case "version": name.Version = new Version (parts [1]); break; case "culture": name.Culture = parts [1]; break; case "publickeytoken": var pk_token = parts [1]; if (pk_token == "null") break; name.PublicKeyToken = new byte [pk_token.Length / 2]; for (int j = 0; j < name.PublicKeyToken.Length; j++) name.PublicKeyToken [j] = Byte.Parse (pk_token.Substring (j * 2, 2), NumberStyles.HexNumber); break; } } return name; } public AssemblyHashAlgorithm HashAlgorithm { get { return hash_algorithm; } set { hash_algorithm = value; } } public virtual byte [] Hash { get { return hash; } set { hash = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } internal AssemblyNameReference () { } public AssemblyNameReference (string name, Version version) { if (name == null) throw new ArgumentNullException ("name"); this.name = name; this.version = version; this.hash_algorithm = AssemblyHashAlgorithm.None; this.token = new MetadataToken (TokenType.AssemblyRef); } public override string ToString () { return this.FullName; } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // 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. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Encapsulates initialization and shutdown of gRPC library. /// </summary> public class GrpcEnvironment { const int MinDefaultThreadPoolSize = 4; const int DefaultBatchContextPoolSharedCapacity = 10000; const int DefaultBatchContextPoolThreadLocalCapacity = 64; const int DefaultRequestCallContextPoolSharedCapacity = 10000; const int DefaultRequestCallContextPoolThreadLocalCapacity = 64; static object staticLock = new object(); static GrpcEnvironment instance; static int refCount; static int? customThreadPoolSize; static int? customCompletionQueueCount; static bool inlineHandlers; static int batchContextPoolSharedCapacity = DefaultBatchContextPoolSharedCapacity; static int batchContextPoolThreadLocalCapacity = DefaultBatchContextPoolThreadLocalCapacity; static int requestCallContextPoolSharedCapacity = DefaultRequestCallContextPoolSharedCapacity; static int requestCallContextPoolThreadLocalCapacity = DefaultRequestCallContextPoolThreadLocalCapacity; static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>(); static readonly HashSet<Server> registeredServers = new HashSet<Server>(); static ILogger logger = new LogLevelFilterLogger(new ConsoleLogger(), LogLevel.Off, true); readonly IObjectPool<BatchContextSafeHandle> batchContextPool; readonly IObjectPool<RequestCallContextSafeHandle> requestCallContextPool; readonly GrpcThreadPool threadPool; readonly DebugStats debugStats = new DebugStats(); readonly AtomicCounter cqPickerCounter = new AtomicCounter(); bool isShutdown; /// <summary> /// Returns a reference-counted instance of initialized gRPC environment. /// Subsequent invocations return the same instance unless reference count has dropped to zero previously. /// </summary> internal static GrpcEnvironment AddRef() { ShutdownHooks.Register(); lock (staticLock) { refCount++; if (instance == null) { instance = new GrpcEnvironment(); } return instance; } } /// <summary> /// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero. /// </summary> internal static async Task ReleaseAsync() { GrpcEnvironment instanceToShutdown = null; lock (staticLock) { GrpcPreconditions.CheckState(refCount > 0); refCount--; if (refCount == 0) { instanceToShutdown = instance; instance = null; } } if (instanceToShutdown != null) { await instanceToShutdown.ShutdownAsync().ConfigureAwait(false); } } internal static int GetRefCount() { lock (staticLock) { return refCount; } } internal static void RegisterChannel(Channel channel) { lock (staticLock) { GrpcPreconditions.CheckNotNull(channel); registeredChannels.Add(channel); } } internal static void UnregisterChannel(Channel channel) { lock (staticLock) { GrpcPreconditions.CheckNotNull(channel); GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set."); } } internal static void RegisterServer(Server server) { lock (staticLock) { GrpcPreconditions.CheckNotNull(server); registeredServers.Add(server); } } internal static void UnregisterServer(Server server) { lock (staticLock) { GrpcPreconditions.CheckNotNull(server); GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set."); } } /// <summary> /// Requests shutdown of all channels created by the current process. /// </summary> public static Task ShutdownChannelsAsync() { HashSet<Channel> snapshot = null; lock (staticLock) { snapshot = new HashSet<Channel>(registeredChannels); } return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync())); } /// <summary> /// Requests immediate shutdown of all servers created by the current process. /// </summary> public static Task KillServersAsync() { HashSet<Server> snapshot = null; lock (staticLock) { snapshot = new HashSet<Server>(registeredServers); } return Task.WhenAll(snapshot.Select((server) => server.KillAsync())); } /// <summary> /// Gets application-wide logger used by gRPC. /// </summary> /// <value>The logger.</value> public static ILogger Logger { get { return logger; } } /// <summary> /// Sets the application-wide logger that should be used by gRPC. /// </summary> public static void SetLogger(ILogger customLogger) { GrpcPreconditions.CheckNotNull(customLogger, "customLogger"); logger = customLogger; } /// <summary> /// Sets the number of threads in the gRPC thread pool that polls for internal RPC events. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetThreadPoolSize(int threadCount) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number"); customThreadPoolSize = threadCount; } } /// <summary> /// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetCompletionQueueCount(int completionQueueCount) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number"); customCompletionQueueCount = completionQueueCount; } } /// <summary> /// By default, gRPC's internal event handlers get offloaded to .NET default thread pool thread (<c>inlineHandlers=false</c>). /// Setting <c>inlineHandlers</c> to <c>true</c> will allow scheduling the event handlers directly to /// <c>GrpcThreadPool</c> internal threads. That can lead to significant performance gains in some situations, /// but requires user to never block in async code (incorrectly written code can easily lead to deadlocks). /// Inlining handlers is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// Note: <c>inlineHandlers=true</c> was the default in gRPC C# v1.4.x and earlier. /// </summary> public static void SetHandlerInlining(bool inlineHandlers) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcEnvironment.inlineHandlers = inlineHandlers; } } /// <summary> /// Sets the parameters for a pool that caches batch context instances. Reusing batch context instances /// instead of creating a new one for every C core operation helps reducing the GC pressure. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// This is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetBatchContextPoolParams(int sharedCapacity, int threadLocalCapacity) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number"); GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number"); batchContextPoolSharedCapacity = sharedCapacity; batchContextPoolThreadLocalCapacity = threadLocalCapacity; } } /// <summary> /// Sets the parameters for a pool that caches request call context instances. Reusing request call context instances /// instead of creating a new one for every requested call in C core helps reducing the GC pressure. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// This is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetRequestCallContextPoolParams(int sharedCapacity, int threadLocalCapacity) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number"); GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number"); requestCallContextPoolSharedCapacity = sharedCapacity; requestCallContextPoolThreadLocalCapacity = threadLocalCapacity; } } /// <summary> /// Occurs when <c>GrpcEnvironment</c> is about the start the shutdown logic. /// If <c>GrpcEnvironment</c> is later initialized and shutdown, the event will be fired again (unless unregistered first). /// </summary> public static event EventHandler ShuttingDown; /// <summary> /// Creates gRPC environment. /// </summary> private GrpcEnvironment() { GrpcNativeInit(); batchContextPool = new DefaultObjectPool<BatchContextSafeHandle>(() => BatchContextSafeHandle.Create(), batchContextPoolSharedCapacity, batchContextPoolThreadLocalCapacity); requestCallContextPool = new DefaultObjectPool<RequestCallContextSafeHandle>(() => RequestCallContextSafeHandle.Create(), requestCallContextPoolSharedCapacity, requestCallContextPoolThreadLocalCapacity); threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault(), inlineHandlers); threadPool.Start(); } /// <summary> /// Gets the completion queues used by this gRPC environment. /// </summary> internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues { get { return this.threadPool.CompletionQueues; } } internal IObjectPool<BatchContextSafeHandle> BatchContextPool => batchContextPool; internal IObjectPool<RequestCallContextSafeHandle> RequestCallContextPool => requestCallContextPool; internal bool IsAlive { get { return this.threadPool.IsAlive; } } /// <summary> /// Picks a completion queue in a round-robin fashion. /// Shouldn't be invoked on a per-call basis (used at per-channel basis). /// </summary> internal CompletionQueueSafeHandle PickCompletionQueue() { var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count); return this.threadPool.CompletionQueues.ElementAt(cqIndex); } /// <summary> /// Gets the completion queue used by this gRPC environment. /// </summary> internal DebugStats DebugStats { get { return this.debugStats; } } /// <summary> /// Gets version of gRPC C core. /// </summary> internal static string GetCoreVersionString() { var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned return Marshal.PtrToStringAnsi(ptr); } internal static void GrpcNativeInit() { NativeMethods.Get().grpcsharp_init(); } internal static void GrpcNativeShutdown() { NativeMethods.Get().grpcsharp_shutdown(); } /// <summary> /// Shuts down this environment. /// </summary> private async Task ShutdownAsync() { if (isShutdown) { throw new InvalidOperationException("ShutdownAsync has already been called"); } await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false); await threadPool.StopAsync().ConfigureAwait(false); requestCallContextPool.Dispose(); batchContextPool.Dispose(); GrpcNativeShutdown(); isShutdown = true; debugStats.CheckOK(); } private int GetThreadPoolSizeOrDefault() { if (customThreadPoolSize.HasValue) { return customThreadPoolSize.Value; } // In systems with many cores, use half of the cores for GrpcThreadPool // and the other half for .NET thread pool. This heuristic definitely needs // more work, but seems to work reasonably well for a start. return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2); } private int GetCompletionQueueCountOrDefault() { if (customCompletionQueueCount.HasValue) { return customCompletionQueueCount.Value; } // by default, create a completion queue for each thread return GetThreadPoolSizeOrDefault(); } private static class ShutdownHooks { static object staticLock = new object(); static bool hooksRegistered; public static void Register() { lock (staticLock) { if (!hooksRegistered) { #if NETSTANDARD1_5 System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (assemblyLoadContext) => { HandleShutdown(); }; #else AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { HandleShutdown(); }; AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { HandleShutdown(); }; #endif } hooksRegistered = true; } } /// <summary> /// Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks. /// </summary> private static void HandleShutdown() { Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync()); } } } }
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 Yad2.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. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; namespace Microsoft.Management.UI.Internal { /// <summary> /// The FilterRulePanel allows users to construct and display a complex query built using <see cref="FilterRule"/>s. /// </summary> /// <remarks> /// <para> /// The FilterRulePanel manages two primary entities: <see cref="FilterRulePanelItem"/>s and DataTemplates. /// /// </para> /// <para> /// <see cref="FilterRulePanelItem" />s are the data classes that store the state for each item in the panel. /// They are added and removed to/from the panel using the AddRulesCommand and the RemoveRuleCommand commands. /// </para> /// <para> /// For a FilterRule to display in the panel it must have a DataTemplate registered. To add and remove /// DataTemplates, use the AddFilterRulePanelItemContentTemplate and RemoveFilterRulePanelItemContentTemplate methods. /// </para> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public partial class FilterRulePanel : Control, IFilterExpressionProvider { #region Properties #region Filter Rule Panel Items /// <summary> /// Gets the collection of FilterRulePanelItems that are currently /// displayed in the panel. /// </summary> public ReadOnlyCollection<FilterRulePanelItem> FilterRulePanelItems { get { return this.Controller.FilterRulePanelItems; } } #endregion Filter Rule Panel Items #region Filter Expression /// <summary> /// Gets a FilterExpression representing the current /// relational organization of FilterRules for this provider. /// </summary> public FilterExpressionNode FilterExpression { get { return this.Controller.FilterExpression; } } #endregion Filter Expression #region Controller private FilterRulePanelController controller = new FilterRulePanelController(); /// <summary> /// Gets the FilterRulePanelController associated with this FilterRulePanel. /// </summary> public FilterRulePanelController Controller { get { return this.controller; } } #endregion Controller #region Filter Rule Template Selector private FilterRuleTemplateSelector filterRuleTemplateSelector; /// <summary> /// Gets a FilterRuleTemplateSelector that stores /// the templates used for items in the panel. /// </summary> public DataTemplateSelector FilterRuleTemplateSelector { get { return this.filterRuleTemplateSelector; } } #endregion Filter Rule Template Selector /// <summary> /// Gets a value indicating whether this provider currently has a non-empty filter expression. /// </summary> public bool HasFilterExpression { get { return this.Controller.HasFilterExpression; } } #endregion Properties #region Events /// <summary> /// Raised when a FilterRulePanelItem has been added or removed. /// </summary> public event EventHandler FilterExpressionChanged; #endregion #region Ctor /// <summary> /// Initializes a new instance of the FilterRulePanel class. /// </summary> public FilterRulePanel() { this.InitializeTemplates(); this.Controller.FilterExpressionChanged += this.Controller_FilterExpressionChanged; } #endregion Ctor #region Public Methods #region Content Templates /// <summary> /// Associates a DataTemplate with a Type so that objects of that Type /// that are displayed in FilterRulePanel use the specified DataTemplate. /// </summary> /// <param name="type"> /// The type to associate the DataTemplate with. /// </param> /// <param name="dataTemplate"> /// The DataTemplate to associate the type with. /// </param> public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTemplate) { if (type == null) { throw new ArgumentNullException("type"); } if (dataTemplate == null) { throw new ArgumentNullException("dataTemplate"); } this.filterRuleTemplateSelector.TemplateDictionary.Add(new KeyValuePair<Type, DataTemplate>(type, dataTemplate)); } /// <summary> /// Removes the Type and associated DataTemplate from usage when displaying objects /// of that type in the FilterRulePanel. /// </summary> /// <param name="type"> /// The type to remove. /// </param> public void RemoveFilterRulePanelItemContentTemplate(Type type) { if (type == null) { throw new ArgumentNullException("type"); } this.filterRuleTemplateSelector.TemplateDictionary.Remove(type); } /// <summary> /// Gets a DataTemplate associated with a type. /// </summary> /// <param name="type">A Type whose DataTemplate will be returned.</param> /// <param name="dataTemplate">A DataTemplate registered for type.</param> /// <returns>Returns true if there is a DataTemplate registered for type, false otherwise.</returns> public bool TryGetContentTemplate(Type type, out DataTemplate dataTemplate) { dataTemplate = null; return this.filterRuleTemplateSelector.TemplateDictionary.TryGetValue(type, out dataTemplate); } /// <summary> /// Removes all the registered content templates. /// </summary> public void ClearContentTemplates() { this.filterRuleTemplateSelector.TemplateDictionary.Clear(); } #endregion Content Templates #region Notify Filter Expression Changed /// <summary> /// Notifies any listeners that the filter expression has changed. /// </summary> protected virtual void NotifyFilterExpressionChanged() { #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. EventHandler eh = this.FilterExpressionChanged; if (eh != null) { eh(this, new EventArgs()); } #pragma warning restore IDE1005 } private void Controller_FilterExpressionChanged(object sender, EventArgs e) { this.NotifyFilterExpressionChanged(); } #endregion Notify Filter Expression Changed #endregion Public Methods #region Private Methods #region Add Rules Command Callback partial void OnAddRulesExecutedImplementation(ExecutedRoutedEventArgs e) { Debug.Assert(e != null, "not null"); if (e.Parameter == null) { throw new ArgumentException("e.Parameter is null.", "e"); } List<FilterRulePanelItem> itemsToAdd = new List<FilterRulePanelItem>(); IList selectedItems = (IList)e.Parameter; foreach (object item in selectedItems) { FilterRulePanelItem newItem = item as FilterRulePanelItem; if (newItem == null) { throw new ArgumentException( "e.Parameter contains a value which is not a valid FilterRulePanelItem object.", "e"); } itemsToAdd.Add(newItem); } foreach (FilterRulePanelItem item in itemsToAdd) { this.AddFilterRuleInternal(item); } } #endregion Add Rules Command Callback #region Remove Rule Command Callback partial void OnRemoveRuleExecutedImplementation(ExecutedRoutedEventArgs e) { Debug.Assert(e != null, "not null"); if (e.Parameter == null) { throw new ArgumentException("e.Parameter is null.", "e"); } FilterRulePanelItem item = e.Parameter as FilterRulePanelItem; if (item == null) { throw new ArgumentException("e.Parameter is not a valid FilterRulePanelItem object.", "e"); } this.RemoveFilterRuleInternal(item); } #endregion Remove Rule Command Callback #region InitializeTemplates private void InitializeTemplates() { this.filterRuleTemplateSelector = new FilterRuleTemplateSelector(); this.InitializeTemplatesForInputTypes(); List<KeyValuePair<Type, string>> defaultTemplates = new List<KeyValuePair<Type, string>>() { new KeyValuePair<Type, string>(typeof(SelectorFilterRule), "CompositeRuleTemplate"), new KeyValuePair<Type, string>(typeof(SingleValueComparableValueFilterRule<>), "ComparableValueRuleTemplate"), new KeyValuePair<Type, string>(typeof(IsEmptyFilterRule), "NoInputTemplate"), new KeyValuePair<Type, string>(typeof(IsNotEmptyFilterRule), "NoInputTemplate"), new KeyValuePair<Type, string>(typeof(FilterRulePanelItemType), "FilterRulePanelGroupItemTypeTemplate"), new KeyValuePair<Type, string>(typeof(ValidatingValue<>), "ValidatingValueTemplate"), new KeyValuePair<Type, string>(typeof(ValidatingSelectorValue<>), "ValidatingSelectorValueTemplate"), new KeyValuePair<Type, string>(typeof(IsBetweenFilterRule<>), "IsBetweenRuleTemplate"), new KeyValuePair<Type, string>(typeof(object), "CatchAllTemplate") }; defaultTemplates.ForEach(templateInfo => this.AddFilterRulePanelItemContentTemplate(templateInfo.Key, templateInfo.Value)); } private void InitializeTemplatesForInputTypes() { List<Type> inputTypes = new List<Type>() { typeof(sbyte), typeof(byte), typeof(short), typeof(int), typeof(long), typeof(ushort), typeof(uint), typeof(ulong), typeof(char), typeof(Single), typeof(double), typeof(decimal), typeof(bool), typeof(Enum), typeof(DateTime), typeof(string) }; inputTypes.ForEach(type => this.AddFilterRulePanelItemContentTemplate(type, "InputValueTemplate")); } private void AddFilterRulePanelItemContentTemplate(Type type, string resourceName) { Debug.Assert(type != null, "not null"); Debug.Assert(!string.IsNullOrEmpty(resourceName), "not null"); var templateInfo = new ComponentResourceKey(typeof(FilterRulePanel), resourceName); DataTemplate template = (DataTemplate)this.TryFindResource(templateInfo); Debug.Assert(template != null, "not null"); this.AddFilterRulePanelItemContentTemplate(type, template); } #endregion InitializeTemplates #region Add/Remove FilterRules to Controller private void AddFilterRuleInternal(FilterRulePanelItem item) { Debug.Assert(item != null, "not null"); FilterRulePanelItem newItem = new FilterRulePanelItem(item.Rule.DeepCopy(), item.GroupId); this.Controller.AddFilterRulePanelItem(newItem); } private void RemoveFilterRuleInternal(FilterRulePanelItem item) { Debug.Assert(item != null, "not null"); this.Controller.RemoveFilterRulePanelItem(item); } #endregion Add/Remove FilterRules to Controller #endregion Private Methods } }
#region License, Terms and Conditions // // Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono // Written by Atif Aziz ([email protected]) // Copyright (c) 2005 Atif Aziz. All rights reserved. // // This library 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 2.1 of the License, or (at your option) // any later version. // // 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 // #endregion namespace Jayrock.Json { #region Imports using System; using System.IO; #endregion /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only means of /// emitting JSON data formatted as JSON text (RFC 4627). /// </summary> public class JsonTextWriter : JsonWriterBase { private readonly TextWriter _writer; // // Pretty printing as per: // http://developer.mozilla.org/es4/proposals/json_encoding_and_decoding.html // // <quote> // ...linefeeds are inserted after each { and , and before } , and multiples // of 4 spaces are inserted to indicate the level of nesting, and one space // will be inserted after :. Otherwise, no whitespace is inserted between // the tokens. // </quote> // private bool _prettyPrint; private bool _newLine; private int _indent; private char[] _indentBuffer; public JsonTextWriter() : this(null) {} public JsonTextWriter(TextWriter writer) { _writer = writer != null ? writer : new StringWriter(); } public bool PrettyPrint { get { return _prettyPrint; } set { _prettyPrint = value; } } protected TextWriter InnerWriter { get { return _writer; } } public override void Flush() { _writer.Flush(); } public override string ToString() { StringWriter stringWriter = _writer as StringWriter; return stringWriter != null ? stringWriter.ToString() : base.ToString(); } protected override void WriteStartObjectImpl() { OnWritingValue(); WriteDelimiter('{'); PrettySpace(); } protected override void WriteEndObjectImpl() { if (Index > 0) { PrettyLine(); _indent--; } WriteDelimiter('}'); } protected override void WriteMemberImpl(string name) { if (Index > 0) { WriteDelimiter(','); PrettyLine(); } else { PrettyLine(); _indent++; } WriteStringImpl(name); PrettySpace(); WriteDelimiter(':'); PrettySpace(); } protected override void WriteStringImpl(string value) { WriteScalar(JsonString.Enquote(value)); } protected override void WriteNumberImpl(string value) { WriteScalar(value); } protected override void WriteBooleanImpl(bool value) { WriteScalar(value ? JsonBoolean.TrueText : JsonBoolean.FalseText); } protected override void WriteNullImpl() { WriteScalar(JsonNull.Text); } protected override void WriteStartArrayImpl() { OnWritingValue(); WriteDelimiter('['); PrettySpace(); } protected override void WriteEndArrayImpl() { if (IsNonEmptyArray()) PrettySpace(); WriteDelimiter(']'); } private void WriteScalar(string text) { OnWritingValue(); PrettyIndent(); _writer.Write(text); } private bool IsNonEmptyArray() { return Bracket == JsonWriterBracket.Array && Index > 0; } // // Methods below are mostly related to pretty-printing of JSON text. // private void OnWritingValue() { if (IsNonEmptyArray()) { WriteDelimiter(','); PrettySpace(); } } private void WriteDelimiter(char ch) { PrettyIndent(); _writer.Write(ch); } private void PrettySpace() { if (!_prettyPrint) return; WriteDelimiter(' '); } private void PrettyLine() { if (!_prettyPrint) return; _writer.WriteLine(); _newLine = true; } private void PrettyIndent() { if (!_prettyPrint) return; if (_newLine) { if (_indent > 0) { int spaces = _indent * 4; if (_indentBuffer == null || _indentBuffer.Length < spaces) _indentBuffer = new string(' ', spaces * 4).ToCharArray(); _writer.Write(_indentBuffer, 0, spaces); } _newLine = false; } } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // 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.Globalization; using System.Diagnostics; using System.IO; using System.Threading; using NUnit.Framework.Constraints; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal.Execution; #if !SILVERLIGHT && !NETCF && !PORTABLE using System.Runtime.Remoting.Messaging; using System.Security; using System.Security.Principal; using NUnit.Compatibility; #endif namespace NUnit.Framework.Internal { /// <summary> /// Helper class used to save and restore certain static or /// singleton settings in the environment that affect tests /// or which might be changed by the user tests. /// /// An internal class is used to hold settings and a stack /// of these objects is pushed and popped as Save and Restore /// are called. /// </summary> public class TestExecutionContext #if !SILVERLIGHT && !NETCF && !PORTABLE : LongLivedMarshalByRefObject, ILogicalThreadAffinative #endif { // NOTE: Be very careful when modifying this class. It uses // conditional compilation extensively and you must give // thought to whether any new features will be supported // on each platform. In particular, instance fields, // properties, initialization and restoration must all // use the same conditions for each feature. #region Instance Fields /// <summary> /// Link to a prior saved context /// </summary> private TestExecutionContext _priorContext; /// <summary> /// Indicates that a stop has been requested /// </summary> private TestExecutionStatus _executionStatus; /// <summary> /// The event listener currently receiving notifications /// </summary> private ITestListener _listener = TestListener.NULL; /// <summary> /// The number of assertions for the current test /// </summary> private int _assertCount; private Randomizer _randomGenerator; /// <summary> /// The current culture /// </summary> private CultureInfo _currentCulture; /// <summary> /// The current UI culture /// </summary> private CultureInfo _currentUICulture; /// <summary> /// The current test result /// </summary> private TestResult _currentResult; #if !NETCF && !SILVERLIGHT && !PORTABLE /// <summary> /// The current Principal. /// </summary> private IPrincipal _currentPrincipal; #endif #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> public TestExecutionContext() { _priorContext = null; TestCaseTimeout = 0; UpstreamActions = new List<ITestAction>(); _currentCulture = CultureInfo.CurrentCulture; _currentUICulture = CultureInfo.CurrentUICulture; #if !NETCF && !SILVERLIGHT && !PORTABLE _currentPrincipal = Thread.CurrentPrincipal; #endif CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val); IsSingleThreaded = false; } /// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> /// <param name="other">An existing instance of TestExecutionContext.</param> public TestExecutionContext(TestExecutionContext other) { _priorContext = other; CurrentTest = other.CurrentTest; CurrentResult = other.CurrentResult; TestObject = other.TestObject; WorkDirectory = other.WorkDirectory; _listener = other._listener; StopOnError = other.StopOnError; TestCaseTimeout = other.TestCaseTimeout; UpstreamActions = new List<ITestAction>(other.UpstreamActions); _currentCulture = other.CurrentCulture; _currentUICulture = other.CurrentUICulture; #if !NETCF && !SILVERLIGHT && !PORTABLE _currentPrincipal = other.CurrentPrincipal; #endif CurrentValueFormatter = other.CurrentValueFormatter; Dispatcher = other.Dispatcher; ParallelScope = other.ParallelScope; IsSingleThreaded = other.IsSingleThreaded; } #endregion #region Static Singleton Instance // NOTE: We use different implementations for various platforms // If a user creates a thread then the current context // will be null. This also happens when the compiler // automatically creates threads for async methods. // We create a new context, which is automatically // populated with values taken from the current thread. #if SILVERLIGHT || PORTABLE // In the Silverlight and portable builds, we use a ThreadStatic // field to hold the current TestExecutionContext. [ThreadStatic] private static TestExecutionContext _currentContext; /// <summary> /// Gets and sets the current context. /// </summary> public static TestExecutionContext CurrentContext { get { if (_currentContext == null) _currentContext = new TestExecutionContext(); return _currentContext; } private set { _currentContext = value; } } #elif NETCF // In the compact framework build, we use a LocalStoreDataSlot private static LocalDataStoreSlot contextSlot = Thread.AllocateDataSlot(); /// <summary> /// Gets and sets the current context. /// </summary> public static TestExecutionContext CurrentContext { get { var current = GetTestExecutionContext(); if (current == null) { current = new TestExecutionContext(); Thread.SetData(contextSlot, current); } return current; } private set { Thread.SetData(contextSlot, value); } } /// <summary> /// Get the current context or return null if none is found. /// </summary> public static TestExecutionContext GetTestExecutionContext() { return (TestExecutionContext)Thread.GetData(contextSlot); } #else // In all other builds, we use the CallContext private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext"; /// <summary> /// Gets and sets the current context. /// </summary> public static TestExecutionContext CurrentContext { // This getter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class. // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. [SecuritySafeCritical] get { var context = GetTestExecutionContext(); if (context == null) // This can happen on Mono { context = new TestExecutionContext(); CallContext.SetData(CONTEXT_KEY, context); } return context; } // This setter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class. // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. [SecuritySafeCritical] private set { if (value == null) CallContext.FreeNamedDataSlot(CONTEXT_KEY); else CallContext.SetData(CONTEXT_KEY, value); } } /// <summary> /// Get the current context or return null if none is found. /// </summary> /// <remarks></remarks> // This setter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class. // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. [SecuritySafeCritical] public static TestExecutionContext GetTestExecutionContext() { return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext; } #endif /// <summary> /// Clear the current context. This is provided to /// prevent "leakage" of the CallContext containing /// the current context back to any runners. /// </summary> public static void ClearCurrentContext() { CurrentContext = null; } #endregion #region Properties /// <summary> /// Gets or sets the current test /// </summary> public Test CurrentTest { get; set; } /// <summary> /// The time the current test started execution /// </summary> public DateTime StartTime { get; set; } /// <summary> /// The time the current test started in Ticks /// </summary> public long StartTicks { get; set; } /// <summary> /// Gets or sets the current test result /// </summary> public TestResult CurrentResult { get { return _currentResult; } set { _currentResult = value; if (value != null) OutWriter = value.OutWriter; } } /// <summary> /// Gets a TextWriter that will send output to the current test result. /// </summary> public TextWriter OutWriter { get; private set; } /// <summary> /// The current test object - that is the user fixture /// object on which tests are being executed. /// </summary> public object TestObject { get; set; } /// <summary> /// Get or set the working directory /// </summary> public string WorkDirectory { get; set; } /// <summary> /// Get or set indicator that run should stop on the first error /// </summary> public bool StopOnError { get; set; } /// <summary> /// Gets an enum indicating whether a stop has been requested. /// </summary> public TestExecutionStatus ExecutionStatus { get { // ExecutionStatus may have been set to StopRequested or AbortRequested // in a prior context. If so, reflect the same setting in this context. if (_executionStatus == TestExecutionStatus.Running && _priorContext != null) _executionStatus = _priorContext.ExecutionStatus; return _executionStatus; } set { _executionStatus = value; // Push the same setting up to all prior contexts if (_priorContext != null) _priorContext.ExecutionStatus = value; } } /// <summary> /// The current test event listener /// </summary> internal ITestListener Listener { get { return _listener; } set { _listener = value; } } /// <summary> /// The current WorkItemDispatcher. Made public for /// use by nunitlite.tests /// </summary> public IWorkItemDispatcher Dispatcher { get; set; } /// <summary> /// The ParallelScope to be used by tests running in this context. /// For builds with out the parallel feature, it has no effect. /// </summary> public ParallelScope ParallelScope { get; set; } /// <summary> /// The unique name of the worker that spawned the context. /// For builds with out the parallel feature, it is null. /// </summary> public string WorkerId {get; internal set;} /// <summary> /// Gets the RandomGenerator specific to this Test /// </summary> public Randomizer RandomGenerator { get { if (_randomGenerator == null) _randomGenerator = new Randomizer(CurrentTest.Seed); return _randomGenerator; } } /// <summary> /// Gets the assert count. /// </summary> /// <value>The assert count.</value> internal int AssertCount { get { return _assertCount; } } /// <summary> /// Gets or sets the test case timeout value /// </summary> public int TestCaseTimeout { get; set; } /// <summary> /// Gets a list of ITestActions set by upstream tests /// </summary> public List<ITestAction> UpstreamActions { get; private set; } // TODO: Put in checks on all of these settings // with side effects so we only change them // if the value is different /// <summary> /// Saves or restores the CurrentCulture /// </summary> public CultureInfo CurrentCulture { get { return _currentCulture; } set { _currentCulture = value; #if !NETCF && !PORTABLE Thread.CurrentThread.CurrentCulture = _currentCulture; #endif } } /// <summary> /// Saves or restores the CurrentUICulture /// </summary> public CultureInfo CurrentUICulture { get { return _currentUICulture; } set { _currentUICulture = value; #if !NETCF && !PORTABLE Thread.CurrentThread.CurrentUICulture = _currentUICulture; #endif } } #if !NETCF && !SILVERLIGHT && !PORTABLE /// <summary> /// Gets or sets the current <see cref="IPrincipal"/> for the Thread. /// </summary> public IPrincipal CurrentPrincipal { get { return _currentPrincipal; } set { _currentPrincipal = value; Thread.CurrentPrincipal = _currentPrincipal; } } #endif /// <summary> /// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter /// </summary> public ValueFormatter CurrentValueFormatter { get; private set; } /// <summary> /// If true, all tests must run on the same thread. No new thread may be spawned. /// </summary> public bool IsSingleThreaded { get; set; } #endregion #region Instance Methods /// <summary> /// Record any changes in the environment made by /// the test code in the execution context so it /// will be passed on to lower level tests. /// </summary> public void UpdateContextFromEnvironment() { _currentCulture = CultureInfo.CurrentCulture; _currentUICulture = CultureInfo.CurrentUICulture; #if !NETCF && !SILVERLIGHT && !PORTABLE _currentPrincipal = Thread.CurrentPrincipal; #endif } /// <summary> /// Set up the execution environment to match a context. /// Note that we may be running on the same thread where the /// context was initially created or on a different thread. /// </summary> public void EstablishExecutionEnvironment() { #if !NETCF && !PORTABLE Thread.CurrentThread.CurrentCulture = _currentCulture; Thread.CurrentThread.CurrentUICulture = _currentUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE Thread.CurrentPrincipal = _currentPrincipal; #endif CurrentContext = this; } /// <summary> /// Increments the assert count by one. /// </summary> public void IncrementAssertCount() { Interlocked.Increment(ref _assertCount); } /// <summary> /// Increments the assert count by a specified amount. /// </summary> public void IncrementAssertCount(int count) { // TODO: Temporary implementation while (count-- > 0) Interlocked.Increment(ref _assertCount); } /// <summary> /// Adds a new ValueFormatterFactory to the chain of formatters /// </summary> /// <param name="formatterFactory">The new factory</param> public void AddFormatter(ValueFormatterFactory formatterFactory) { CurrentValueFormatter = formatterFactory(CurrentValueFormatter); } #endregion #region InitializeLifetimeService #if !SILVERLIGHT && !NETCF && !PORTABLE /// <summary> /// Obtain lifetime service object /// </summary> /// <returns></returns> [SecurityCritical] // Override of security critical method must be security critical itself public override object InitializeLifetimeService() { return null; } #endif #endregion } }
#region File Description //----------------------------------------------------------------------------- // Billboard.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace Billboard { /// <summary> /// Sample showing how to efficiently render billboard sprites. /// </summary> public class BillboardGame : Microsoft.Xna.Framework.Game { #region Fields GraphicsDeviceManager graphics; KeyboardState currentKeyboardState = new KeyboardState(); GamePadState currentGamePadState = new GamePadState(); Vector3 cameraPosition = new Vector3(0, 50, 50); Vector3 cameraFront = new Vector3(0, 0, -1); Model landscape; #endregion #region Initialization public BillboardGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { landscape = Content.Load<Model>("landscape"); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); UpdateCamera(gameTime); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { GraphicsDevice device = graphics.GraphicsDevice; device.Clear(Color.CornflowerBlue); // Compute camera matrices. Matrix view = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraFront, Vector3.Up); Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1, 10000); Vector3 lightDirection = Vector3.Normalize(new Vector3(3, -1, 1)); Vector3 lightColor = new Vector3(0.3f, 0.4f, 0.2f); // Time is scaled down to make things wave in the wind more slowly. float time = (float)gameTime.TotalGameTime.TotalSeconds * 0.333f; // First we draw the ground geometry using BasicEffect. foreach (ModelMesh mesh in landscape.Meshes) { if (mesh.Name != "Billboards") { foreach (BasicEffect effect in mesh.Effects) { effect.View = view; effect.Projection = projection; effect.LightingEnabled = true; effect.DirectionalLight0.Enabled = true; effect.DirectionalLight0.Direction = lightDirection; effect.DirectionalLight0.DiffuseColor = lightColor; effect.AmbientLightColor = new Vector3(0.1f, 0.2f, 0.1f); } device.BlendState = BlendState.Opaque; device.DepthStencilState = DepthStencilState.Default; device.RasterizerState = RasterizerState.CullCounterClockwise; mesh.Draw(); } } // Then we use a two-pass technique to render alpha blended billboards with // almost-correct depth sorting. The only way to make blending truly proper for // alpha objects is to draw everything in sorted order, but manually sorting all // our billboards would be very expensive. Instead, we draw in two passes. // // The first pass has alpha blending turned off, alpha testing set to only accept // ~95% or more opaque pixels, and the depth buffer turned on. Because this is only // rendering the solid parts of each billboard, the depth buffer works as // normal to give correct sorting, but obviously only part of each billboard will // be rendered. // // Then in the second pass we enable alpha blending, set alpha test to only accept // pixels with fractional alpha values, and set the depth buffer to test against // the existing data but not to write new depth values. This means the translucent // areas of each billboard will be sorted correctly against the depth buffer // information that was previously written while drawing the opaque parts, although // there can still be sorting errors between the translucent areas of different // billboards. // // In practice, sorting errors between translucent pixels tend not to be too // noticable as long as the opaque pixels are sorted correctly, so this technique // often looks ok, and is much faster than trying to sort everything 100% // correctly. It is particularly effective for organic textures like grass and // trees. foreach (ModelMesh mesh in landscape.Meshes) { if (mesh.Name == "Billboards") { // First pass renders opaque pixels. foreach (Effect effect in mesh.Effects) { effect.Parameters["View"].SetValue(view); effect.Parameters["Projection"].SetValue(projection); effect.Parameters["LightDirection"].SetValue(lightDirection); effect.Parameters["WindTime"].SetValue(time); effect.Parameters["AlphaTestDirection"].SetValue(1f); } device.BlendState = BlendState.Opaque; device.DepthStencilState = DepthStencilState.Default; device.RasterizerState = RasterizerState.CullNone; device.SamplerStates[0] = SamplerState.LinearClamp; mesh.Draw(); // Second pass renders the alpha blended fringe pixels. foreach (Effect effect in mesh.Effects) { effect.Parameters["AlphaTestDirection"].SetValue(-1f); } device.BlendState = BlendState.NonPremultiplied; device.DepthStencilState = DepthStencilState.DepthRead; mesh.Draw(); } } base.Draw(gameTime); } #endregion #region Handle Input /// <summary> /// Handles input for quitting the game. /// </summary> private void HandleInput() { currentKeyboardState = Keyboard.GetState(); currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.Buttons.Back == ButtonState.Pressed) { Exit(); } } /// <summary> /// Handles camera input. /// </summary> private void UpdateCamera(GameTime gameTime) { float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds; // Check for input to rotate the camera. float pitch = -currentGamePadState.ThumbSticks.Right.Y * time * 0.001f; float turn = -currentGamePadState.ThumbSticks.Right.X * time * 0.001f; if (currentKeyboardState.IsKeyDown(Keys.Up)) pitch += time * 0.001f; if (currentKeyboardState.IsKeyDown(Keys.Down)) pitch -= time * 0.001f; if (currentKeyboardState.IsKeyDown(Keys.Left)) turn += time * 0.001f; if (currentKeyboardState.IsKeyDown(Keys.Right)) turn -= time * 0.001f; Vector3 cameraRight = Vector3.Cross(Vector3.Up, cameraFront); Vector3 flatFront = Vector3.Cross(cameraRight, Vector3.Up); Matrix pitchMatrix = Matrix.CreateFromAxisAngle(cameraRight, pitch); Matrix turnMatrix = Matrix.CreateFromAxisAngle(Vector3.Up, turn); Vector3 tiltedFront = Vector3.TransformNormal(cameraFront, pitchMatrix * turnMatrix); // Check angle so we cant flip over if (Vector3.Dot(tiltedFront, flatFront) > 0.001f) { cameraFront = Vector3.Normalize(tiltedFront); } // Check for input to move the camera around. if (currentKeyboardState.IsKeyDown(Keys.W)) cameraPosition += cameraFront * time * 0.1f; if (currentKeyboardState.IsKeyDown(Keys.S)) cameraPosition -= cameraFront * time * 0.1f; if (currentKeyboardState.IsKeyDown(Keys.A)) cameraPosition += cameraRight * time * 0.1f; if (currentKeyboardState.IsKeyDown(Keys.D)) cameraPosition -= cameraRight * time * 0.1f; cameraPosition += cameraFront * currentGamePadState.ThumbSticks.Left.Y * time * 0.1f; cameraPosition -= cameraRight * currentGamePadState.ThumbSticks.Left.X * time * 0.1f; if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.R)) { cameraPosition = new Vector3(0, 50, 50); cameraFront = new Vector3(0, 0, -1); } } #endregion } #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (BillboardGame game = new BillboardGame()) { game.Run(); } } } #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.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Xunit; namespace System.Linq.Tests { public class WhereTests : EnumerableTests { #region Null arguments [Fact] public void Where_SourceIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = null; Func<int, bool> simplePredicate = (value) => true; Func<int, int, bool> complexPredicate = (value, index) => true; AssertExtensions.Throws<ArgumentNullException>("source", () => source.Where(simplePredicate)); AssertExtensions.Throws<ArgumentNullException>("source", () => source.Where(complexPredicate)); } [Fact] public void Where_PredicateIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, bool> simplePredicate = null; Func<int, int, bool> complexPredicate = null; AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.Where(simplePredicate)); AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.Where(complexPredicate)); } #endregion #region Deferred execution [Fact] public void Where_Array_ExecutionIsDeferred() { bool funcCalled = false; Func<bool>[] source = { () => { funcCalled = true; return true; } }; IEnumerable<Func<bool>> query = source.Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void Where_List_ExecutionIsDeferred() { bool funcCalled = false; List<Func<bool>> source = new List<Func<bool>>() { () => { funcCalled = true; return true; } }; IEnumerable<Func<bool>> query = source.Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void Where_IReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<bool>> source = new ReadOnlyCollection<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } }); IEnumerable<Func<bool>> query = source.Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void Where_ICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<bool>> source = new LinkedList<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } }); IEnumerable<Func<bool>> query = source.Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void Where_IEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<bool>> source = Enumerable.Repeat((Func<bool>)(() => { funcCalled = true; return true; }), 1); IEnumerable<Func<bool>> query = source.Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void WhereWhere_Array_ExecutionIsDeferred() { bool funcCalled = false; Func<bool>[] source = new Func<bool>[] { () => { funcCalled = true; return true; } }; IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void WhereWhere_List_ExecutionIsDeferred() { bool funcCalled = false; List<Func<bool>> source = new List<Func<bool>>() { () => { funcCalled = true; return true; } }; IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void WhereWhere_IReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<bool>> source = new ReadOnlyCollection<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } }); IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void WhereWhere_ICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<bool>> source = new LinkedList<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } }); IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } [Fact] public void WhereWhere_IEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<bool>> source = Enumerable.Repeat((Func<bool>)(() => { funcCalled = true; return true; }), 1); IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value()); Assert.False(funcCalled); query = source.Where((value, index) => value()); Assert.False(funcCalled); } #endregion #region Expected return value [Fact] public void Where_Array_ReturnsExpectedValues_True() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> truePredicate = (value) => true; IEnumerable<int> result = source.Where(truePredicate); Assert.Equal(source.Length, result.Count()); for (int i = 0; i < source.Length; i++) { Assert.Equal(source.ElementAt(i), result.ElementAt(i)); } } [Fact] public void Where_Array_ReturnsExpectedValues_False() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> falsePredicate = (value) => false; IEnumerable<int> result = source.Where(falsePredicate); Assert.Equal(0, result.Count()); } [Fact] public void Where_Array_ReturnsExpectedValues_Complex() { int[] source = new[] { 2, 1, 3, 5, 4 }; Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); }; IEnumerable<int> result = source.Where(complexPredicate); Assert.Equal(2, result.Count()); Assert.Equal(1, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void Where_List_ReturnsExpectedValues_True() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> truePredicate = (value) => true; IEnumerable<int> result = source.Where(truePredicate); Assert.Equal(source.Count, result.Count()); for (int i = 0; i < source.Count; i++) { Assert.Equal(source.ElementAt(i), result.ElementAt(i)); } } [Fact] public void Where_List_ReturnsExpectedValues_False() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> falsePredicate = (value) => false; IEnumerable<int> result = source.Where(falsePredicate); Assert.Equal(0, result.Count()); } [Fact] public void Where_List_ReturnsExpectedValues_Complex() { List<int> source = new List<int> { 2, 1, 3, 5, 4 }; Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); }; IEnumerable<int> result = source.Where(complexPredicate); Assert.Equal(2, result.Count()); Assert.Equal(1, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void Where_IReadOnlyCollection_ReturnsExpectedValues_True() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> truePredicate = (value) => true; IEnumerable<int> result = source.Where(truePredicate); Assert.Equal(source.Count, result.Count()); for (int i = 0; i < source.Count; i++) { Assert.Equal(source.ElementAt(i), result.ElementAt(i)); } } [Fact] public void Where_IReadOnlyCollection_ReturnsExpectedValues_False() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> falsePredicate = (value) => false; IEnumerable<int> result = source.Where(falsePredicate); Assert.Equal(0, result.Count()); } [Fact] public void Where_IReadOnlyCollection_ReturnsExpectedValues_Complex() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 2, 1, 3, 5, 4 }); Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); }; IEnumerable<int> result = source.Where(complexPredicate); Assert.Equal(2, result.Count()); Assert.Equal(1, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void Where_ICollection_ReturnsExpectedValues_True() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> truePredicate = (value) => true; IEnumerable<int> result = source.Where(truePredicate); Assert.Equal(source.Count, result.Count()); for (int i = 0; i < source.Count; i++) { Assert.Equal(source.ElementAt(i), result.ElementAt(i)); } } [Fact] public void Where_ICollection_ReturnsExpectedValues_False() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> falsePredicate = (value) => false; IEnumerable<int> result = source.Where(falsePredicate); Assert.Equal(0, result.Count()); } [Fact] public void Where_ICollection_ReturnsExpectedValues_Complex() { ICollection<int> source = new LinkedList<int>(new List<int> { 2, 1, 3, 5, 4 }); Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); }; IEnumerable<int> result = source.Where(complexPredicate); Assert.Equal(2, result.Count()); Assert.Equal(1, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void Where_IEnumerable_ReturnsExpectedValues_True() { IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, bool> truePredicate = (value) => true; IEnumerable<int> result = source.Where(truePredicate); Assert.Equal(source.Count(), result.Count()); for (int i = 0; i < source.Count(); i++) { Assert.Equal(source.ElementAt(i), result.ElementAt(i)); } } [Fact] public void Where_IEnumerable_ReturnsExpectedValues_False() { IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, bool> falsePredicate = (value) => false; IEnumerable<int> result = source.Where(falsePredicate); Assert.Equal(0, result.Count()); } [Fact] public void Where_IEnumerable_ReturnsExpectedValues_Complex() { IEnumerable<int> source = new LinkedList<int>(new List<int> { 2, 1, 3, 5, 4 }); Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); }; IEnumerable<int> result = source.Where(complexPredicate); Assert.Equal(2, result.Count()); Assert.Equal(1, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void Where_EmptyEnumerable_ReturnsNoElements() { IEnumerable<int> source = Enumerable.Empty<int>(); bool wasSelectorCalled = false; IEnumerable<int> result = source.Where(value => { wasSelectorCalled = true; return true; }); Assert.Equal(0, result.Count()); Assert.False(wasSelectorCalled); } [Fact] public void Where_EmptyEnumerable_ReturnsNoElementsWithIndex() { Assert.Empty(Enumerable.Empty<int>().Where((e, i) => true)); } [Fact] public void Where_Array_CurrentIsDefaultOfTAfterEnumeration() { int[] source = new[] { 1 }; Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Where_List_CurrentIsDefaultOfTAfterEnumeration() { List<int> source = new List<int>() { 1 }; Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Where_IReadOnlyCollection_CurrentIsDefaultOfTAfterEnumeration() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int>() { 1 }); Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Where_ICollection_CurrentIsDefaultOfTAfterEnumeration() { ICollection<int> source = new LinkedList<int>(new List<int>() { 1 }); Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Where_IEnumerable_CurrentIsDefaultOfTAfterEnumeration() { IEnumerable<int> source = Enumerable.Repeat(1, 1); Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void WhereWhere_Array_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate); Assert.Equal(2, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void WhereWhere_List_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate); Assert.Equal(2, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void WhereWhere_IReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate); Assert.Equal(2, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void WhereWhere_ICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate); Assert.Equal(2, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void WhereWhere_IEnumerable_ReturnsExpectedValues() { IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, bool> evenPredicate = (value) => value % 2 == 0; IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate); Assert.Equal(2, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); } [Fact] public void WhereSelect_Array_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelectSelect_Array_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelect_List_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelectSelect_List_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelect_IReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelectSelect_IReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelect_ICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelectSelect_ICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelect_IEnumerable_ReturnsExpectedValues() { IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void WhereSelectSelect_IEnumerable_ReturnsExpectedValues() { IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector); Assert.Equal(2, result.Count()); Assert.Equal(3, result.ElementAt(0)); Assert.Equal(5, result.ElementAt(1)); } [Fact] public void SelectWhere_Array_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate); Assert.Equal(3, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); Assert.Equal(6, result.ElementAt(2)); } [Fact] public void SelectWhere_List_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate); Assert.Equal(3, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); Assert.Equal(6, result.ElementAt(2)); } [Fact] public void SelectWhere_IReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate); Assert.Equal(3, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); Assert.Equal(6, result.ElementAt(2)); } [Fact] public void SelectWhere_ICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate); Assert.Equal(3, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); Assert.Equal(6, result.ElementAt(2)); } [Fact] public void SelectWhere_IEnumerable_ReturnsExpectedValues() { IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, bool> evenPredicate = (value) => value % 2 == 0; Func<int, int> addSelector = (value) => value + 1; IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate); Assert.Equal(3, result.Count()); Assert.Equal(2, result.ElementAt(0)); Assert.Equal(4, result.ElementAt(1)); Assert.Equal(6, result.ElementAt(2)); } #endregion #region Exceptions [Fact] public void Where_PredicateThrowsException() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, bool> predicate = value => { if (value == 1) { throw new InvalidOperationException(); } return true; }; var enumerator = source.Where(predicate).GetEnumerator(); // Ensure the first MoveNext call throws an exception Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); // Ensure Current is set to the default value of type T int currentValue = enumerator.Current; Assert.Equal(default(int), currentValue); // Ensure subsequent MoveNext calls succeed Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); } [Fact] public void Where_SourceThrowsOnCurrent() { IEnumerable<int> source = new ThrowsOnCurrentEnumerator(); Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); // Ensure the first MoveNext call throws an exception Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); // Ensure subsequent MoveNext calls succeed Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); } [Fact] public void Where_SourceThrowsOnMoveNext() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); // Ensure the first MoveNext call throws an exception Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); // Ensure Current is set to the default value of type T int currentValue = enumerator.Current; Assert.Equal(default(int), currentValue); // Ensure subsequent MoveNext calls succeed Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); } [Fact] public void Where_SourceThrowsOnGetEnumerator() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); // Ensure the first MoveNext call throws an exception Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); // Ensure Current is set to the default value of type T int currentValue = enumerator.Current; Assert.Equal(default(int), currentValue); // Ensure subsequent MoveNext calls succeed Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); } [Fact] public void Select_ResetEnumerator_ThrowsException() { int[] source = new[] { 1, 2, 3, 4, 5 }; IEnumerator<int> enumerator = source.Where(value => true).GetEnumerator(); // The full .NET Framework throws a NotImplementedException. // See https://github.com/dotnet/corefx/pull/2959. if (PlatformDetection.IsFullFramework) { Assert.Throws<NotImplementedException>(() => enumerator.Reset()); } else { Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } } [Fact] public void Where_SourceThrowsOnConcurrentModification() { List<int> source = new List<int>() { 1, 2, 3, 4, 5 }; Func<int, bool> truePredicate = (value) => true; var enumerator = source.Where(truePredicate).GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); source.Add(6); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } #endregion [Fact] public void Where_GetEnumeratorReturnsUniqueInstances() { int[] source = new[] { 1, 2, 3, 4, 5 }; var result = source.Where(value => true); using (var enumerator1 = result.GetEnumerator()) using (var enumerator2 = result.GetEnumerator()) { Assert.Same(result, enumerator1); Assert.NotSame(enumerator1, enumerator2); } } [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > int.MinValue select x; Assert.Equal(q.Where(IsEven), q.Where(IsEven)); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", null, "SoS", string.Empty } select x; Assert.Equal(q.Where(string.IsNullOrEmpty), q.Where(string.IsNullOrEmpty)); } [Fact] public void SingleElementPredicateFalse() { int[] source = { 3 }; Assert.Empty(source.Where(IsEven)); } [Fact] public void PredicateFalseForAll() { int[] source = { 9, 7, 15, 3, 27 }; Assert.Empty(source.Where(IsEven)); } [Fact] public void PredicateTrueFirstOnly() { int[] source = { 10, 9, 7, 15, 3, 27 }; Assert.Equal(source.Take(1), source.Where(IsEven)); } [Fact] public void PredicateTrueLastOnly() { int[] source = { 9, 7, 15, 3, 27, 20 }; Assert.Equal(source.Skip(source.Length - 1), source.Where(IsEven)); } [Fact] public void PredicateTrueFirstThirdSixth() { int[] source = { 20, 7, 18, 9, 7, 10, 21 }; int[] expected = { 20, 18, 10 }; Assert.Equal(expected, source.Where(IsEven)); } [Fact] public void RunOnce() { int[] source = { 20, 7, 18, 9, 7, 10, 21 }; int[] expected = { 20, 18, 10 }; Assert.Equal(expected, source.RunOnce().Where(IsEven)); } [Fact] public void SourceAllNullsPredicateTrue() { int?[] source = { null, null, null, null }; Assert.Equal(source, source.Where(num => true)); } [Fact] public void SourceEmptyIndexedPredicate() { Assert.Empty(Enumerable.Empty<int>().Where((e, i) => i % 2 == 0)); } [Fact] public void SingleElementIndexedPredicateTrue() { int[] source = { 2 }; Assert.Equal(source, source.Where((e, i) => e % 2 == 0)); } [Fact] public void SingleElementIndexedPredicateFalse() { int[] source = { 3 }; Assert.Empty(source.Where((e, i) => e % 2 == 0)); } [Fact] public void IndexedPredicateFalseForAll() { int[] source = { 9, 7, 15, 3, 27 }; Assert.Empty(source.Where((e, i) => e % 2 == 0)); } [Fact] public void IndexedPredicateTrueFirstOnly() { int[] source = { 10, 9, 7, 15, 3, 27 }; Assert.Equal(source.Take(1), source.Where((e, i) => e % 2 == 0)); } [Fact] public void IndexedPredicateTrueLastOnly() { int[] source = { 9, 7, 15, 3, 27, 20 }; Assert.Equal(source.Skip(source.Length - 1), source.Where((e, i) => e % 2 == 0)); } [Fact] public void IndexedPredicateTrueFirstThirdSixth() { int[] source = { 20, 7, 18, 9, 7, 10, 21 }; int[] expected = { 20, 18, 10 }; Assert.Equal(expected, source.Where((e, i) => e % 2 == 0)); } [Fact] public void SourceAllNullsIndexedPredicateTrue() { int?[] source = { null, null, null, null }; Assert.Equal(source, source.Where((num, index) => true)); } [Fact] public void PredicateSelectsFirst() { int[] source = { -40, 20, 100, 5, 4, 9 }; Assert.Equal(source.Take(1), source.Where((e, i) => i == 0)); } [Fact] public void PredicateSelectsLast() { int[] source = { -40, 20, 100, 5, 4, 9 }; Assert.Equal(source.Skip(source.Length - 1), source.Where((e, i) => i == source.Length - 1)); } [Fact(Skip = "Valid test but too intensive to enable even in OuterLoop")] public void IndexOverflows() { var infiniteWhere = new FastInfiniteEnumerator<int>().Where((e, i) => true); using (var en = infiniteWhere.GetEnumerator()) Assert.Throws<OverflowException>(() => { while (en.MoveNext()) { } }); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Where(i => true); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateArray() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Where(i => true); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Where(i => true); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIndexed() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Where((e, i) => true); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateWhereSelect() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Where(i => true).Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateWhereSelectArray() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Where(i => true).Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateWhereSelectList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Where(i => true).Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Theory] [MemberData(nameof(ToCollectionData))] public void ToCollection(IEnumerable<int> source) { foreach (IEnumerable<int> equivalent in new[] { source.Where(s => true), source.Where(s => true).Select(s => s) }) { Assert.Equal(source, equivalent); Assert.Equal(source, equivalent.ToArray()); Assert.Equal(source, equivalent.ToList()); Assert.Equal(source.Count(), equivalent.Count()); // Count may be optimized. The above asserts do not imply this will pass. using (IEnumerator<int> en = equivalent.GetEnumerator()) { for (int i = 0; i < equivalent.Count(); i++) { Assert.True(en.MoveNext()); } Assert.False(en.MoveNext()); // No more items, this should dispose. Assert.Equal(0, en.Current); // Reset to default value Assert.False(en.MoveNext()); // Want to be sure MoveNext after disposing still works. Assert.Equal(0, en.Current); } } } public static IEnumerable<object[]> ToCollectionData() { IEnumerable<int> seq = GenerateRandomSequnce(seed: 0xdeadbeef, count: 10); foreach (IEnumerable<int> seq2 in IdentityTransforms<int>().Select(t => t(seq))) { yield return new object[] { seq2 }; } } private static IEnumerable<int> GenerateRandomSequnce(uint seed, int count) { var random = new Random(unchecked((int)seed)); for (int i = 0; i < count; i++) { yield return random.Next(int.MinValue, int.MaxValue); } } } }
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 TokenApi.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; } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.FSharp.ProjectSystem; using ErrorHandler = Microsoft.VisualStudio.ErrorHandler; using VSLangProj; using System.Collections; using System.Diagnostics.CodeAnalysis; namespace Microsoft.VisualStudio.FSharp.ProjectSystem.Automation { /// <summary> /// Represents the automation object for the equivalent ReferenceContainerNode object /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ComVisible(true)] public class OAReferences : ConnectionPointContainer, IEventSource<_dispReferencesEvents>, References, ReferencesEvents { private ReferenceContainerNode container; internal OAReferences(ReferenceContainerNode containerNode) { container = containerNode; AddEventSource<_dispReferencesEvents>(this as IEventSource<_dispReferencesEvents>); container.OnChildAdded += new EventHandler<HierarchyNodeEventArgs>(OnReferenceAdded); container.OnChildRemoved += new EventHandler<HierarchyNodeEventArgs>(OnReferenceRemoved); } private Reference AddFromSelectorData(VSCOMPONENTSELECTORDATA selector) { ReferenceNode refNode = container.AddReferenceFromSelectorData(selector); if (null == refNode) { return null; } return refNode.Object as Reference; } private Reference FindByName(string stringIndex) { foreach (Reference refNode in this) { if (0 == string.Compare(refNode.Name, stringIndex, StringComparison.Ordinal)) { return refNode; } } return null; } public Reference Add(string bstrPath) { if (string.IsNullOrEmpty(bstrPath)) { return null; } return UIThread.DoOnUIThread(delegate(){ // approximate the C#/VB logic found in vsproject\vsproject\vsextrefs.cpp: STDMETHODIMP CVsProjExtRefMgr::Add(BSTR bstrPath, Reference** ppRefExtObject) bool isFusionName = bstrPath[0] == '*' || bstrPath.Contains(","); var isFullPath = false; VSCOMPONENTTYPE selectorType = VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus; // now we mimic behavior of CVsProjExtRefMgr::Add more precisely: // if bstrFile is absolute path and file exists - add file reference if (!isFusionName) { try { if (System.IO.Path.IsPathRooted(bstrPath)) { isFullPath = true; if (System.IO.File.Exists(bstrPath)) { selectorType = VSCOMPONENTTYPE.VSCOMPONENTTYPE_File; } } } catch (ArgumentException) { } } if (!isFullPath && bstrPath[0] != '*') { bstrPath = "*" + bstrPath; // may be e.g. just System.Xml, '*' will cause us to resolve it like MSBuild would } VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA(); selector.type = selectorType; selector.bstrFile = bstrPath; return AddFromSelectorData(selector); }); } public Reference AddActiveX(string bstrTypeLibGuid, int lMajorVer, int lMinorVer, int lLocaleId, string bstrWrapperTool) { return UIThread.DoOnUIThread(delegate(){ VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA(); selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2; selector.guidTypeLibrary = new Guid(bstrTypeLibGuid); selector.lcidTypeLibrary = (uint)lLocaleId; selector.wTypeLibraryMajorVersion = (ushort)lMajorVer; selector.wTypeLibraryMinorVersion = (ushort)lMinorVer; return AddFromSelectorData(selector); }); } public Reference AddProject(EnvDTE.Project pProject) { if (null == pProject) { return null; } return UIThread.DoOnUIThread(delegate(){ // Get the soulution. IVsSolution solution = container.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution; if (null == solution) { return null; } // Get the hierarchy for this project. IVsHierarchy projectHierarchy; ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(pProject.UniqueName, out projectHierarchy)); // Create the selector data. VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA(); selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project; // Get the project reference string. ErrorHandler.ThrowOnFailure(solution.GetProjrefOfProject(projectHierarchy, out selector.bstrProjRef)); selector.bstrTitle = pProject.Name; selector.bstrFile = pProject.FullName; return AddFromSelectorData(selector); }); } public EnvDTE.Project ContainingProject { get { return UIThread.DoOnUIThread(delegate(){ return container.ProjectMgr.GetAutomationObject() as EnvDTE.Project; }); } } public int Count { get { return UIThread.DoOnUIThread(delegate(){ return container.EnumReferences().Count; }); } } public EnvDTE.DTE DTE { get { return UIThread.DoOnUIThread(delegate(){ return container.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; }); } } public Reference Find(string bstrIdentity) { if (string.IsNullOrEmpty(bstrIdentity)) { return null; } return UIThread.DoOnUIThread(delegate(){ foreach (Reference refNode in this) { if (null != refNode) { if (0 == string.Compare(bstrIdentity, refNode.Identity, StringComparison.Ordinal)) { return refNode; } } } return null; }); } public IEnumerator GetEnumerator() { return UIThread.DoOnUIThread(delegate(){ List<Reference> references = new List<Reference>(); IEnumerator baseEnum = container.EnumReferences().GetEnumerator(); if (null == baseEnum) { return references.GetEnumerator(); } while (baseEnum.MoveNext()) { ReferenceNode refNode = baseEnum.Current as ReferenceNode; if (null == refNode) { continue; } Reference reference = refNode.Object as Reference; if (null != reference) { references.Add(reference); } } return references.GetEnumerator(); }); } public Reference Item(object index) { return UIThread.DoOnUIThread(delegate(){ string stringIndex = index as string; if (null != stringIndex) { return FindByName(stringIndex); } // Note that this cast will throw if the index is not convertible to int. int intIndex = (int)index; IList<ReferenceNode> refs = container.EnumReferences(); if (null == refs) { throw new ArgumentOutOfRangeException(); } if ((intIndex <= 0) || (intIndex > refs.Count)) { throw new ArgumentOutOfRangeException(); } // Let the implementation of IList<> throw in case of index not correct. return refs[intIndex - 1].Object as Reference; }); } public object Parent { get { return UIThread.DoOnUIThread(delegate(){ return container.Parent.Object; }); } } public event _dispReferencesEvents_ReferenceAddedEventHandler ReferenceAdded; public event _dispReferencesEvents_ReferenceChangedEventHandler ReferenceChanged; public event _dispReferencesEvents_ReferenceRemovedEventHandler ReferenceRemoved; private void OnReferenceAdded(object sender, HierarchyNodeEventArgs args) { // Validate the parameters. if ((container != sender as ReferenceContainerNode) || (null == args) || (null == args.Child)) { return; } // Check if there is any sink for this event. if (null == ReferenceAdded) { return; } // Check that the removed item implements the Reference interface. Reference reference = args.Child.Object as Reference; if (null != reference) { ReferenceAdded(reference); } } private void OnReferenceChanged(object sender, HierarchyNodeEventArgs args) { // Check if there is any sink for this event. if (null == ReferenceChanged) { return; } // The sender of this event should be the reference node that was changed ReferenceNode refNode = sender as ReferenceNode; if (null == refNode) { return; } // Check that the removed item implements the Reference interface. Reference reference = refNode.Object as Reference; if (null != reference) { ReferenceChanged(reference); } } private void OnReferenceRemoved(object sender, HierarchyNodeEventArgs args) { // Validate the parameters. if ((container != sender as ReferenceContainerNode) || (null == args) || (null == args.Child)) { return; } // Check if there is any sink for this event. if (null == ReferenceRemoved) { return; } // Check that the removed item implements the Reference interface. Reference reference = args.Child.Object as Reference; if (null != reference) { ReferenceRemoved(reference); } } void IEventSource<_dispReferencesEvents>.OnSinkAdded(_dispReferencesEvents sink) { ReferenceAdded += new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded); ReferenceChanged += new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged); ReferenceRemoved += new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved); } void IEventSource<_dispReferencesEvents>.OnSinkRemoved(_dispReferencesEvents sink) { ReferenceAdded -= new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded); ReferenceChanged -= new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged); ReferenceRemoved -= new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved); } } }
//------------------------------------------------------------------------------ // <copyright file="AsyncCopyController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Blob.Protocol; using Microsoft.WindowsAzure.Storage.File; internal abstract class AsyncCopyController : TransferControllerBase { /// <summary> /// Timer to signal refresh status. /// </summary> private Timer statusRefreshTimer; /// <summary> /// Lock to protect statusRefreshTimer. /// </summary> private object statusRefreshTimerLock = new object(); /// <summary> /// Keeps track of the internal state-machine state. /// </summary> private volatile State state; /// <summary> /// Indicates whether the controller has work available /// or not for the calling code. /// </summary> private bool hasWork; /// <summary> /// Indicates the BytesCopied value of last CopyState /// </summary> private long lastBytesCopied; /// <summary> /// Initializes a new instance of the <see cref="AsyncCopyController"/> class. /// </summary> /// <param name="scheduler">Scheduler object which creates this object.</param> /// <param name="transferJob">Instance of job to start async copy.</param> /// <param name="userCancellationToken">Token user input to notify about cancellation.</param> internal AsyncCopyController( TransferScheduler scheduler, TransferJob transferJob, CancellationToken userCancellationToken) : base(scheduler, transferJob, userCancellationToken) { if (null == transferJob.Destination) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ParameterCannotBeNullException, "Dest"), "transferJob"); } if ((null == transferJob.Source.SourceUri && null == transferJob.Source.Blob && null == transferJob.Source.AzureFile) || (null != transferJob.Source.SourceUri && null != transferJob.Source.Blob) || (null != transferJob.Source.Blob && null != transferJob.Source.AzureFile) || (null != transferJob.Source.SourceUri && null != transferJob.Source.AzureFile)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ProvideExactlyOneOfThreeParameters, "Source.SourceUri", "Source.Blob", "Source.AzureFile"), "transferJob"); } this.SourceUri = this.TransferJob.Source.SourceUri; this.SourceBlob = this.TransferJob.Source.Blob; this.SourceFile = this.TransferJob.Source.AzureFile; // initialize the status refresh timer this.statusRefreshTimer = new Timer( new TimerCallback( delegate(object timerState) { this.hasWork = true; })); this.SetInitialStatus(); } /// <summary> /// Internal state values. /// </summary> private enum State { FetchSourceAttributes, GetDestination, StartCopy, GetCopyState, Finished, Error, } public override bool HasWork { get { return this.hasWork; } } protected CloudBlob SourceBlob { get; private set; } protected CloudFile SourceFile { get; private set; } protected Uri SourceUri { get; private set; } protected abstract Uri DestUri { get; } public static AsyncCopyController CreateAsyncCopyController(TransferScheduler transferScheduler, TransferJob transferJob, CancellationToken cancellationToken) { if (transferJob.Destination.TransferLocationType == TransferLocationType.AzureFile) { return new FileAsyncCopyController(transferScheduler, transferJob, cancellationToken); } if (transferJob.Destination.TransferLocationType == TransferLocationType.AzureBlob) { return new BlobAsyncCopyController(transferScheduler, transferJob, cancellationToken); } throw new InvalidOperationException(Resources.CanOnlyCopyToFileOrBlobException); } /// <summary> /// Do work in the controller. /// A controller controls the whole transfer from source to destination, /// which could be split into several work items. This method is to let controller to do one of those work items. /// There could be several work items to do at the same time in the controller. /// </summary> /// <returns>Whether the controller has completed. This is to tell <c>TransferScheduler</c> /// whether the controller can be disposed.</returns> protected override async Task<bool> DoWorkInternalAsync() { switch (this.state) { case State.FetchSourceAttributes: await this.FetchSourceAttributesAsync(); break; case State.GetDestination: await this.GetDestinationAsync(); break; case State.StartCopy: await this.StartCopyAsync(); break; case State.GetCopyState: await this.GetCopyStateAsync(); break; case State.Finished: case State.Error: default: break; } return (State.Error == this.state || State.Finished == this.state); } /// <summary> /// Sets the state of the controller to Error, while recording /// the last occurred exception and setting the HasWork and /// IsFinished fields. /// </summary> /// <param name="ex">Exception to record.</param> protected override void SetErrorState(Exception ex) { Debug.Assert( this.state != State.Finished, "SetErrorState called, while controller already in Finished state"); this.state = State.Error; this.hasWork = false; } /// <summary> /// Taken from <c>Microsoft.WindowsAzure.Storage.Core.Util.HttpUtility</c>: Parse the http query string. /// </summary> /// <param name="query">Http query string.</param> /// <returns>A dictionary of query pairs.</returns> protected static Dictionary<string, string> ParseQueryString(string query) { Dictionary<string, string> retVal = new Dictionary<string, string>(); if (query == null || query.Length == 0) { return retVal; } // remove ? if present if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } string[] valuePairs = query.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries); foreach (string vp in valuePairs) { int equalDex = vp.IndexOf("=", StringComparison.OrdinalIgnoreCase); if (equalDex < 0) { retVal.Add(Uri.UnescapeDataString(vp), null); continue; } string key = vp.Substring(0, equalDex); string value = vp.Substring(equalDex + 1); retVal.Add(Uri.UnescapeDataString(key), Uri.UnescapeDataString(value)); } return retVal; } private void SetInitialStatus() { switch (this.TransferJob.Status) { case TransferJobStatus.NotStarted: this.TransferJob.Status = TransferJobStatus.Transfer; break; case TransferJobStatus.Transfer: break; case TransferJobStatus.Monitor: break; case TransferJobStatus.Finished: default: throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, Resources.InvalidInitialEntryStatusForControllerException, this.TransferJob.Status, this.GetType().Name)); } this.SetHasWorkAfterStatusChanged(); } private void SetHasWorkAfterStatusChanged() { if (TransferJobStatus.Transfer == this.TransferJob.Status) { if (null != this.SourceUri) { this.state = State.GetDestination; } else { this.state = State.FetchSourceAttributes; } } else if(TransferJobStatus.Monitor == this.TransferJob.Status) { this.state = State.GetCopyState; } else { Debug.Fail("We should never be here"); } this.hasWork = true; } private async Task FetchSourceAttributesAsync() { Debug.Assert( this.state == State.FetchSourceAttributes, "FetchSourceAttributesAsync called, but state isn't FetchSourceAttributes"); this.hasWork = false; this.StartCallbackHandler(); try { await this.DoFetchSourceAttributesAsync(); } catch (StorageException e) { HandleFetchSourceAttributesException(e); throw; } this.TransferJob.Source.CheckedAccessCondition = true; this.state = State.GetDestination; this.hasWork = true; } private static void HandleFetchSourceAttributesException(StorageException e) { // Getting a storage exception is expected if the source doesn't // exist. For those cases that indicate the source doesn't exist // we will set a specific error state. if (null != e.RequestInformation && e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { throw new InvalidOperationException(Resources.SourceDoesNotExistException); } } private async Task GetDestinationAsync() { Debug.Assert( this.state == State.GetDestination, "GetDestinationAsync called, but state isn't GetDestination"); this.hasWork = false; this.StartCallbackHandler(); try { await this.DoFetchDestAttributesAsync(); } catch (StorageException se) { if (!this.HandleGetDestinationResult(se)) { throw se; } return; } this.HandleGetDestinationResult(null); } private bool HandleGetDestinationResult(Exception e) { bool destExist = true; if (null != e) { StorageException se = e as StorageException; // Getting a storage exception is expected if the destination doesn't // exist. In this case we won't error out, but set the // destExist flag to false to indicate we will copy to // a new blob/file instead of overwriting an existing one. if (null != se && null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { destExist = false; } else { this.DoHandleGetDestinationException(se); return false; } } this.TransferJob.Destination.CheckedAccessCondition = true; if ((TransferJobStatus.Monitor == this.TransferJob.Status) && string.IsNullOrEmpty(this.TransferJob.CopyId)) { throw new InvalidOperationException(Resources.RestartableInfoCorruptedException); } // If destination file exists, query user whether to overwrite it. Uri sourceUri = this.GetSourceUri(); this.CheckOverwrite( destExist, sourceUri.ToString(), this.DestUri.ToString()); this.UpdateProgressAddBytesTransferred(0); this.state = State.StartCopy; this.hasWork = true; return true; } private async Task StartCopyAsync() { Debug.Assert( this.state == State.StartCopy, "StartCopyAsync called, but state isn't StartCopy"); this.hasWork = false; try { this.TransferJob.CopyId = await this.DoStartCopyAsync(); } catch (StorageException se) { if (!this.HandleStartCopyResult(se)) { throw; } return; } this.HandleStartCopyResult(null); } private bool HandleStartCopyResult(StorageException se) { if (null != se) { if (null != se.RequestInformation && null != se.RequestInformation.ExtendedErrorInformation && BlobErrorCodeStrings.PendingCopyOperation == se.RequestInformation.ExtendedErrorInformation.ErrorCode) { CopyState copyState = this.FetchCopyStateAsync().Result; if (null == copyState) { return false; } string baseUriString = copyState.Source.GetComponents( UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); Uri sourceUri = this.GetSourceUri(); string ourBaseUriString = sourceUri.GetComponents(UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); DateTimeOffset? baseSnapshot = null; DateTimeOffset? ourSnapshot = null == this.SourceBlob ? null : this.SourceBlob.SnapshotTime; string snapshotString; if (ParseQueryString(copyState.Source.Query).TryGetValue("snapshot", out snapshotString)) { if (!string.IsNullOrEmpty(snapshotString)) { DateTimeOffset snapshotTime; if (DateTimeOffset.TryParse( snapshotString, CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out snapshotTime)) { baseSnapshot = snapshotTime; } } } if (!baseUriString.Equals(ourBaseUriString) || !baseSnapshot.Equals(ourSnapshot)) { return false; } if (string.IsNullOrEmpty(this.TransferJob.CopyId)) { this.TransferJob.CopyId = copyState.CopyId; } } else { return false; } } this.state = State.GetCopyState; this.hasWork = true; return true; } private async Task GetCopyStateAsync() { Debug.Assert( this.state == State.GetCopyState, "GetCopyStateAsync called, but state isn't GetCopyState"); this.hasWork = false; this.StartCallbackHandler(); CopyState copyState = null; try { copyState = await this.FetchCopyStateAsync(); } catch (StorageException se) { if (null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { // The reason of 404 (Not Found) may be that the destination blob has not been created yet. this.RestartTimer(); } else { throw; } } this.HandleFetchCopyStateResult(copyState); } private void HandleFetchCopyStateResult(CopyState copyState) { if (null == copyState) { // Reach here, the destination should already exist. string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToRetrieveCopyStateForObjectException, this.DestUri.ToString()); throw new TransferException( TransferErrorCode.FailToRetrieveCopyStateForObject, exceptionMessage); } else { // Verify we are monitoring the right blob copying process. if (!this.TransferJob.CopyId.Equals(copyState.CopyId)) { throw new TransferException( TransferErrorCode.MismatchCopyId, Resources.MismatchFoundBetweenLocalAndServerCopyIdsException); } if (CopyStatus.Success == copyState.Status) { this.UpdateTransferProgress(copyState); this.DisposeStatusRefreshTimer(); this.SetFinished(); } else if (CopyStatus.Pending == copyState.Status) { this.UpdateTransferProgress(copyState); // Wait a period to restart refresh the status. this.RestartTimer(); } else { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToAsyncCopyObjectException, this.GetSourceUri().ToString(), this.DestUri.ToString(), copyState.Status.ToString(), copyState.StatusDescription); // CopyStatus.Invalid | Failed | Aborted throw new TransferException( TransferErrorCode.AsyncCopyFailed, exceptionMessage); } } } private void UpdateTransferProgress(CopyState copyState) { if (null != copyState && copyState.TotalBytes.HasValue) { Debug.Assert( copyState.BytesCopied.HasValue, "BytesCopied cannot be null as TotalBytes is not null."); if (this.TransferContext != null) { long bytesTransferred = copyState.BytesCopied.Value; this.UpdateProgressAddBytesTransferred(bytesTransferred - this.lastBytesCopied); this.lastBytesCopied = bytesTransferred; } } } private void SetFinished() { this.state = State.Finished; this.hasWork = false; this.FinishCallbackHandler(null); } private void RestartTimer() { // Wait a period to restart refresh the status. this.statusRefreshTimer.Change( TimeSpan.FromMilliseconds(Constants.AsyncCopyStatusRefreshWaitTimeInMilliseconds), new TimeSpan(-1)); } private void DisposeStatusRefreshTimer() { if (null != this.statusRefreshTimer) { lock (this.statusRefreshTimerLock) { if (null != this.statusRefreshTimer) { this.statusRefreshTimer.Dispose(); this.statusRefreshTimer = null; } } } } private Uri GetSourceUri() { if (null != this.SourceUri) { return this.SourceUri; } if (null != this.SourceBlob) { return this.SourceBlob.SnapshotQualifiedUri; } return this.SourceFile.Uri; } protected async Task DoFetchSourceAttributesAsync() { AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( this.TransferJob.Source.AccessCondition, this.TransferJob.Source.CheckedAccessCondition); OperationContext operationContext = Utils.GenerateOperationContext(this.TransferContext); if (this.SourceBlob != null) { await this.SourceBlob.FetchAttributesAsync( accessCondition, Utils.GenerateBlobRequestOptions(this.TransferJob.Source.BlobRequestOptions), operationContext, this.CancellationToken); } else if (this.SourceFile != null) { await this.SourceFile.FetchAttributesAsync( accessCondition, Utils.GenerateFileRequestOptions(this.TransferJob.Source.FileRequestOptions), operationContext, this.CancellationToken); } } protected abstract Task DoFetchDestAttributesAsync(); protected abstract Task<string> DoStartCopyAsync(); protected abstract void DoHandleGetDestinationException(StorageException se); protected abstract Task<CopyState> FetchCopyStateAsync(); } }
using UnityEngine; namespace Pathfinding.Voxels { using Pathfinding.Util; public partial class Voxelize { /** Returns T iff (v_i, v_j) is a proper internal * diagonal of P. */ public static bool Diagonal (int i, int j, int n, int[] verts, int[] indices) { return InCone(i, j, n, verts, indices) && Diagonalie(i, j, n, verts, indices); } public static bool InCone (int i, int j, int n, int[] verts, int[] indices) { int pi = (indices[i] & 0x0fffffff) * 4; int pj = (indices[j] & 0x0fffffff) * 4; int pi1 = (indices[Next(i, n)] & 0x0fffffff) * 4; int pin1 = (indices[Prev(i, n)] & 0x0fffffff) * 4; // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. if (LeftOn(pin1, pi, pi1, verts)) return Left(pi, pj, pin1, verts) && Left(pj, pi, pi1, verts); // Assume (i-1,i,i+1) not collinear. // else P[i] is reflex. return !(LeftOn(pi, pj, pi1, verts) && LeftOn(pj, pi, pin1, verts)); } /** Returns true iff c is strictly to the left of the directed * line through a to b. */ public static bool Left (int a, int b, int c, int[] verts) { return Area2(a, b, c, verts) < 0; } public static bool LeftOn (int a, int b, int c, int[] verts) { return Area2(a, b, c, verts) <= 0; } public static bool Collinear (int a, int b, int c, int[] verts) { return Area2(a, b, c, verts) == 0; } public static int Area2 (int a, int b, int c, int[] verts) { return (verts[b] - verts[a]) * (verts[c+2] - verts[a+2]) - (verts[c+0] - verts[a+0]) * (verts[b+2] - verts[a+2]); } /** * Returns T iff (v_i, v_j) is a proper internal *or* external * diagonal of P, *ignoring edges incident to v_i and v_j*. */ static bool Diagonalie (int i, int j, int n, int[] verts, int[] indices) { int d0 = (indices[i] & 0x0fffffff) * 4; int d1 = (indices[j] & 0x0fffffff) * 4; /*int a = (i+1) % indices.Length; * if (a == j) a = (i-1 + indices.Length) % indices.Length; * int a_v = (indices[a] & 0x0fffffff) * 4; * * if (a != j && Collinear (d0,a_v,d1,verts)) { * return false; * }*/ // For each edge (k,k+1) of P for (int k = 0; k < n; k++) { int k1 = Next(k, n); // Skip edges incident to i or j if (!((k == i) || (k1 == i) || (k == j) || (k1 == j))) { int p0 = (indices[k] & 0x0fffffff) * 4; int p1 = (indices[k1] & 0x0fffffff) * 4; if (Vequal(d0, p0, verts) || Vequal(d1, p0, verts) || Vequal(d0, p1, verts) || Vequal(d1, p1, verts)) continue; if (Intersect(d0, d1, p0, p1, verts)) return false; } } return true; } // Exclusive or: true iff exactly one argument is true. // The arguments are negated to ensure that they are 0/1 // values. Then the bitwise Xor operator may apply. // (This idea is due to Michael Baldwin.) public static bool Xorb (bool x, bool y) { return !x ^ !y; } // Returns true iff ab properly intersects cd: they share // a point interior to both segments. The properness of the // intersection is ensured by using strict leftness. public static bool IntersectProp (int a, int b, int c, int d, int[] verts) { // Eliminate improper cases. if (Collinear(a, b, c, verts) || Collinear(a, b, d, verts) || Collinear(c, d, a, verts) || Collinear(c, d, b, verts)) return false; return Xorb(Left(a, b, c, verts), Left(a, b, d, verts)) && Xorb(Left(c, d, a, verts), Left(c, d, b, verts)); } // Returns T iff (a,b,c) are collinear and point c lies // on the closed segement ab. static bool Between (int a, int b, int c, int[] verts) { if (!Collinear(a, b, c, verts)) return false; // If ab not vertical, check betweenness on x; else on y. if (verts[a+0] != verts[b+0]) return ((verts[a+0] <= verts[c+0]) && (verts[c+0] <= verts[b+0])) || ((verts[a+0] >= verts[c+0]) && (verts[c+0] >= verts[b+0])); else return ((verts[a+2] <= verts[c+2]) && (verts[c+2] <= verts[b+2])) || ((verts[a+2] >= verts[c+2]) && (verts[c+2] >= verts[b+2])); } // Returns true iff segments ab and cd intersect, properly or improperly. static bool Intersect (int a, int b, int c, int d, int[] verts) { if (IntersectProp(a, b, c, d, verts)) return true; else if (Between(a, b, c, verts) || Between(a, b, d, verts) || Between(c, d, a, verts) || Between(c, d, b, verts)) return true; else return false; } static bool Vequal (int a, int b, int[] verts) { return verts[a+0] == verts[b+0] && verts[a+2] == verts[b+2]; } /** (i-1+n) % n assuming 0 <= i < n */ public static int Prev (int i, int n) { return i-1 >= 0 ? i-1 : n-1; } /** (i+1) % n assuming 0 <= i < n */ public static int Next (int i, int n) { return i+1 < n ? i+1 : 0; } /** Builds a polygon mesh from a contour set. * * \param cset contour set to build a mesh from. * \param nvp Maximum allowed vertices per polygon. \warning Currently locked to 3. * \param mesh Results will be written to this mesh. */ public void BuildPolyMesh (VoxelContourSet cset, int nvp, out VoxelMesh mesh) { AstarProfiler.StartProfile("Build Poly Mesh"); nvp = 3; int maxVertices = 0; int maxTris = 0; int maxVertsPerCont = 0; for (int i = 0; i < cset.conts.Count; i++) { // Skip null contours. if (cset.conts[i].nverts < 3) continue; maxVertices += cset.conts[i].nverts; maxTris += cset.conts[i].nverts - 2; maxVertsPerCont = System.Math.Max(maxVertsPerCont, cset.conts[i].nverts); } Int3[] verts = ArrayPool<Int3>.Claim(maxVertices); int[] polys = ArrayPool<int>.Claim(maxTris*nvp); int[] areas = ArrayPool<int>.Claim(maxTris); Pathfinding.Util.Memory.MemSet<int>(polys, 0xff, sizeof(int)); int[] indices = ArrayPool<int>.Claim(maxVertsPerCont); int[] tris = ArrayPool<int>.Claim(maxVertsPerCont*3); int vertexIndex = 0; int polyIndex = 0; int areaIndex = 0; for (int i = 0; i < cset.conts.Count; i++) { VoxelContour cont = cset.conts[i]; // Skip degenerate contours if (cont.nverts < 3) { continue; } for (int j = 0; j < cont.nverts; j++) { indices[j] = j; // Convert the z coordinate from the form z*voxelArea.width which is used in other places for performance cont.verts[j*4+2] /= voxelArea.width; } // Triangulate the contour int ntris = Triangulate(cont.nverts, cont.verts, ref indices, ref tris); // Assign the correct vertex indices int startIndex = vertexIndex; for (int j = 0; j < ntris*3; polyIndex++, j++) { //@Error sometimes polys[polyIndex] = tris[j]+startIndex; } // Mark all triangles generated by this contour // as having the area cont.area for (int j = 0; j < ntris; areaIndex++, j++) { areas[areaIndex] = cont.area; } // Copy the vertex positions for (int j = 0; j < cont.nverts; vertexIndex++, j++) { verts[vertexIndex] = new Int3(cont.verts[j*4], cont.verts[j*4+1], cont.verts[j*4+2]); } } mesh = new VoxelMesh { verts = Memory.ShrinkArray(verts, vertexIndex), tris = Memory.ShrinkArray(polys, polyIndex), areas = Memory.ShrinkArray(areas, areaIndex) }; ArrayPool<Int3>.Release(ref verts); ArrayPool<int>.Release(ref polys); ArrayPool<int>.Release(ref areas); ArrayPool<int>.Release(ref indices); ArrayPool<int>.Release(ref tris); AstarProfiler.EndProfile("Build Poly Mesh"); } int Triangulate (int n, int[] verts, ref int[] indices, ref int[] tris) { int ntris = 0; int[] dst = tris; int dstIndex = 0; // Debug code //int on = n; // The last bit of the index is used to indicate if the vertex can be removed. for (int i = 0; i < n; i++) { int i1 = Next(i, n); int i2 = Next(i1, n); if (Diagonal(i, i2, n, verts, indices)) { indices[i1] |= 0x40000000; } } while (n > 3) { #if ASTARDEBUG for (int j = 0; j < n; j++) { DrawLine(Prev(j, n), j, indices, verts, Color.red); } #endif int minLen = -1; int mini = -1; for (int q = 0; q < n; q++) { int q1 = Next(q, n); if ((indices[q1] & 0x40000000) != 0) { int p0 = (indices[q] & 0x0fffffff) * 4; int p2 = (indices[Next(q1, n)] & 0x0fffffff) * 4; int dx = verts[p2+0] - verts[p0+0]; int dz = verts[p2+2] - verts[p0+2]; #if ASTARDEBUG DrawLine(q, Next(q1, n), indices, verts, Color.blue); #endif //Squared distance int len = dx*dx + dz*dz; if (minLen < 0 || len < minLen) { minLen = len; mini = q; } } } if (mini == -1) { Debug.LogWarning("Degenerate triangles might have been generated.\n" + "Usually this is not a problem, but if you have a static level, try to modify the graph settings slightly to avoid this edge case."); // Can't run the debug stuff because we are likely running from a separate thread //for (int j=0;j<on;j++) { // DrawLine (Prev(j,on),j,indices,verts,Color.red); //} // Should not happen. /* printf("mini == -1 ntris=%d n=%d\n", ntris, n); * for (int i = 0; i < n; i++) * { * printf("%d ", indices[i] & 0x0fffffff); * } * printf("\n");*/ //yield break; return -ntris; } int i = mini; int i1 = Next(i, n); int i2 = Next(i1, n); #if ASTARDEBUG for (int j = 0; j < n; j++) { DrawLine(Prev(j, n), j, indices, verts, Color.red); } DrawLine(i, i2, indices, verts, Color.magenta); for (int j = 0; j < n; j++) { DrawLine(Prev(j, n), j, indices, verts, Color.red); } #endif dst[dstIndex] = indices[i] & 0x0fffffff; dstIndex++; dst[dstIndex] = indices[i1] & 0x0fffffff; dstIndex++; dst[dstIndex] = indices[i2] & 0x0fffffff; dstIndex++; ntris++; // Removes P[i1] by copying P[i+1]...P[n-1] left one index. n--; for (int k = i1; k < n; k++) { indices[k] = indices[k+1]; } if (i1 >= n) i1 = 0; i = Prev(i1, n); // Update diagonal flags. if (Diagonal(Prev(i, n), i1, n, verts, indices)) { indices[i] |= 0x40000000; } else { indices[i] &= 0x0fffffff; } if (Diagonal(i, Next(i1, n), n, verts, indices)) { indices[i1] |= 0x40000000; } else { indices[i1] &= 0x0fffffff; } } dst[dstIndex] = indices[0] & 0x0fffffff; dstIndex++; dst[dstIndex] = indices[1] & 0x0fffffff; dstIndex++; dst[dstIndex] = indices[2] & 0x0fffffff; dstIndex++; ntris++; return ntris; } } }
// // 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 // // 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 Microsoft.PackageManagement.Internal.Utility.Plugin { using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Extensions; internal static class DynamicTypeExtensions { private static readonly Type[] _emptyTypes = { }; private static MethodInfo _asMethod; private static MethodInfo AsMethod { get { var methods = typeof(DynamicInterfaceExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (_asMethod == null) { _asMethod = methods.FirstOrDefault(method => String.Equals(method.Name, "As", StringComparison.OrdinalIgnoreCase) && method.GetParameterTypes().Count() == 1 && method.GetParameterTypes().First() == typeof(Object)); } return _asMethod; } } internal static void OverrideInitializeLifetimeService(this TypeBuilder dynamicType) { // add override of InitLifetimeService so this object doesn't fall prey to timeouts var il = dynamicType.DefineMethod("InitializeLifetimeService", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, CallingConventions.HasThis, typeof(object), _emptyTypes).GetILGenerator(); il.LoadNull(); il.Return(); } internal static void GenerateIsMethodImplemented(this TypeBuilder dynamicType) { // special case -- the IsMethodImplemented method can give the interface owner information as to // which methods are actually implemented. var implementedMethodsField = dynamicType.DefineField("__implementedMethods", typeof(HashSet<string>), FieldAttributes.Private); var il = dynamicType.CreateMethod("IsMethodImplemented", typeof(bool), typeof(string)); il.LoadThis(); il.LoadField(implementedMethodsField); il.LoadArgument(1); il.CallVirtual(typeof(HashSet<string>).GetMethod("Contains")); il.Return(); } internal static void GenerateMethodForDirectCall(this TypeBuilder dynamicType, MethodInfo method, FieldBuilder backingField, MethodInfo instanceMethod, MethodInfo onUnhandledException) { var il = dynamicType.CreateMethod(method); // the target object has a method that matches. // let's use that. var hasReturn = method.ReturnType != typeof(void); var hasOue = onUnhandledException != null; var exit = il.DefineLabel(); var setDefaultReturn = il.DefineLabel(); var ret = hasReturn ? il.DeclareLocal(method.ReturnType) : null; var exc = hasOue ? il.DeclareLocal(typeof(Exception)) : null; il.BeginExceptionBlock(); il.LoadThis(); il.LoadField(backingField); var imTypes = instanceMethod.GetParameterTypes(); var dmTypes = method.GetParameterTypes(); for (var i = 0; i < dmTypes.Length; i++) { il.LoadArgument(i + 1); // if the types are assignable, if (imTypes[i].IsAssignableFrom(dmTypes[i])) { // it assigns straight across. } else { // it doesn't, we'll ducktype it. if (dmTypes[i].GetTypeInfo().IsPrimitive) { // box it first? il.Emit(OpCodes.Box, dmTypes[i]); } il.Call(AsMethod.MakeGenericMethod(imTypes[i])); } } // call the actual method implementation il.CallVirtual(instanceMethod); if (hasReturn) { // copy the return value in the return // check to see if we need to ducktype the return value here. if (method.ReturnType.IsAssignableFrom(instanceMethod.ReturnType)) { // it can store it directly. } else { // it doesn't assign directly, let's ducktype it. if (instanceMethod.ReturnType.GetTypeInfo().IsPrimitive) { il.Emit(OpCodes.Box, instanceMethod.ReturnType); } il.Call(AsMethod.MakeGenericMethod(method.ReturnType)); } il.StoreLocation(ret); } else { // this method isn't returning anything. if (instanceMethod.ReturnType != typeof(void)) { // pop the return value because the generated method is void and the // method we called actually gave us a result. il.Emit(OpCodes.Pop); } } il.Emit(OpCodes.Leave_S, exit); il.BeginCatchBlock(typeof(Exception)); if (hasOue) { // we're going to call the handler. il.StoreLocation(exc.LocalIndex); il.LoadArgument(0); il.Emit(OpCodes.Ldstr, instanceMethod.ToSignatureString()); il.LoadLocation(exc.LocalIndex); il.Call(onUnhandledException); il.Emit(OpCodes.Leave_S, setDefaultReturn); } else { // suppress the exception quietly il.Emit(OpCodes.Pop); il.Emit(OpCodes.Leave_S, setDefaultReturn); } il.EndExceptionBlock(); // if we can't return the appropriate value, we're returning default(T) il.MarkLabel(setDefaultReturn); SetDefaultReturnValue(il, method.ReturnType); il.Return(); // looks like we're returning the value that we got back from the implementation. il.MarkLabel(exit); if (hasReturn) { il.LoadLocation(ret.LocalIndex); } il.Return(); } internal static ILGenerator CreateMethod(this TypeBuilder dynamicType, MethodInfo method) { return dynamicType.CreateMethod(method.Name, method.ReturnType, method.GetParameterTypes()); } internal static ILGenerator CreateMethod(this TypeBuilder dynamicType, string methodName, Type returnType, params Type[] parameterTypes) { var methodBuilder = dynamicType.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, returnType, parameterTypes); return methodBuilder.GetILGenerator(); } internal static void GenerateMethodForDelegateCall(this TypeBuilder dynamicType, MethodInfo method, FieldBuilder field, MethodInfo onUnhandledException) { var il = dynamicType.CreateMethod(method); // the target object has a property or field that matches the signature we're looking for. // let's use that. var delegateType = WrappedDelegate.GetFuncOrActionType(method.GetParameterTypes(), method.ReturnType); il.LoadThis(); il.LoadField(field); for (var i = 0; i < method.GetParameterTypes().Length; i++) { il.LoadArgument(i + 1); } il.CallVirtual(delegateType.GetMethod("Invoke")); il.Return(); } internal static void GenerateStubMethod(this TypeBuilder dynamicType, MethodInfo method) { var il = dynamicType.CreateMethod(method); do { if (method.ReturnType != typeof(void)) { if (method.ReturnType.GetTypeInfo().IsPrimitive) { if (method.ReturnType == typeof(double)) { il.LoadDouble(0.0); break; } if (method.ReturnType == typeof(float)) { il.LoadFloat(0.0F); break; } il.LoadInt32(0); if (method.ReturnType == typeof(long) || method.ReturnType == typeof(ulong)) { il.ConvertToInt64(); } break; } if (method.ReturnType.GetTypeInfo().IsEnum) { // should really find out the actual default? il.LoadInt32(0); break; } if (method.ReturnType.GetTypeInfo().IsValueType) { var result = il.DeclareLocal(method.ReturnType); il.LoadLocalAddress(result); il.InitObject(method.ReturnType); il.LoadLocation(0); break; } il.LoadNull(); } } while (false); il.Return(); } private static void SetDefaultReturnValue(ILGenerator il, Type returnType) { if (returnType != typeof(void)) { if (returnType.GetTypeInfo().IsPrimitive) { if (returnType == typeof(double)) { il.LoadDouble(0.0); return; } if (returnType == typeof(float)) { il.LoadFloat(0.0F); return; } il.LoadInt32(0); if (returnType == typeof(long) || returnType == typeof(ulong)) { il.ConvertToInt64(); } return; } if (returnType.GetTypeInfo().IsEnum) { // should really find out the actual default? il.LoadInt32(0); return; } if (returnType.GetTypeInfo().IsValueType) { var result = il.DeclareLocal(returnType); il.LoadLocalAddress(result); il.InitObject(returnType); il.LoadLocation(result.LocalIndex); return; } // otherwise load null. il.LoadNull(); } } } }