context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // 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. namespace ISSE.SafetyChecking { using System; using ExecutedModel; using Utilities; public enum MomentOfIndependentFaultActivation { AtStepBeginning, OnFirstMethodWithoutUndo, OnFirstMethodWithUndo } // TODO: obsolete public enum RetraversalNormalizations { None, EmbedObserversIntoModel } public enum LtmcModelChecker { BuiltInLtmc, BuiltInDtmc, ExternalMrmc } public enum LtmdpModelChecker { BuiltInLtmdp, BuiltInNmdp, BuildInMdpWithNewStates, BuildInMdpWithFlattening } /// <summary> /// Configures S#'s model checker, determining the amount of CPU cores and memory to use. /// </summary> public struct AnalysisConfiguration { private const long DefaultStackCapacity = 1 << 20; private const long DefaultSuccessorStateCapacity = 1 << 14; private const long MinCapacity = 1024; private static readonly ModelCapacity _defaultModelCapacity = ModelCapacityByModelDensity.Normal; private int _cpuCount; private long _stackCapacity; private long _successorStateCapacity; /// <summary> /// </summary> public bool AllowFaultsOnInitialTransitions { get; set; } /// <summary> /// Simulation only: Use the probabilities of the options when selecting the result of a probabilistic choice. /// Thus, more probable options get selected more probable. Otherwise, each option has the same chance to get selected. /// </summary> public bool UseOptionProbabilitiesInSimulation { get; set; } /// <summary> /// </summary> public bool EnableEarlyTermination { get; set; } /// <summary> /// If set to true, the model checker uses a compact state storage, in which the found states are indexed by a continuous variable. /// If set to false, the traditional sparse state storage is used, which requires a little less memory and is unnoticeable faster. /// </summary> public bool UseCompactStateStorage { get; set; } /// <summary> /// Gets or sets a value indicating whether a counter example should be generated when a formula violation is detected or an /// unhandled exception occurred during model checking. /// </summary> public bool GenerateCounterExample { get; set; } /// <summary> /// Collect fault sets when conducting a MinimalCriticalSetAnalysis. /// </summary> public bool CollectFaultSets { get; set; } /// <summary> /// Gets or sets a value indicating whether only progress reports should be output. /// </summary> internal bool ProgressReportsOnly { get; set; } /// <summary> /// The TextWriter used to log the process. /// </summary> public System.IO.TextWriter DefaultTraceOutput { get; set; } /// <summary> /// Write GraphViz models of the state space to the DefaultTraceOutput when creating the models. /// </summary> public bool WriteGraphvizModels { get; set; } /// <summary> /// The default configuration. /// </summary> public static readonly AnalysisConfiguration Default = new AnalysisConfiguration { AllowFaultsOnInitialTransitions = false, UseOptionProbabilitiesInSimulation = false, EnableEarlyTermination = false, CpuCount = Int32.MaxValue, ProgressReportsOnly = false, DefaultTraceOutput = Console.Out, WriteGraphvizModels = false, ModelCapacity = _defaultModelCapacity, StackCapacity = DefaultStackCapacity, SuccessorCapacity = DefaultSuccessorStateCapacity, UseCompactStateStorage = false, GenerateCounterExample = true, CollectFaultSets = true, StateDetected = null, UseAtomarPropositionsAsStateLabels = true, MomentOfIndependentFaultActivation = MomentOfIndependentFaultActivation.OnFirstMethodWithUndo, LimitOfActiveFaults = null, RetraversalNormalizations = RetraversalNormalizations.None, LtmcModelChecker = LtmcModelChecker.BuiltInDtmc, LtmdpModelChecker = LtmdpModelChecker.BuiltInLtmdp }; /// <summary> /// Gets or sets the number of states and transitions that can be stored during model checking. /// </summary> public ModelCapacity ModelCapacity { get; set; } /// <summary> /// Gets or sets the number of states that can be stored on the stack during model checking. /// </summary> public long StackCapacity { get { return Math.Max(_stackCapacity, MinCapacity); } set { Requires.That(value >= MinCapacity, $"{nameof(StackCapacity)} must be at least {MinCapacity}."); _stackCapacity = value; } } /// <summary> /// Gets or sets the number of successor states that can be computed for each state. /// </summary> public long SuccessorCapacity { get { return Math.Max(_successorStateCapacity, MinCapacity); } set { Requires.That(value >= MinCapacity, $"{nameof(SuccessorCapacity)} must be at least {MinCapacity}."); _successorStateCapacity = value; } } /// <summary> /// Gets or sets the number of CPUs that are used for model checking. The value is automatically clamped /// to the interval of [1, #CPUs]. /// </summary> public int CpuCount { get { return _cpuCount; } set { _cpuCount = Math.Min(Environment.ProcessorCount, Math.Max(1, value)); } } /// <summary> /// Useful for debugging purposes. When a state is detected the first time then call the associated action. /// The delegate is only called in debug mode. /// A great usage example is to set "StateDetected = (state) => { if (state==190292) Debugger.Break();};" /// It makes sense to set CpuCount to 1 to omit races and ensure that a state always gets the same state /// number. /// </summary> public Action<int> StateDetected { get; set; } /// <summary> /// Determine if a formula like "Model.X==1 || Model.Y==true" should be split into the smaller parts /// "Model.X==1" and "Model.Y==true". If set to false then the maximal possible expressions are used. /// </summary> public bool UseAtomarPropositionsAsStateLabels { get; set; } /// <summary> /// </summary> public MomentOfIndependentFaultActivation MomentOfIndependentFaultActivation { get; set; } /// <summary> /// </summary> public int? LimitOfActiveFaults{ get; set; } /// <summary> /// </summary> public RetraversalNormalizations RetraversalNormalizations { get; set; } /// <summary> /// </summary> public LtmcModelChecker LtmcModelChecker { get; set; } /// <summary> /// </summary> public LtmdpModelChecker LtmdpModelChecker { get; set; } } }
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com> // Federico Di Gregorio <fog@initd.org> // // Copyright (C) 2008 Novell (http://www.novell.com) // Copyright (C) 2009 Federico Di Gregorio. // // 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. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif #if NDESK_OPTIONS namespace NDesk.Options #else namespace Mono.Options #endif { static class StringCoda { public static IEnumerable<string> WrappedLines (string self, params int[] widths) { IEnumerable<int> w = widths; return WrappedLines (self, w); } public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths) { if (widths == null) throw new ArgumentNullException ("widths"); return CreateWrappedLinesIterator (self, widths); } private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths) { if (string.IsNullOrEmpty (self)) { yield return string.Empty; yield break; } using (IEnumerator<int> ewidths = widths.GetEnumerator ()) { bool? hw = null; int width = GetNextWidth (ewidths, int.MaxValue, ref hw); int start = 0, end; do { end = GetLineEnd (start, width, self); char c = self [end-1]; if (char.IsWhiteSpace (c)) --end; bool needContinuation = end != self.Length && !IsEolChar (c); string continuation = ""; if (needContinuation) { --end; continuation = "-"; } string line = self.Substring (start, end - start) + continuation; yield return line; start = end; if (char.IsWhiteSpace (c)) ++start; width = GetNextWidth (ewidths, width, ref hw); } while (end < self.Length); } } private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid) { if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) { curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth; // '.' is any character, - is for a continuation const string minWidth = ".-"; if (curWidth < minWidth.Length) throw new ArgumentOutOfRangeException ("widths", string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); return curWidth; } // no more elements, use the last element. return curWidth; } private static bool IsEolChar (char c) { return !char.IsLetterOrDigit (c); } private static int GetLineEnd (int start, int length, string description) { int end = System.Math.Min (start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { if (description [i] == '\n') return i+1; if (IsEolChar (description [i])) sep = i+1; } if (sep == -1 || end == description.Length) return end; return sep; } } public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string> (); OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException ("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException ("prototype"); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException ("maxValueCount"); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { Type tt = typeof (T); bool nullable = tt.IsValueType && tt.IsGenericType && !tt.IsGenericTypeDefinition && tt.GetGenericTypeDefinition () == typeof (Nullable<>); Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); TypeConverter conv = TypeDescriptor.GetConverter (targetType); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString (value); } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, targetType.Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } public abstract class ArgumentSource { protected ArgumentSource () { } public abstract string[] GetNames (); public abstract string Description { get; } public abstract bool GetArguments (string value, out IEnumerable<string> replacement); public static IEnumerable<string> GetArgumentsFromFile (string file) { return GetArguments (File.OpenText (file), true); } public static IEnumerable<string> GetArguments (TextReader reader) { return GetArguments (reader, false); } // Cribbed from mcs/driver.cs:LoadArgs(string) static IEnumerable<string> GetArguments (TextReader reader, bool close) { try { StringBuilder arg = new StringBuilder (); string line; while ((line = reader.ReadLine ()) != null) { int t = line.Length; for (int i = 0; i < t; i++) { char c = line [i]; if (c == '"' || c == '\'') { char end = c; for (i++; i < t; i++){ c = line [i]; if (c == end) break; arg.Append (c); } } else if (c == ' ') { if (arg.Length > 0) { yield return arg.ToString (); arg.Length = 0; } } else arg.Append (c); } if (arg.Length > 0) { yield return arg.ToString (); arg.Length = 0; } } } finally { if (close) reader.Close (); } } } public class ResponseFileSource : ArgumentSource { public override string[] GetNames () { return new string[]{"@file"}; } public override string Description { get {return "Read response file for more options.";} } public override bool GetArguments (string value, out IEnumerable<string> replacement) { if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) { replacement = null; return false; } replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1)); return true; } } [Serializable] public class OptionException : Exception { private string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } public string OptionName { get {return this.option;} } [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet () : this (delegate (string f) {return f;}) { } public OptionSet (Converter<string, string> localizer) { this.localizer = localizer; this.roSources = new ReadOnlyCollection<ArgumentSource>(sources); } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get {return localizer;} } List<ArgumentSource> sources = new List<ArgumentSource> (); ReadOnlyCollection<ArgumentSource> roSources; public ReadOnlyCollection<ArgumentSource> ArgumentSources { get {return roSources;} } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException ("option"); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException ("option"); try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { Option p = Items [index]; base.RemoveItem (index); // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException ("option"); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } public OptionSet Add (ArgumentSource source) { if (source == null) throw new ArgumentNullException ("source"); sources.Add (source); return this; } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } public List<string> Parse (IEnumerable<string> arguments) { if (arguments == null) throw new ArgumentNullException ("arguments"); OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; ArgumentEnumerator ae = new ArgumentEnumerator (arguments); foreach (string argument in ae) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (AddSource (ae, argument)) continue; if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } class ArgumentEnumerator : IEnumerable<string> { List<IEnumerator<string>> sources = new List<IEnumerator<string>> (); public ArgumentEnumerator (IEnumerable<string> arguments) { sources.Add (arguments.GetEnumerator ()); } public void Add (IEnumerable<string> arguments) { sources.Add (arguments.GetEnumerator ()); } public IEnumerator<string> GetEnumerator () { do { IEnumerator<string> c = sources [sources.Count-1]; if (c.MoveNext ()) yield return c.Current; else { c.Dispose (); sources.RemoveAt (sources.Count-1); } } while (sources.Count > 0); } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } } bool AddSource (ArgumentEnumerator ae, string argument) { foreach (ArgumentSource source in sources) { IEnumerable<string> replacement; if (!source.GetArguments (argument, out replacement)) continue; ae.Add (replacement); return true; } return false; } private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly Regex ValueOption = new Regex ( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException ("argument"); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue (f, string.Concat (n + s + v), c)) return true; return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke (c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring (i+1); c.Option = p; c.OptionName = opt; ParseValue (v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 29; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } bool indent = false; string prefix = new string (' ', OptionWidth+2); foreach (string line in GetLines (localizer (GetDescription (p.Description)))) { if (indent) o.Write (prefix); o.WriteLine (line); indent = true; } } foreach (ArgumentSource s in sources) { string[] names = s.GetNames (); if (names == null || names.Length == 0) continue; int written = 0; Write (o, ref written, " "); Write (o, ref written, names [0]); for (int i = 1; i < names.Length; ++i) { Write (o, ref written, ", "); Write (o, ref written, names [i]); } if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } bool indent = false; string prefix = new string (' ', OptionWidth+2); foreach (string line in GetLines (localizer (GetDescription (s.Description)))) { if (indent) o.Write (prefix); o.WriteLine (line); indent = true; } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("[")); } Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static IEnumerable<string> GetLines (string description) { return StringCoda.WrappedLines (description, 80 - OptionWidth, 80 - OptionWidth - 2); } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_304 : MapLoop { public M_304() : base(null) { Content.AddRange(new MapBaseEntity[] { new B2() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new B2A() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new Y6() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new G1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new G2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new G3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new V1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new V3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new M0() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_M1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new M2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new C2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new L_R4(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new R2A() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new R2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 13 }, new K1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new L11() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 }, new H3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 }, new L5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new X1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new X2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new L_C8(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new L_L3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_M1 : MapLoop { public L_M1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new M1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, }); } } //3000 public class L_R4 : MapLoop { public L_R4(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new R4() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 }, }); } } //4000 public class L_C8 : MapLoop { public L_C8(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new C8() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new C8C() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new SUP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //5000 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new Y2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_N7(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new L11() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new K1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_PO4(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new L_L0(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 120 }, }); } } //5100 public class L_N7 : MapLoop { public L_N7(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N7() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N12() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new M7() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new M7A() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new W09() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LH6() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 }, new L_L1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L7() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new X1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new X2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new L_H1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_LH1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, }); } } //5110 public class L_L1 : MapLoop { public L_L1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //5120 public class L_H1 : MapLoop { public L_H1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new H1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new H2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //5130 public class L_LH1 : MapLoop { public L_LH1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LH1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LH2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 4 }, new LH3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new LFH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new LEP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new LH4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LHT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new LHR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //5200 public class L_PO4 : MapLoop { public L_PO4(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PO4() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //5300 public class L_L0 : MapLoop { public L_L0(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L0() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_PO4_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new L4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LH6() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 }, new L_PAL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new L_CTP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L12() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_L1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L7() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_SAC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_L9(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new X1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new X2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new L_C8_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L_H1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_LH1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //5310 public class L_PO4_1 : MapLoop { public L_PO4_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PO4() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //5320 public class L_PAL : MapLoop { public L_PAL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PAL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //5330 public class L_CTP : MapLoop { public L_CTP(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CTP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //5340 public class L_L1_1 : MapLoop { public L_L1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //5350 public class L_SAC : MapLoop { public L_SAC(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //5360 public class L_L9 : MapLoop { public L_L9(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //5370 public class L_C8_1 : MapLoop { public L_C8_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new C8() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new C8C() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new SUP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //5380 public class L_H1_1 : MapLoop { public L_H1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new H1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new H2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //5390 public class L_LH1_1 : MapLoop { public L_LH1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LH1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LH2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 4 }, new LH3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new LFH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new LEP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new LH4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LHT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new LHR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //5395 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, }); } } //6000 public class L_L3 : MapLoop { public L_L3(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L3() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 }, new SUP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new L_L1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L_TDS(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_SAC_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_L9_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new ISS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new V9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new K1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new L11() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 24 }, }); } } //6100 public class L_L1_2 : MapLoop { public L_L1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6200 public class L_TDS : MapLoop { public L_TDS(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TDS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6300 public class L_SAC_1 : MapLoop { public L_SAC_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6400 public class L_L9_1 : MapLoop { public L_L9_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new L9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Linq.Expressions; using System.Net.Http; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using CoreFoundation; using Foundation; using UIKit; using Xamarin.Forms.Internals; using Xamarin.Forms.Platform.iOS; namespace Xamarin.Forms { public static class Forms { //Preserve GetCallingAssembly static readonly bool nevertrue = false; static bool? s_isiOS9OrNewer; static Forms() { if (nevertrue) Assembly.GetCallingAssembly(); } public static bool IsInitialized { get; private set; } internal static bool IsiOS9OrNewer { get { if (!s_isiOS9OrNewer.HasValue) s_isiOS9OrNewer = UIDevice.CurrentDevice.CheckSystemVersion(9, 0); return s_isiOS9OrNewer.Value; } } public static void Init() { if (IsInitialized) return; IsInitialized = true; Color.Accent = Color.FromRgba(50, 79, 133, 255); Log.Listeners.Add(new DelegateLogListener((c, m) => Trace.WriteLine(m, c))); Device.PlatformServices = new IOSPlatformServices(); Device.Info = new IOSDeviceInfo(); Registrar.RegisterAll(new[] { typeof(ExportRendererAttribute), typeof(ExportCellAttribute), typeof(ExportImageSourceHandlerAttribute) }); Device.Idiom = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? TargetIdiom.Tablet : TargetIdiom.Phone; ExpressionSearch.Default = new iOSExpressionSearch(); } public static event EventHandler<ViewInitializedEventArgs> ViewInitialized; internal static void SendViewInitialized(this VisualElement self, UIView nativeView) { ViewInitialized?.Invoke(self, new ViewInitializedEventArgs { View = self, NativeView = nativeView }); } class iOSExpressionSearch : ExpressionVisitor, IExpressionSearch { List<object> _results; Type _targetType; public List<T> FindObjects<T>(Expression expression) where T : class { _results = new List<object>(); _targetType = typeof(T); Visit(expression); return _results.Select(o => o as T).ToList(); } protected override Expression VisitMember(MemberExpression node) { if (node.Expression is ConstantExpression && node.Member is FieldInfo) { var container = ((ConstantExpression)node.Expression).Value; var value = ((FieldInfo)node.Member).GetValue(container); if (_targetType.IsInstanceOfType(value)) _results.Add(value); } return base.VisitMember(node); } } internal class IOSDeviceInfo : DeviceInfo { readonly NSObject _notification; readonly Size _scaledScreenSize; readonly double _scalingFactor; public IOSDeviceInfo() { _notification = UIDevice.Notifications.ObserveOrientationDidChange((sender, args) => CurrentOrientation = UIDevice.CurrentDevice.Orientation.ToDeviceOrientation()); _scalingFactor = UIScreen.MainScreen.Scale; _scaledScreenSize = new Size(UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height); PixelScreenSize = new Size(_scaledScreenSize.Width * _scalingFactor, _scaledScreenSize.Height * _scalingFactor); } public override Size PixelScreenSize { get; } public override Size ScaledScreenSize => _scaledScreenSize; public override double ScalingFactor => _scalingFactor; protected override void Dispose(bool disposing) { _notification.Dispose(); base.Dispose(disposing); } } class IOSPlatformServices : IPlatformServices { static readonly MD5CryptoServiceProvider s_checksum = new MD5CryptoServiceProvider(); public void BeginInvokeOnMainThread(Action action) { NSRunLoop.Main.BeginInvokeOnMainThread(action.Invoke); } public Ticker CreateTicker() { return new CADisplayLinkTicker(); } public Assembly[] GetAssemblies() { return AppDomain.CurrentDomain.GetAssemblies(); } public string GetMD5Hash(string input) { var bytes = s_checksum.ComputeHash(Encoding.UTF8.GetBytes(input)); var ret = new char[32]; for (var i = 0; i < 16; i++) { ret[i * 2] = (char)Hex(bytes[i] >> 4); ret[i * 2 + 1] = (char)Hex(bytes[i] & 0xf); } return new string(ret); } public double GetNamedSize(NamedSize size, Type targetElementType, bool useOldSizes) { // We make these up anyway, so new sizes didn't really change // iOS docs say default button font size is 15, default label font size is 17 so we use those as the defaults. switch (size) { case NamedSize.Default: return typeof(Button).IsAssignableFrom(targetElementType) ? 15 : 17; case NamedSize.Micro: return 12; case NamedSize.Small: return 14; case NamedSize.Medium: return 17; case NamedSize.Large: return 22; default: throw new ArgumentOutOfRangeException("size"); } } public async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken) { using (var client = GetHttpClient()) using (var response = await client.GetAsync(uri, cancellationToken)) { if (!response.IsSuccessStatusCode) { Log.Warning("HTTP Request", $"Could not retrieve {uri}, status code {response.StatusCode}"); return null; } return await response.Content.ReadAsStreamAsync(); } } public IIsolatedStorageFile GetUserStoreForApplication() { return new _IsolatedStorageFile(IsolatedStorageFile.GetUserStoreForApplication()); } public bool IsInvokeRequired => !NSThread.IsMain; public string RuntimePlatform => Device.iOS; public void OpenUriAction(Uri uri) { UIApplication.SharedApplication.OpenUrl(new NSUrl(uri.AbsoluteUri)); } public void StartTimer(TimeSpan interval, Func<bool> callback) { NSTimer timer = NSTimer.CreateRepeatingTimer(interval, t => { if (!callback()) t.Invalidate(); }); NSRunLoop.Main.AddTimer(timer, NSRunLoopMode.Common); } HttpClient GetHttpClient() { var proxy = CFNetwork.GetSystemProxySettings(); var handler = new HttpClientHandler(); if (!string.IsNullOrEmpty(proxy.HTTPProxy)) { handler.Proxy = CFNetwork.GetDefaultProxy(); handler.UseProxy = true; } return new HttpClient(handler); } static int Hex(int v) { if (v < 10) return '0' + v; return 'a' + v - 10; } public class _IsolatedStorageFile : IIsolatedStorageFile { readonly IsolatedStorageFile _isolatedStorageFile; public _IsolatedStorageFile(IsolatedStorageFile isolatedStorageFile) { _isolatedStorageFile = isolatedStorageFile; } public Task CreateDirectoryAsync(string path) { _isolatedStorageFile.CreateDirectory(path); return Task.FromResult(true); } public Task<bool> GetDirectoryExistsAsync(string path) { return Task.FromResult(_isolatedStorageFile.DirectoryExists(path)); } public Task<bool> GetFileExistsAsync(string path) { return Task.FromResult(_isolatedStorageFile.FileExists(path)); } public Task<DateTimeOffset> GetLastWriteTimeAsync(string path) { return Task.FromResult(_isolatedStorageFile.GetLastWriteTime(path)); } public Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access) { Stream stream = _isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access); return Task.FromResult(stream); } public Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access, FileShare share) { Stream stream = _isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share); return Task.FromResult(stream); } } } } }
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Collections.Generic; using InControl.ReorderableList.Internal; namespace InControl.ReorderableList { /// <summary> /// Utility class for drawing reorderable lists. /// </summary> public static class ReorderableListGUI { /// <summary> /// Default list item height is 18 pixels. /// </summary> public const float DefaultItemHeight = 18; /// <summary> /// Gets or sets zero-based index of last item which was changed. A value of -1 /// indicates that no item was changed by list. /// </summary> /// <remarks> /// <para>This property should not be set when items are added or removed.</para> /// </remarks> public static int indexOfChangedItem { get; internal set; } /// <summary> /// Gets zero-based index of list item which is currently being drawn; /// or a value of -1 if no item is currently being drawn. /// </summary> public static int currentItemIndex { get { return ReorderableListControl.currentItemIndex; } } #region Basic Item Drawers /// <summary> /// Default list item drawer implementation. /// </summary> /// <remarks> /// <para>Always presents the label "Item drawer not implemented.".</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Unmodified value of list item. /// </returns> /// <typeparam name="T">Type of list item.</typeparam> public static T DefaultItemDrawer<T>( Rect position, T item ) { GUI.Label( position, "Item drawer not implemented." ); return item; } /// <summary> /// Draws text field allowing list items to be edited. /// </summary> /// <remarks> /// <para>Null values are automatically changed to empty strings since null /// values cannot be edited using a text field.</para> /// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item /// is modified.</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Modified value of list item. /// </returns> public static string TextFieldItemDrawer( Rect position, string item ) { if (item == null) { item = ""; GUI.changed = true; } return EditorGUI.TextField( position, item ); } #endregion /// <summary> /// Gets the default list control implementation. /// </summary> private static ReorderableListControl defaultListControl { get; set; } static ReorderableListGUI() { InitStyles(); defaultListControl = new ReorderableListControl(); // Duplicate default styles to prevent user scripts from interferring with // the default list control instance. defaultListControl.containerStyle = new GUIStyle( defaultContainerStyle ); defaultListControl.addButtonStyle = new GUIStyle( defaultAddButtonStyle ); defaultListControl.removeButtonStyle = new GUIStyle( defaultRemoveButtonStyle ); indexOfChangedItem = -1; } #region Custom Styles /// <summary> /// Gets default style for title header. /// </summary> public static GUIStyle defaultTitleStyle { get; private set; } /// <summary> /// Gets default style for background of list control. /// </summary> public static GUIStyle defaultContainerStyle { get; private set; } /// <summary> /// Gets default style for add item button. /// </summary> public static GUIStyle defaultAddButtonStyle { get; private set; } /// <summary> /// Gets default style for remove item button. /// </summary> public static GUIStyle defaultRemoveButtonStyle { get; private set; } private static void InitStyles() { defaultTitleStyle = new GUIStyle(); defaultTitleStyle.border = new RectOffset( 2, 2, 2, 1 ); defaultTitleStyle.margin = new RectOffset( 5, 5, 5, 0 ); defaultTitleStyle.padding = new RectOffset( 5, 5, 0, 0 ); defaultTitleStyle.alignment = TextAnchor.MiddleLeft; defaultTitleStyle.normal.background = ReorderableListResources.texTitleBackground; defaultTitleStyle.normal.textColor = EditorGUIUtility.isProSkin ? new Color( 0.8f, 0.8f, 0.8f ) : new Color( 0.2f, 0.2f, 0.2f ); defaultContainerStyle = new GUIStyle(); defaultContainerStyle.border = new RectOffset( 2, 2, 1, 2 ); defaultContainerStyle.margin = new RectOffset( 5, 5, 5, 5 ); defaultContainerStyle.padding = new RectOffset( 1, 1, 2, 2 ); defaultContainerStyle.normal.background = ReorderableListResources.texContainerBackground; defaultAddButtonStyle = new GUIStyle(); defaultAddButtonStyle.fixedWidth = 30; defaultAddButtonStyle.fixedHeight = 16; defaultAddButtonStyle.normal.background = ReorderableListResources.texAddButton; defaultAddButtonStyle.active.background = ReorderableListResources.texAddButtonActive; defaultRemoveButtonStyle = new GUIStyle(); defaultRemoveButtonStyle.fixedWidth = 27; defaultRemoveButtonStyle.active.background = ReorderableListResources.CreatePixelTexture( "Dark Pixel (List GUI)", new Color32( 18, 18, 18, 255 ) ); defaultRemoveButtonStyle.imagePosition = ImagePosition.ImageOnly; defaultRemoveButtonStyle.alignment = TextAnchor.MiddleCenter; } #endregion private static GUIContent s_Temp = new GUIContent(); #region Title Control /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Content for title control.</param> public static void Title( GUIContent title ) { Rect position = GUILayoutUtility.GetRect( title, defaultTitleStyle ); position.height += 6; Title( position, title ); } /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title("Your Title"); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title('Your Title'); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Text for title control.</param> public static void Title( string title ) { s_Temp.text = title; Title( s_Temp ); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="title">Content for title control.</param> public static void Title( Rect position, GUIContent title ) { if (Event.current.type == EventType.Repaint) defaultTitleStyle.Draw( position, title, false, false, false, false ); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="text">Text for title control.</param> public static void Title( Rect position, string text ) { s_Temp.text = text; Title( position, s_Temp ); } #endregion #region List<T> Control /// <summary> /// Draw list field control. /// </summary> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags ) { var adaptor = new GenericListAdaptor<T>( list, drawItem, itemHeight ); ReorderableListControl.DrawControlFromState( adaptor, drawEmpty, flags ); } /// <summary> /// Draw list field control with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags ) { var adaptor = new GenericListAdaptor<T>( list, drawItem, itemHeight ); ReorderableListControl.DrawControlFromState( position, adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, drawEmpty, itemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, itemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight ) { DoListField<T>( list, drawItem, drawEmpty, itemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, itemHeight, 0 ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, drawEmpty, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField<T>( list, drawItem, drawEmpty, DefaultItemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, DefaultItemHeight, 0 ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, null, itemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, null, itemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight ) { DoListField<T>( list, drawItem, null, itemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight ) { DoListFieldAbsolute<T>( position, list, drawItem, null, itemHeight, 0 ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, null, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, null, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem ) { DoListField<T>( list, drawItem, null, DefaultItemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem ) { DoListFieldAbsolute<T>( position, list, drawItem, null, DefaultItemHeight, 0 ); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="itemCount">Count of items in list.</param> /// <param name="itemHeight">Fixed height of list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight( int itemCount, float itemHeight, ReorderableListFlags flags ) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight( itemCount, itemHeight ); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight( int itemCount, ReorderableListFlags flags ) { return CalculateListFieldHeight( itemCount, DefaultItemHeight, flags ); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight( int itemCount, float itemHeight ) { return CalculateListFieldHeight( itemCount, itemHeight, 0 ); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight( int itemCount ) { return CalculateListFieldHeight( itemCount, DefaultItemHeight, 0 ); } #endregion #region SerializedProperty Control /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { var adaptor = new SerializedPropertyAdaptor( arrayProperty, fixedItemHeight ); ReorderableListControl.DrawControlFromState( adaptor, drawEmpty, flags ); } /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="position">Position of control.</param> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { var adaptor = new SerializedPropertyAdaptor( arrayProperty, fixedItemHeight ); ReorderableListControl.DrawControlFromState( position, adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField( arrayProperty, 0, drawEmpty, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, 0, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( arrayProperty, 0, drawEmpty, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, arrayProperty, 0, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, ReorderableListFlags flags ) { DoListField( arrayProperty, 0, null, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, 0, null, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty ) { DoListField( arrayProperty, 0, null, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty ) { DoListFieldAbsolute( position, arrayProperty, 0, null, 0 ); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight( SerializedProperty arrayProperty, ReorderableListFlags flags ) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight( new SerializedPropertyAdaptor( arrayProperty ) ); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/> public static float CalculateListFieldHeight( SerializedProperty arrayProperty ) { return CalculateListFieldHeight( arrayProperty, 0 ); } #endregion #region SerializedProperty Control (Fixed Item Height) /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField( arrayProperty, fixedItemHeight, drawEmpty, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( arrayProperty, fixedItemHeight, drawEmpty, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags ) { DoListField( arrayProperty, fixedItemHeight, null, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, null, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight ) { DoListField( arrayProperty, fixedItemHeight, null, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, null, 0 ); } #endregion #region Adaptor Control /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { ReorderableListControl.DrawControlFromState( adaptor, drawEmpty, flags ); } private static void DoListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( adaptor, drawEmpty, 0 ); } /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="position">Position of control.</param> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { ReorderableListControl.DrawControlFromState( position, adaptor, drawEmpty, flags ); } private static void DoListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, adaptor, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField( adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( adaptor, drawEmpty, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, adaptor, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor, ReorderableListFlags flags ) { DoListField( adaptor, null, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags ) { DoListFieldAbsolute( position, adaptor, null, flags ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor ) { DoListField( adaptor, null, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor ) { DoListFieldAbsolute( position, adaptor, null, 0 ); } /// <summary> /// Calculate height of list field for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight( IReorderableListAdaptor adaptor, ReorderableListFlags flags ) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight( adaptor ); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/> public static float CalculateListFieldHeight( IReorderableListAdaptor adaptor ) { return CalculateListFieldHeight( adaptor, 0 ); } #endregion } } #endif
using System; using System.Collections.Generic; using SchemeCore.objects; using SchemeCore; using SchemeCore.helper; using SchemeCore.builtin; using System.Diagnostics; namespace SchemeCore { public class SchemeEvaluator { public ISchemeEnvironment environment { get{return currentEnvironment;} } private SchemeEnvironmentRoot root; public SchemeEvaluator() { root = SchemeEnvironmentRoot.instance; //instanciate the builtin Functions: root.set(new SchemeSymbol("+"), new SchemeBuiltInPlus()); root.set(new SchemeSymbol("define"), new SchemeBuitInDefine()); root.set(new SchemeSymbol("lambda"), new SchemeBuiltInLambda()); root.set(new SchemeSymbol("="), new SchemeBuiltinEquals()); root.set(new SchemeSymbol("if"), new SchemeBuiltInIf()); root.set(new SchemeSymbol("modulo"), new ScehemBuiltinModulo()); root.set(new SchemeSymbol("cons"), new SchemeBuiltinCons()); root.set(new SchemeSymbol("cdr"), new SchemeBuiltinCdr()); root.set(new SchemeSymbol("car"), new SchemeBuiltinCar()); root.set(new SchemeSymbol(">"), new SchemeBuiltinGreaterThan()); root.set(new SchemeSymbol(">="), new SchemeBuiltinGreaterThanEqual()); root.set(new SchemeSymbol("<"), new SchemeBuiltinLessThan()); root.set(new SchemeSymbol("<="), new SchemeBuiltinLessThanEquals()); root.set(new SchemeSymbol("and"), new SchemeBuiltinAnd()); root.set(new SchemeSymbol("or"), new SchemeBuiltinOr()); } public void loadSchemeLibrary(string path) { System.IO.StreamReader file = new System.IO.StreamReader(path); string libraryString = file.ReadToEnd(); file.Close(); var reader = new SchemeReader(); var ast = reader.parseString(libraryString); evaluate(ast); } public List<SchemeObject> evaluate(SchemeAST AST) { if (currentEnvironment == null) { currentEnvironment = root; } return evaluate(ref AST); } internal ISchemeEnvironment currentEnvironment { get; set; } // this is necessary because the ref keyword does not allow polymorphism internal List<SchemeObject> evaluate(ref SchemeAST currentAST) { var returnValue = new List<SchemeObject>(); if (currentAST.currentObject == SchemeVoid.instance) { for (int i = 0; i < currentAST.children.Count; i++) { var ast = (SchemeAST)currentAST.children[i]; int instructionCount = 0; while (true) { Logger.writeLine(String.Format("Instruction: {0}", instructionCount++)); if (Logger.enableConsoleLog || Logger.enableLogfile) { ast.createTreeOutput(); } if (updateToNextLevelChild(ref ast, this.currentEnvironment)) //this updates currentAST until the first AST object is found which contains leaf objects only { continue; } var evaluated = evaluateSchemeAST(ref ast, this.currentEnvironment); //evaluate the expression if (evaluated == null) { continue; } updateParent(ref ast, evaluated); //replace currentAST with result if (ast.parent.currentObject != SchemeVoid.instance) { ast = ast.parent; //ascend the tree again } else { returnValue.Add(evaluated); break; } } } } return returnValue; } private bool updateToNextLevelChild(ref SchemeAST currentAst, ISchemeEnvironment environment) { Type type = currentAst.currentObject.GetType(); if (type == typeof(SchemeSymbol)) { SchemeType t = environment.get((SchemeSymbol)currentAst.currentObject); if (t == null) { throw new SchemeUndefinedSymbolException(String.Format("Undefined Symbol: {0}", currentAst.currentObject.ToString()), currentAst.fileName, currentAst.sourceLength, currentAst.sourceOffset); } Type obj = t.GetType(); if (obj == typeof(SchemeBuiltInLambda)) // or typeof if. this is needed for parts which should not be evaluated. { return false; } if (obj == typeof(SchemeBuiltInIf)) { var tmpRoot = new SchemeAST(); var condition = currentAst.children[0]; var oldParent = condition.parent; tmpRoot.children.Add(condition); condition.parent = tmpRoot; var evaluated = evaluate(ref tmpRoot); //evaluate the if condition tmpRoot = new SchemeAST(currentAst, evaluated[0]); currentAst.children[0] = tmpRoot; return false; } } foreach (SchemeAST child in currentAst.children) { if (child.children.Count != 0) { currentAst = child; return true; } } return false; } private void updateParent(ref SchemeAST currentAST, SchemeObject newValue) { /* if (currentAST.currentObject.GetType() == typeof(SchemeLambda)) { // foreach (SchemeType obj in currrentEn ) foreach (string key in currentEnvironment.getDict().Keys) { currentEnvironment.parent().set(new SchemeSymbol(key), currentEnvironment.getDict()[key]); } } */ if (currentAST.hasOwnEnviornment)// && currentEnvironment.parent() != null ) { /* if (newValue is SchemeLambda) { foreach (string key in currentEnvironment.getDict().Keys) { currentEnvironment.parent().set(new SchemeSymbol(key), currentEnvironment.getDict()[key]); } } */ currentEnvironment = currentEnvironment.parent(); } int postition = currentAST.parent.children.IndexOf(currentAST); currentAST.parent.children.Remove(currentAST); // if( newValue != SchemeVoid.instance ) // { var returnValue = new SchemeAST(currentAST.parent, newValue); currentAST.parent.children.Insert(postition, returnValue); // } } private SchemeObject evaluateSchemeAST(ref SchemeAST ast, ISchemeEnvironment environment) { var func = getFunction(ref ast, environment); if (func != null) { return func.evaluate(ref ast, this); } else { var type = getType(ref ast, environment); if (type != null) { return type; } else { throw new SchemeNoSuchMethodException(String.Format("{0} is no valid Scheme Method!", ast.currentObject.ToString())); } } } private ISchemeFunction getFunction(ref SchemeAST ast, ISchemeEnvironment environment) { SchemeObject ret = ast.currentObject; if (ast.currentObject.GetType() == typeof(SchemeSymbol)) { ret = environment.get((SchemeSymbol)ret); } if (!(ret is ISchemeFunction)) { return null; } return (ISchemeFunction)ret; } private SchemeType getType(ref SchemeAST ast, ISchemeEnvironment environment) { SchemeObject ret = ast.currentObject; if (ast.currentObject.GetType() == typeof(SchemeSymbol)) { ret = environment.get((SchemeSymbol)ret); } if (!(ret is SchemeType)) { return null; } return (SchemeType)ret; } } }
using Mvp.Xml.Common.XPath; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; namespace InnovatorAdmin { public static class XmlUtils { public static string RemoveComments(string xml) { if (string.IsNullOrEmpty(xml)) { return ""; } try { using (var reader = new StringReader(xml)) using (var xReader = XmlReader.Create(reader, new XmlReaderSettings() { IgnoreComments = true })) { var doc = new XmlDocument(); doc.Load(xReader); return doc.OuterXml; } } catch (XmlException) { return xml; } } public static XmlDocument NewDoc(this XmlNode node) { var doc = (node as XmlDocument) ?? node.OwnerDocument; return new XmlDocument(doc == null ? new NameTable() : doc.NameTable); } public static IEnumerable<XmlElement> RootItems(XmlElement elem) { var curr = elem; while (curr != null && curr.LocalName != "Item") curr = curr.ChildNodes.OfType<XmlElement>().FirstOrDefault(); if (curr?.LocalName == "Item" && curr.ParentNode != null) { foreach (var item in curr.ParentNode.Elements("Item")) yield return item; } else if ((curr ?? elem)?.LocalName == "Item") { yield return curr ?? elem; } } public static XmlElement Elem(this XmlNode node, string localName) { if (node == null) return null; var doc = node as XmlDocument; var newElem = (doc ?? node.OwnerDocument).CreateElement(localName); node.AppendChild(newElem); return newElem; } public static void Elem(this XmlNode node, string localName, string value) { if (node == null) return; node.Elem(localName).AppendChild(node.OwnerDocument.CreateTextNode(value)); } public static string Attribute(this XmlNode elem, string localName, string defaultValue = null) { if (elem == null || elem.Attributes == null) return defaultValue; var attr = elem.Attributes[localName]; if (attr == null) { return defaultValue; } else { return attr.Value; } } public static XmlElement Attr(this XmlElement elem, string localName, string value) { if (elem == null) return elem; elem.SetAttribute(localName, value); return elem; } public static void Detach(this XmlNode node) { if (node != null && node.ParentNode != null) { var attr = node as XmlAttribute; if (attr == null) { node.ParentNode.RemoveChild(node); } else { ((XmlElement)node.ParentNode).RemoveAttributeNode(attr); } } } public static XmlElement Element(this XmlNode node, string localName) { if (node == null) return null; return node.ChildNodes.OfType<XmlElement>().SingleOrDefault(e => e.LocalName == localName); } public static string Element(this XmlNode node, string localName, string defaultValue) { if (node == null) return defaultValue; var elem = node.Element(localName); if (elem == null) return defaultValue; return elem.InnerText; } public static XmlElement Element(this IEnumerable<XmlElement> nodes, string localName) { if (nodes == null) return null; return nodes.SelectMany(n => n.ChildNodes.OfType<XmlElement>()).SingleOrDefault(e => e.LocalName == localName); } public static void VisitDescendantsAndSelf(this XmlNode node, Action<XmlElement> action) { var elem = node as XmlElement; if (elem != null) action.Invoke(elem); ElementRecursion(node, action); } private static void ElementRecursion(XmlNode node, Action<XmlElement> action) { foreach (var elem in node.Elements()) { action.Invoke(elem); ElementRecursion(elem, action); } } public static IEnumerable<XmlElement> Descendants(this XmlNode node, Func<XmlElement, bool> predicate) { var results = new List<XmlElement>(); ElementQuery(node, results, predicate); return results; } public static IEnumerable<XmlElement> DescendantsAndSelf(this XmlNode node, Func<XmlElement, bool> predicate) { var results = new List<XmlElement>(); if (predicate.Invoke((XmlElement)node)) results.Add((XmlElement)node); ElementQuery(node, results, predicate); return results; } private static void ElementQuery(XmlNode node, List<XmlElement> results, Func<XmlElement, bool> predicate) { foreach (var elem in node.Elements()) { if (predicate.Invoke(elem)) results.Add(elem); ElementQuery(elem, results, predicate); } } public static IEnumerable<XmlElement> Elements(this XmlNode node) { return node.ChildNodes.OfType<XmlElement>(); } public static IEnumerable<XmlElement> Elements(this XmlNode node, string localName) { return node.ChildNodes.OfType<XmlElement>().Where(e => e.LocalName == localName); } public static IEnumerable<XmlElement> Elements(this XmlNode node, Func<XmlElement, bool> predicate) { return node.ChildNodes.OfType<XmlElement>().Where(predicate); } public static IEnumerable<XmlElement> Elements(this IEnumerable<XmlElement> nodes, Func<XmlElement, bool> predicate) { return nodes.SelectMany(n => n.ChildNodes.OfType<XmlElement>()).Where(predicate); } public static IEnumerable<XmlElement> Elements(this IEnumerable<XmlElement> nodes, string localName) { return nodes.SelectMany(n => n.ChildNodes.OfType<XmlElement>()).Where(e => e.LocalName == localName); } public static IEnumerable<XmlElement> ElementsByXPath(this XmlNode node, string xPath) { return XPathCache.SelectNodes(xPath, node).OfType<XmlElement>(); } public static IEnumerable<XmlElement> ElementsByXPath(this XmlNode node, string xPath, params object[] vars) { return XPathCache.SelectNodes(xPath, node, vars.Select((v, i) => new XPathVariable("p" + i.ToString(), v)).ToArray()) .OfType<XmlElement>(); } public static bool HasValue(this XmlNode node) { return node != null && (node.Elements().Any() || !string.IsNullOrEmpty(node.InnerText)); } public static IEnumerable<XmlNode> XPath(this XmlNode node, string xPath) { return XPathCache.SelectNodes(xPath, node).OfType<XmlNode>(); } public static IEnumerable<XmlNode> XPath(this XmlNode node, string xPath, params object[] vars) { return XPathCache.SelectNodes(xPath, node, vars.Select((v, i) => new XPathVariable("p" + i.ToString(), v)).ToArray()) .OfType<XmlNode>(); } public static XmlNode Parent(this XmlNode node) { if (node == null) return null; return node.ParentNode; } public static IEnumerable<XmlElement> Parents(this XmlNode node) { if (node == null) yield break; var parent = node.ParentNode as XmlElement; while (parent != null) { yield return parent; parent = parent.ParentNode as XmlElement; } } public static XmlDocument DocFromXml(string xml) { var result = new XmlDocument(); result.LoadXml(xml); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information // // XmlDsigXsltTransformTest.cs - Test Cases for XmlDsigXsltTransform // // Author: // Sebastien Pouliot <sebastien@ximian.com> // Atsushi Enomoto <atsushi@ximian.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2004 Novell (http://www.novell.com) // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.Collections; using System.IO; using System.Text; using System.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigXsltTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigXsltTransform : XmlDsigXsltTransform { public UnprotectedXmlDsigXsltTransform() { } public UnprotectedXmlDsigXsltTransform(bool includeComments) : base(includeComments) { } public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigXsltTransformTest { protected UnprotectedXmlDsigXsltTransform transform; public XmlDsigXsltTransformTest() { transform = new UnprotectedXmlDsigXsltTransform(); } [Fact] // ctor () public void Constructor1() { CheckProperties(transform); } [Fact] // ctor (Boolean) public void Constructor2() { transform = new UnprotectedXmlDsigXsltTransform(true); CheckProperties(transform); transform = new UnprotectedXmlDsigXsltTransform(false); CheckProperties(transform); } void CheckProperties(XmlDsigXsltTransform transform) { Assert.Equal("http://www.w3.org/TR/1999/REC-xslt-19991116", transform.Algorithm); Type[] input = transform.InputTypes; Assert.True((input.Length == 3), "Input #"); // check presence of every supported input types bool istream = false; bool ixmldoc = false; bool ixmlnl = false; foreach (Type t in input) { if (t.ToString() == "System.IO.Stream") istream = true; if (t.ToString() == "System.Xml.XmlDocument") ixmldoc = true; if (t.ToString() == "System.Xml.XmlNodeList") ixmlnl = true; } Assert.True(istream, "Input Stream"); Assert.True(ixmldoc, "Input XmlDocument"); Assert.True(ixmlnl, "Input XmlNodeList"); Type[] output = transform.OutputTypes; Assert.True((output.Length == 1), "Output #"); // check presence of every supported output types bool ostream = false; foreach (Type t in output) { if (t.ToString() == "System.IO.Stream") ostream = true; } Assert.True(ostream, "Output Stream"); } [Fact] public void GetInnerXml() { XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } private string Stream2Array(Stream s) { StringBuilder sb = new StringBuilder(); int b = s.ReadByte(); while (b != -1) { sb.Append(b.ToString("X2")); b = s.ReadByte(); } return sb.ToString(); } [Fact] public void EmptyXslt() { string test = "<Test>XmlDsigXsltTransform</Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInput(doc.ChildNodes); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Assert.Throws<ArgumentNullException>(() => transform.GetOutput()); } } [Fact] // Note that this is _valid_ as an "embedded stylesheet". // (see XSLT spec 2.7) public void EmbeddedStylesheet() { string test = "<Test xsl:version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>XmlDsigXsltTransform</Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInnerXml(doc.ChildNodes); transform.LoadInput(doc); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); } } [Fact] public void InvalidXslt() { bool result = false; try { string test = "<xsl:element name='foo' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>XmlDsigXsltTransform</xsl:element>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInnerXml(doc.ChildNodes); Stream s = (Stream)transform.GetOutput(); } catch (Exception e) { // we must deal with an internal exception result = (e.GetType().ToString().EndsWith("XsltLoadException")); result = true; } finally { Assert.True(result, "Exception not thrown"); } } [Fact] public void OnlyInner() { string test = "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns=\"http://www.w3.org/TR/xhtml1/strict\" version=\"1.0\">"; test += "<xsl:output encoding=\"UTF-8\" indent=\"no\" method=\"xml\" />"; test += "<xsl:template match=\"/\"><html><head><title>Notaries</title>"; test += "</head><body><table><xsl:for-each select=\"Notaries/Notary\">"; test += "<tr><th><xsl:value-of select=\"@name\" /></th></tr></xsl:for-each>"; test += "</table></body></html></xsl:template></xsl:stylesheet>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); transform.LoadInnerXml(doc.ChildNodes); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Assert.Throws<ArgumentNullException>(() => transform.GetOutput()); } } private XmlDocument GetXslDoc() { string test = "<Transform Algorithm=\"http://www.w3.org/TR/1999/REC-xslt-19991116\" xmlns='http://www.w3.org/2000/09/xmldsig#'>"; test += "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns=\"http://www.w3.org/TR/xhtml1/strict\" version=\"1.0\">"; test += "<xsl:output encoding=\"UTF-8\" indent=\"no\" method=\"xml\" />"; test += "<xsl:template match=\"/\"><html><head><title>Notaries</title>"; test += "</head><body><table><xsl:for-each select=\"Notaries/Notary\">"; test += "<tr><th><xsl:value-of select=\"@name\" /></th></tr></xsl:for-each>"; test += "</table></body></html></xsl:template></xsl:stylesheet></Transform>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); return doc; } [Fact] public void LoadInputAsXmlDocument() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); transform.LoadInput(doc); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } [Fact] public void LoadInputAsXmlNodeList() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); transform.LoadInput(doc.ChildNodes); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } [Fact] public void LoadInputAsStream() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; transform.LoadInput(ms); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } protected void AreEqual(string msg, XmlNodeList expected, XmlNodeList actual) { Assert.Equal(expected, actual); } [Fact] public void LoadInnerXml() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); AssertNodeListEqual(doc.DocumentElement.ChildNodes, xnl, "LoadInnerXml"); } void AssertNodeListEqual(XmlNodeList nl1, XmlNodeList nl2, string label) { Assert.Equal(nl1.Count, nl2.Count); IEnumerator e1, e2; int i; for (i = 0, e1 = nl1.GetEnumerator(), e2 = nl2.GetEnumerator(); e1.MoveNext(); i++) { Assert.True(e2.MoveNext(), label + " : nl2.MoveNext"); Assert.Equal(e1.Current, e2.Current); } Assert.False(e2.MoveNext(), label + " : nl2 has extras"); } [Fact] public void Load2() { XmlDocument doc = GetXslDoc(); transform.LoadInnerXml(doc.DocumentElement.ChildNodes); transform.LoadInput(doc); if (PlatformDetection.IsXmlDsigXsltTransformSupported) { Stream s = (Stream)transform.GetOutput(); string output = Stream2Array(s); } } [Fact] public void UnsupportedInput() { byte[] bad = { 0xBA, 0xD }; // input MUST be one of InputType - but no exception is thrown (not documented) transform.LoadInput(bad); } [Fact] public void UnsupportedOutput() { XmlDocument doc = new XmlDocument(); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType())); } } }
/** * 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 Fieldable = Lucene.Net.Documents.Fieldable; using IndexOutput = Lucene.Net.Store.IndexOutput; using Token = Lucene.Net.Analysis.Token; using UnicodeUtil = Lucene.Net.Util.UnicodeUtil; namespace Lucene.Net.Index { internal sealed class TermVectorsTermsWriterPerField : TermsHashConsumerPerField { internal readonly TermVectorsTermsWriterPerThread perThread; internal readonly TermsHashPerField termsHashPerField; internal readonly TermVectorsTermsWriter termsWriter; internal readonly FieldInfo fieldInfo; internal readonly DocumentsWriter.DocState docState; internal readonly DocInverter.FieldInvertState fieldState; internal bool doVectors; internal bool doVectorPositions; internal bool doVectorOffsets; internal int maxNumPostings; public TermVectorsTermsWriterPerField(TermsHashPerField termsHashPerField, TermVectorsTermsWriterPerThread perThread, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.perThread = perThread; this.termsWriter = perThread.termsWriter; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; } internal override int getStreamCount() { return 2; } internal override bool start(Fieldable[] fields, int count) { doVectors = false; doVectorPositions = false; doVectorOffsets = false; for (int i = 0; i < count; i++) { Fieldable field = fields[i]; if (field.IsIndexed() && field.IsTermVectorStored()) { doVectors = true; doVectorPositions |= field.IsStorePositionWithTermVector(); doVectorOffsets |= field.IsStoreOffsetWithTermVector(); } } if (doVectors) { if (perThread.doc == null) { perThread.doc = termsWriter.getPerDoc(); perThread.doc.docID = docState.docID; System.Diagnostics.Debug.Assert(perThread.doc.numVectorFields == 0); System.Diagnostics.Debug.Assert(0 == perThread.doc.tvf.Length()); System.Diagnostics.Debug.Assert(0 == perThread.doc.tvf.GetFilePointer()); } else { System.Diagnostics.Debug.Assert(perThread.doc.docID == docState.docID); if (termsHashPerField.numPostings != 0) // Only necessary if previous doc hit a // non-aborting exception while writing vectors in // this field: termsHashPerField.reset(); } } // TODO: only if needed for performance //perThread.postingsCount = 0; return doVectors; } public void abort() { } /** Called once per field per document if term vectors * are enabled, to write the vectors to * RAMOutputStream, which is then quickly flushed to * * the real term vectors files in the Directory. */ internal override void finish() { System.Diagnostics.Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.finish start")); int numPostings = termsHashPerField.numPostings; System.Diagnostics.Debug.Assert(numPostings >= 0); if (!doVectors || numPostings == 0) return; if (numPostings > maxNumPostings) maxNumPostings = numPostings; IndexOutput tvf = perThread.doc.tvf; // This is called once, after inverting all occurences // of a given field in the doc. At this point we flush // our hash into the DocWriter. System.Diagnostics.Debug.Assert(fieldInfo.storeTermVector); System.Diagnostics.Debug.Assert(perThread.vectorFieldsInOrder(fieldInfo)); perThread.doc.addField(termsHashPerField.fieldInfo.number); RawPostingList[] postings = termsHashPerField.sortPostings(); tvf.WriteVInt(numPostings); byte bits = 0x0; if (doVectorPositions) bits |= TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR; if (doVectorOffsets) bits |= TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR; tvf.WriteByte(bits); int encoderUpto = 0; int lastTermBytesCount = 0; ByteSliceReader reader = perThread.vectorSliceReader; char[][] charBuffers = perThread.termsHashPerThread.charPool.buffers; for (int j = 0; j < numPostings; j++) { TermVectorsTermsWriter.PostingList posting = (TermVectorsTermsWriter.PostingList)postings[j]; int freq = posting.freq; char[] text2 = charBuffers[posting.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; int start2 = posting.textStart & DocumentsWriter.CHAR_BLOCK_MASK; // We swap between two encoders to save copying // last Term's byte array UnicodeUtil.UTF8Result utf8Result = perThread.utf8Results[encoderUpto]; // TODO: we could do this incrementally UnicodeUtil.UTF16toUTF8(text2, start2, utf8Result); int termBytesCount = utf8Result.length; // TODO: UTF16toUTF8 could tell us this prefix // Compute common prefix between last term and // this term int prefix = 0; if (j > 0) { byte[] lastTermBytes = perThread.utf8Results[1 - encoderUpto].result; byte[] termBytes = perThread.utf8Results[encoderUpto].result; while (prefix < lastTermBytesCount && prefix < termBytesCount) { if (lastTermBytes[prefix] != termBytes[prefix]) break; prefix++; } } encoderUpto = 1 - encoderUpto; lastTermBytesCount = termBytesCount; int suffix = termBytesCount - prefix; tvf.WriteVInt(prefix); tvf.WriteVInt(suffix); tvf.WriteBytes(utf8Result.result, prefix, suffix); tvf.WriteVInt(freq); if (doVectorPositions) { termsHashPerField.initReader(reader, posting, 0); reader.WriteTo(tvf); } if (doVectorOffsets) { termsHashPerField.initReader(reader, posting, 1); reader.WriteTo(tvf); } } termsHashPerField.reset(); perThread.termsHashPerThread.reset(false); } internal void shrinkHash() { termsHashPerField.shrinkHash(maxNumPostings); maxNumPostings = 0; } internal override void newTerm(Token t, RawPostingList p0) { System.Diagnostics.Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.newTerm start")); TermVectorsTermsWriter.PostingList p = (TermVectorsTermsWriter.PostingList)p0; p.freq = 1; if (doVectorOffsets) { int startOffset = fieldState.offset + t.StartOffset(); int endOffset = fieldState.offset + t.EndOffset(); termsHashPerField.writeVInt(1, startOffset); termsHashPerField.writeVInt(1, endOffset - startOffset); p.lastOffset = endOffset; } if (doVectorPositions) { termsHashPerField.writeVInt(0, fieldState.position); p.lastPosition = fieldState.position; } } internal override void addTerm(Token t, RawPostingList p0) { System.Diagnostics.Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.addTerm start")); TermVectorsTermsWriter.PostingList p = (TermVectorsTermsWriter.PostingList)p0; p.freq++; if (doVectorOffsets) { int startOffset = fieldState.offset + t.StartOffset(); int endOffset = fieldState.offset + t.EndOffset(); termsHashPerField.writeVInt(1, startOffset - p.lastOffset); termsHashPerField.writeVInt(1, endOffset - startOffset); p.lastOffset = endOffset; } if (doVectorPositions) { termsHashPerField.writeVInt(0, fieldState.position - p.lastPosition); p.lastPosition = fieldState.position; } } internal override void skippingLongTerm(Token t) { } } }
//------------------------------------------------------------------------------ // <copyright file="ISAPIApplicationHost.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Application host for IIS 5.0 and 6.0 * * Copyright (c) 1999 Microsoft Corporation */ namespace System.Web.Hosting { using Microsoft.Win32; using System.IO; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Util; using System.Web.Management; using System.Diagnostics.CodeAnalysis; // helper class to implement AppHost based on ISAPI internal class ISAPIApplicationHost : MarshalByRefObject, IApplicationHost { private String _appId; private String _siteID; private String _siteName; private VirtualPath _virtualPath; private String _physicalPath; private IProcessHostSupportFunctions _functions; private String _iisVersion; private const int MAX_PATH = 260; private const string LMW3SVC_PREFIX = "/LM/W3SVC/"; private const string DEFAULT_SITEID = "1"; private const string DEFAULT_APPID_PREFIX = "/LM/W3SVC/1/ROOT"; internal ISAPIApplicationHost(string appIdOrVirtualPath, string physicalPath, bool validatePhysicalPath, IProcessHostSupportFunctions functions, string iisVersion = null) { _iisVersion = iisVersion; // appIdOrVirtualPath is either a full metabase path, or just a virtual path // e.g. /LM/W3SVC/1/Root/MyApp ot /MyApp // Figure out which one we have, and get the other one from it _functions = functions; // make sure the functions are set in the default domain if (null == _functions) { ProcessHost h = ProcessHost.DefaultHost; if (null != h) { _functions = h.SupportFunctions; if (null != _functions) { HostingEnvironment.SupportFunctions = _functions; } } } IServerConfig serverConfig = ServerConfig.GetDefaultDomainInstance(_iisVersion); if (StringUtil.StringStartsWithIgnoreCase(appIdOrVirtualPath, LMW3SVC_PREFIX)) { _appId = appIdOrVirtualPath; _virtualPath = VirtualPath.Create(ExtractVPathFromAppId(_appId)); _siteID = ExtractSiteIdFromAppId(_appId); _siteName = serverConfig.GetSiteNameFromSiteID(_siteID); } else { _virtualPath = VirtualPath.Create(appIdOrVirtualPath); _appId = GetDefaultAppIdFromVPath(_virtualPath.VirtualPathString); _siteID = DEFAULT_SITEID; _siteName = serverConfig.GetSiteNameFromSiteID(_siteID); } // Get the physical path from the virtual path if it wasn't passed in if (physicalPath == null) { _physicalPath = serverConfig.MapPath(this, _virtualPath); } else { _physicalPath = physicalPath; } if (validatePhysicalPath) { if (!Directory.Exists(_physicalPath)) { throw new HttpException(SR.GetString(SR.Invalid_IIS_app, appIdOrVirtualPath)); } } } internal ISAPIApplicationHost(string appIdOrVirtualPath, string physicalPath, bool validatePhysicalPath) :this(appIdOrVirtualPath, physicalPath, validatePhysicalPath, null) {} public override Object InitializeLifetimeService() { return null; // never expire lease } // IApplicationHost implementation string IApplicationHost.GetVirtualPath() { return _virtualPath.VirtualPathString; } String IApplicationHost.GetPhysicalPath() { return _physicalPath; } IConfigMapPathFactory IApplicationHost.GetConfigMapPathFactory() { return new ISAPIConfigMapPathFactory(); } IntPtr IApplicationHost.GetConfigToken() { if (null != _functions) { return _functions.GetConfigToken(_appId); } IntPtr token = IntPtr.Zero; String username; String password; IServerConfig serverConfig = ServerConfig.GetDefaultDomainInstance(_iisVersion); bool hasUncUser = serverConfig.GetUncUser(this, _virtualPath, out username, out password); if (hasUncUser) { try { String error; token = IdentitySection.CreateUserToken(username, password, out error); } catch { } } return token; } String IApplicationHost.GetSiteName() { return _siteName; } String IApplicationHost.GetSiteID() { return _siteID; } void IApplicationHost.MessageReceived() { // make this method call a no-op // it will be removed soon altogether } internal string AppId { get { return _appId; } } private static String ExtractVPathFromAppId(string id) { // app id is /LM/W3SVC/1/ROOT for root or /LM/W3SVC/1/ROOT/VDIR // find fifth / (assuming it starts with /) int si = 0; for (int i = 1; i < 5; i++) { si = id.IndexOf('/', si+1); if (si < 0) break; } if (si < 0) // root? return "/"; else return id.Substring(si); } private static String GetDefaultAppIdFromVPath(string virtualPath) { if (virtualPath.Length == 1 && virtualPath[0] == '/') { return DEFAULT_APPID_PREFIX; } else { return DEFAULT_APPID_PREFIX + virtualPath; } } private static String ExtractSiteIdFromAppId(string id) { // app id is /LM/W3SVC/1/ROOT for root or /LM/W3SVC/1/ROOT/VDIR // the site id is right after prefix int offset = LMW3SVC_PREFIX.Length; int si = id.IndexOf('/', offset); return (si > 0) ? id.Substring(offset, si - offset) : DEFAULT_SITEID; } internal IProcessHostSupportFunctions SupportFunctions { get { return _functions; } } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method's caller is trusted.")] internal string ResolveRootWebConfigPath() { string rootWebConfigPath = null; if (null != _functions) { rootWebConfigPath = _functions.GetRootWebConfigFilename(); } return rootWebConfigPath; } } // // Create an instance of IConfigMapPath in the worker appdomain. // By making the class Serializable, the call to IConfigMapPathFactory.Create() // will execute in the worker appdomain. // [Serializable()] internal class ISAPIConfigMapPathFactory : IConfigMapPathFactory { IConfigMapPath IConfigMapPathFactory.Create(string virtualPath, string physicalPath) { return IISMapPath.GetInstance(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Indicators; using QuantConnect.Interfaces; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Regression algorithm reproducing data type bugs in the RegisterIndicator API. Related to GH 4205. /// </summary> public class RegisterIndicatorRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private List<IIndicator> _indicators; private Symbol _symbol; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 09); var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME); _symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate.AddDays(1)).First(); AddFutureContract(_symbol); // this collection will hold all indicators and at the end of the algorithm we will assert that all of them are ready _indicators = new List<IIndicator>(); // Test the different APIs for IndicatorBase<QuoteBar> works correctly. // Should be able to determine the correct consolidator and not throw an exception var indicator = new CustomIndicator(); RegisterIndicator(_symbol, indicator, Resolution.Minute); _indicators.Add(indicator); // specifying a selector and using resolution var indicator2 = new CustomIndicator(); RegisterIndicator(_symbol, indicator2, Resolution.Minute, data => (QuoteBar) data); _indicators.Add(indicator2); // specifying a selector and using timeSpan var indicator3 = new CustomIndicator(); RegisterIndicator(_symbol, indicator3, TimeSpan.FromMinutes(1), data => (QuoteBar)data); _indicators.Add(indicator3); // directly sending in the desired consolidator var indicator4 = new SimpleMovingAverage(10); var consolidator = ResolveConsolidator(_symbol, Resolution.Minute, typeof(QuoteBar)); RegisterIndicator(_symbol, indicator4, consolidator); _indicators.Add(indicator4); // directly sending in the desired consolidator and specifying a selector var indicator5 = new SimpleMovingAverage(10); var consolidator2 = ResolveConsolidator(_symbol, Resolution.Minute, typeof(QuoteBar)); RegisterIndicator(_symbol, indicator5, consolidator2, data => { var quoteBar = data as QuoteBar; return quoteBar.High - quoteBar.Low; }); _indicators.Add(indicator5); // Now make sure default data type TradeBar works correctly and does not throw an exception // Specifying resolution and selector var movingAverage = new SimpleMovingAverage(10); RegisterIndicator(_symbol, movingAverage, Resolution.Minute, data => data.Value); _indicators.Add(movingAverage); // Specifying resolution var movingAverage2 = new SimpleMovingAverage(10); RegisterIndicator(_symbol, movingAverage2, Resolution.Minute); _indicators.Add(movingAverage2); // Specifying TimeSpan var movingAverage3 = new SimpleMovingAverage(10); RegisterIndicator(_symbol, movingAverage3, TimeSpan.FromMinutes(1)); _indicators.Add(movingAverage3); // Specifying TimeSpan and selector var movingAverage4 = new SimpleMovingAverage(10); RegisterIndicator(_symbol, movingAverage4, TimeSpan.FromMinutes(1), data => data.Value); _indicators.Add(movingAverage4); // Test custom data is able to register correctly and indicators updated var smaCustomData = new SimpleMovingAverage(1); var symbol = AddData<CustomDataRegressionAlgorithm.Bitcoin>("BTC", Resolution.Minute).Symbol; RegisterIndicator(symbol, smaCustomData, TimeSpan.FromMinutes(1), data => data.Value); _indicators.Add(smaCustomData); var smaCustomData2 = new SimpleMovingAverage(1); RegisterIndicator(symbol, smaCustomData2, Resolution.Minute); _indicators.Add(smaCustomData2); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { SetHoldings(_symbol, 0.5); } } public override void OnEndOfAlgorithm() { if (_indicators.Any(indicator => !indicator.IsReady)) { throw new Exception("All indicators should be ready"); } Log($"Total of {_indicators.Count} are ready"); } private class CustomIndicator : IndicatorBase<QuoteBar> { private bool _isReady; public override bool IsReady => _isReady; public CustomIndicator() : base("Jose") { } protected override decimal ComputeNextValue(QuoteBar input) { _isReady = true; return input.Close; } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "-100.000%"}, {"Drawdown", "19.800%"}, {"Expectancy", "0"}, {"Net Profit", "-10.353%"}, {"Sharpe Ratio", "-1.379"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "3.004"}, {"Beta", "5.322"}, {"Annual Standard Deviation", "0.725"}, {"Annual Variance", "0.525"}, {"Information Ratio", "-0.42"}, {"Tracking Error", "0.589"}, {"Treynor Ratio", "-0.188"}, {"Total Fees", "$20.35"}, {"Estimated Strategy Capacity", "$13000000.00"}, {"Lowest Capacity Asset", "ES VMKLFZIH2MTD"}, {"Fitness Score", "0.125"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-2.162"}, {"Return Over Maximum Drawdown", "-8.144"}, {"Portfolio Turnover", "3.184"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "7ff48adafe9676f341e64ac9388d3c2c"} }; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ReplicationvCentersOperations operations. /// </summary> internal partial class ReplicationvCentersOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationvCentersOperations { /// <summary> /// Initializes a new instance of the ReplicationvCentersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ReplicationvCentersOperations(SiteRecoveryManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SiteRecoveryManagementClient /// </summary> public SiteRecoveryManagementClient Client { get; private set; } /// <summary> /// Gets the details of a vCenter. /// </summary> /// <remarks> /// Gets the details of a registered vCenter server(Add vCenter server.) /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCenter name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VCenter>> GetWithHttpMessagesAsync(string fabricName, string vCenterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (vCenterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vCenterName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("vCenterName", vCenterName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{vCenterName}", System.Uri.EscapeDataString(vCenterName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VCenter>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VCenter>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Add vCenter. /// </summary> /// <remarks> /// The operation to create a vCenter object.. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCenter name. /// </param> /// <param name='addVCenterRequest'> /// The input to the add vCenter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VCenter>> CreateWithHttpMessagesAsync(string fabricName, string vCenterName, AddVCenterRequest addVCenterRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<VCenter> _response = await BeginCreateWithHttpMessagesAsync(fabricName, vCenterName, addVCenterRequest, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Remove vCenter operation. /// </summary> /// <remarks> /// The operation to remove(unregister) a registered vCenter server from the /// vault. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCenter name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string fabricName, string vCenterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(fabricName, vCenterName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update vCenter operation. /// </summary> /// <remarks> /// The operation to update a registered vCenter. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCeneter name /// </param> /// <param name='updateVCenterRequest'> /// The input to the update vCenter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VCenter>> UpdateWithHttpMessagesAsync(string fabricName, string vCenterName, UpdateVCenterRequest updateVCenterRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<VCenter> _response = await BeginUpdateWithHttpMessagesAsync(fabricName, vCenterName, updateVCenterRequest, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the list of vCenter registered under a fabric. /// </summary> /// <remarks> /// Lists the vCenter servers registered in a fabric. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VCenter>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationFabrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VCenter>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VCenter>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of vCenter registered under the vault. /// </summary> /// <remarks> /// Lists the vCenter servers registered in the vault. /// </remarks> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VCenter>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationvCenters").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VCenter>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VCenter>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Add vCenter. /// </summary> /// <remarks> /// The operation to create a vCenter object.. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCenter name. /// </param> /// <param name='addVCenterRequest'> /// The input to the add vCenter operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VCenter>> BeginCreateWithHttpMessagesAsync(string fabricName, string vCenterName, AddVCenterRequest addVCenterRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (vCenterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vCenterName"); } if (addVCenterRequest == null) { throw new ValidationException(ValidationRules.CannotBeNull, "addVCenterRequest"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("vCenterName", vCenterName); tracingParameters.Add("addVCenterRequest", addVCenterRequest); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{vCenterName}", System.Uri.EscapeDataString(vCenterName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(addVCenterRequest != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(addVCenterRequest, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VCenter>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VCenter>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Remove vCenter operation. /// </summary> /// <remarks> /// The operation to remove(unregister) a registered vCenter server from the /// vault. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCenter name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string fabricName, string vCenterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (vCenterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vCenterName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("vCenterName", vCenterName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{vCenterName}", System.Uri.EscapeDataString(vCenterName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update vCenter operation. /// </summary> /// <remarks> /// The operation to update a registered vCenter. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='vCenterName'> /// vCeneter name /// </param> /// <param name='updateVCenterRequest'> /// The input to the update vCenter operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VCenter>> BeginUpdateWithHttpMessagesAsync(string fabricName, string vCenterName, UpdateVCenterRequest updateVCenterRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (vCenterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vCenterName"); } if (updateVCenterRequest == null) { throw new ValidationException(ValidationRules.CannotBeNull, "updateVCenterRequest"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("vCenterName", vCenterName); tracingParameters.Add("updateVCenterRequest", updateVCenterRequest); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{vCenterName}", System.Uri.EscapeDataString(vCenterName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(updateVCenterRequest != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(updateVCenterRequest, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VCenter>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VCenter>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of vCenter registered under a fabric. /// </summary> /// <remarks> /// Lists the vCenter servers registered in a fabric. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VCenter>>> ListByReplicationFabricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationFabricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VCenter>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VCenter>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of vCenter registered under the vault. /// </summary> /// <remarks> /// Lists the vCenter servers registered in the vault. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VCenter>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VCenter>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VCenter>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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.Buffers.Text; using System.Diagnostics; namespace System.Security.Cryptography.Asn1 { /// <summary> /// A stateful, forward-only reader for BER-, CER-, or DER-encoded ASN.1 data. /// </summary> internal partial class AsnReader { // T-REC-X.690-201508 sec 9.2 internal const int MaxCERSegmentSize = 1000; // T-REC-X.690-201508 sec 8.1.5 says only 0000 is legal. private const int EndOfContentsEncodedLength = 2; private ReadOnlyMemory<byte> _data; /// <summary> /// The <see cref="AsnEncodingRules"/> in use by this reader. /// </summary> public AsnEncodingRules RuleSet { get; } /// <summary> /// An indication of whether or not the reader has remaining data available to process. /// </summary> public bool HasData => !_data.IsEmpty; /// <summary> /// Construct an <see cref="AsnReader"/> over <paramref name="data"/> with a given ruleset. /// </summary> /// <param name="data">The data to read.</param> /// <param name="ruleSet">The encoding constraints for the reader.</param> /// <remarks> /// This constructor does not evaluate <paramref name="data"/> for correctness, /// any correctness checks are done as part of member methods. /// /// This constructor does not copy <paramref name="data"/>. The caller is responsible for /// ensuring that the values do not change until the reader is finished. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="ruleSet"/> is not defined. /// </exception> public AsnReader(ReadOnlyMemory<byte> data, AsnEncodingRules ruleSet) { CheckEncodingRules(ruleSet); _data = data; RuleSet = ruleSet; } /// <summary> /// Throws a standardized <see cref="CryptographicException"/> if the reader has remaining /// data, performs no function if <see cref="HasData"/> returns <c>false</c>. /// </summary> /// <remarks> /// This method provides a standardized target and standardized exception for reading a /// "closed" structure, such as the nested content for an explicitly tagged value. /// </remarks> public void ThrowIfNotEmpty() { if (HasData) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } /// <summary> /// Read the encoded tag at the next data position, without advancing the reader. /// </summary> /// <returns> /// The decoded <see cref="Asn1Tag"/> value. /// </returns> /// <exception cref="CryptographicException"> /// a tag could not be decoded at the reader's current position. /// </exception> public Asn1Tag PeekTag() { if (Asn1Tag.TryDecode(_data.Span, out Asn1Tag tag, out int bytesRead)) { return tag; } throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } /// <summary> /// Get a <see cref="ReadOnlyMemory{T}"/> view of the next encoded value without /// advancing the reader. For indefinite length encodings this includes the /// End of Contents marker. /// </summary> /// <returns>A <see cref="ReadOnlyMemory{T}"/> view of the next encoded value.</returns> /// <exception cref="CryptographicException"> /// The reader is positioned at a point where the tag or length is invalid /// under the current encoding rules. /// </exception> /// <seealso cref="PeekContentBytes"/> /// <seealso cref="ReadEncodedValue"/> public ReadOnlyMemory<byte> PeekEncodedValue() { Asn1Tag tag = ReadTagAndLength(out int? length, out int bytesRead); if (length == null) { int contentsLength = SeekEndOfContents(_data.Slice(bytesRead)); return Slice(_data, 0, bytesRead + contentsLength + EndOfContentsEncodedLength); } return Slice(_data, 0, bytesRead + length.Value); } /// <summary> /// Get a <see cref="ReadOnlyMemory{T}"/> view of the content octets (bytes) of the /// next encoded value without advancing the reader. /// </summary> /// <returns> /// A <see cref="ReadOnlyMemory{T}"/> view of the contents octets of the next encoded value. /// </returns> /// <exception cref="CryptographicException"> /// The reader is positioned at a point where the tag or length is invalid /// under the current encoding rules. /// </exception> /// <seealso cref="PeekEncodedValue"/> public ReadOnlyMemory<byte> PeekContentBytes() { Asn1Tag tag = ReadTagAndLength(out int? length, out int bytesRead); if (length == null) { return Slice(_data, bytesRead, SeekEndOfContents(_data.Slice(bytesRead))); } return Slice(_data, bytesRead, length.Value); } /// <summary> /// Get a <see cref="ReadOnlyMemory{T}"/> view of the next encoded value, /// and advance the reader past it. For an indefinite length encoding this includes /// the End of Contents marker. /// </summary> /// <returns>A <see cref="ReadOnlyMemory{T}"/> view of the next encoded value.</returns> /// <seealso cref="PeekEncodedValue"/> public ReadOnlyMemory<byte> ReadEncodedValue() { ReadOnlyMemory<byte> encodedValue = PeekEncodedValue(); _data = _data.Slice(encodedValue.Length); return encodedValue; } private static bool TryReadLength( ReadOnlySpan<byte> source, AsnEncodingRules ruleSet, out int? length, out int bytesRead) { length = null; bytesRead = 0; CheckEncodingRules(ruleSet); if (source.IsEmpty) { return false; } // T-REC-X.690-201508 sec 8.1.3 byte lengthOrLengthLength = source[bytesRead]; bytesRead++; const byte MultiByteMarker = 0x80; // 0x00-0x7F are direct length values. // 0x80 is BER/CER indefinite length. // 0x81-0xFE says that the length takes the next 1-126 bytes. // 0xFF is forbidden. if (lengthOrLengthLength == MultiByteMarker) { // T-REC-X.690-201508 sec 10.1 (DER: Length forms) if (ruleSet == AsnEncodingRules.DER) { bytesRead = 0; return false; } // Null length == indefinite. return true; } if (lengthOrLengthLength < MultiByteMarker) { length = lengthOrLengthLength; return true; } if (lengthOrLengthLength == 0xFF) { bytesRead = 0; return false; } byte lengthLength = (byte)(lengthOrLengthLength & ~MultiByteMarker); // +1 for lengthOrLengthLength if (lengthLength + 1 > source.Length) { bytesRead = 0; return false; } // T-REC-X.690-201508 sec 9.1 (CER: Length forms) // T-REC-X.690-201508 sec 10.1 (DER: Length forms) bool minimalRepresentation = ruleSet == AsnEncodingRules.DER || ruleSet == AsnEncodingRules.CER; // The ITU-T specifications tecnically allow lengths up to ((2^128) - 1), but // since Span's length is a signed Int32 we're limited to identifying memory // that is within ((2^31) - 1) bytes of the tag start. if (minimalRepresentation && lengthLength > sizeof(int)) { bytesRead = 0; return false; } uint parsedLength = 0; for (int i = 0; i < lengthLength; i++) { byte current = source[bytesRead]; bytesRead++; if (parsedLength == 0) { if (minimalRepresentation && current == 0) { bytesRead = 0; return false; } if (!minimalRepresentation && current != 0) { // Under BER rules we could have had padding zeros, so // once the first data bits come in check that we fit within // sizeof(int) due to Span bounds. if (lengthLength - i > sizeof(int)) { bytesRead = 0; return false; } } } parsedLength <<= 8; parsedLength |= current; } // This value cannot be represented as a Span length. if (parsedLength > int.MaxValue) { bytesRead = 0; return false; } if (minimalRepresentation && parsedLength < MultiByteMarker) { bytesRead = 0; return false; } Debug.Assert(bytesRead > 0); length = (int)parsedLength; return true; } internal Asn1Tag ReadTagAndLength(out int? contentsLength, out int bytesRead) { if (Asn1Tag.TryDecode(_data.Span, out Asn1Tag tag, out int tagBytesRead) && TryReadLength(_data.Slice(tagBytesRead).Span, RuleSet, out int? length, out int lengthBytesRead)) { int allBytesRead = tagBytesRead + lengthBytesRead; if (tag.IsConstructed) { // T-REC-X.690-201508 sec 9.1 (CER: Length forms) says constructed is always indefinite. if (RuleSet == AsnEncodingRules.CER && length != null) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } else if (length == null) { // T-REC-X.690-201508 sec 8.1.3.2 says primitive encodings must use a definite form. throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } bytesRead = allBytesRead; contentsLength = length; return tag; } throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } private static void ValidateEndOfContents(Asn1Tag tag, int? length, int headerLength) { // T-REC-X.690-201508 sec 8.1.5 excludes the BER 8100 length form for 0. if (tag.IsConstructed || length != 0 || headerLength != EndOfContentsEncodedLength) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } /// <summary> /// Get the number of bytes between the start of <paramref name="source" /> and /// the End-of-Contents marker /// </summary> private int SeekEndOfContents(ReadOnlyMemory<byte> source) { ReadOnlyMemory<byte> cur = source; int totalLen = 0; AsnReader tmpReader = new AsnReader(cur, RuleSet); // Our reader is bounded by int.MaxValue. // The most aggressive data input would be a one-byte tag followed by // indefinite length "ad infinitum", which would be half the input. // So the depth marker can never overflow the signed integer space. int depth = 1; while (tmpReader.HasData) { Asn1Tag tag = tmpReader.ReadTagAndLength(out int? length, out int bytesRead); if (tag == Asn1Tag.EndOfContents) { ValidateEndOfContents(tag, length, bytesRead); depth--; if (depth == 0) { // T-REC-X.690-201508 sec 8.1.1.1 / 8.1.1.3 indicate that the // End-of-Contents octets are "after" the contents octets, not // "at the end" of them, so we don't include these bytes in the // accumulator. return totalLen; } } // We found another indefinite length, that means we need to find another // EndOfContents marker to balance it out. if (length == null) { depth++; tmpReader._data = tmpReader._data.Slice(bytesRead); totalLen += bytesRead; } else { // This will throw a CryptographicException if the length exceeds our bounds. ReadOnlyMemory<byte> tlv = Slice(tmpReader._data, 0, bytesRead + length.Value); // No exception? Then slice the data and continue. tmpReader._data = tmpReader._data.Slice(tlv.Length); totalLen += tlv.Length; } } throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } private static int ParseNonNegativeIntAndSlice(ref ReadOnlySpan<byte> data, int bytesToRead) { int value = ParseNonNegativeInt(Slice(data, 0, bytesToRead)); data = data.Slice(bytesToRead); return value; } private static int ParseNonNegativeInt(ReadOnlySpan<byte> data) { if (Utf8Parser.TryParse(data, out uint value, out int consumed) && value <= int.MaxValue && consumed == data.Length) { return (int)value; } throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } private static ReadOnlySpan<byte> SliceAtMost(ReadOnlySpan<byte> source, int longestPermitted) { int len = Math.Min(longestPermitted, source.Length); return source.Slice(0, len); } private static ReadOnlySpan<byte> Slice(ReadOnlySpan<byte> source, int offset, int length) { Debug.Assert(offset >= 0); if (length < 0 || source.Length - offset < length) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } return source.Slice(offset, length); } private static ReadOnlyMemory<byte> Slice(ReadOnlyMemory<byte> source, int offset, int? length) { Debug.Assert(offset >= 0); if (length == null) { return source.Slice(offset); } int lengthVal = length.Value; if (lengthVal < 0 || source.Length - offset < lengthVal) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } return source.Slice(offset, lengthVal); } private static void CheckEncodingRules(AsnEncodingRules ruleSet) { if (ruleSet != AsnEncodingRules.BER && ruleSet != AsnEncodingRules.CER && ruleSet != AsnEncodingRules.DER) { throw new ArgumentOutOfRangeException(nameof(ruleSet)); } } private static void CheckExpectedTag(Asn1Tag tag, Asn1Tag expectedTag, UniversalTagNumber tagNumber) { if (expectedTag.TagClass == TagClass.Universal && expectedTag.TagValue != (int)tagNumber) { throw new ArgumentException( SR.Cryptography_Asn_UniversalValueIsFixed, nameof(expectedTag)); } if (expectedTag.TagClass != tag.TagClass || expectedTag.TagValue != tag.TagValue) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using MSBuild = Microsoft.Build.Evaluation; using MSBuildExecution = Microsoft.Build.Execution; namespace Microsoft.VisualStudio.Project { /// <summary> /// Creates projects within the solution /// </summary> [CLSCompliant(false)] public abstract class ProjectFactory : Microsoft.VisualStudio.Shell.Flavor.FlavoredProjectFactoryBase, IVsAsynchronousProjectCreate { #region fields private Microsoft.VisualStudio.Shell.Package package; private System.IServiceProvider site; private static readonly Lazy<IVsTaskSchedulerService> taskSchedulerService = new Lazy<IVsTaskSchedulerService>(() => Package.GetGlobalService(typeof(SVsTaskSchedulerService)) as IVsTaskSchedulerService); /// <summary> /// The msbuild engine that we are going to use. /// </summary> private MSBuild.ProjectCollection buildEngine; /// <summary> /// The msbuild project for the project file. /// </summary> private MSBuild.Project buildProject; #endregion #region properties protected Microsoft.VisualStudio.Shell.Package Package { get { return this.package; } } protected System.IServiceProvider Site { get { return this.site; } } /// <summary> /// The msbuild engine that we are going to use. /// </summary> protected MSBuild.ProjectCollection BuildEngine { get { return this.buildEngine; } } /// <summary> /// The msbuild project for the temporary project file. /// </summary> protected MSBuild.Project BuildProject { get { return this.buildProject; } set { this.buildProject = value; } } #endregion #region ctor protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package) { this.package = package; this.site = package; // Please be aware that this methods needs that ServiceProvider is valid, thus the ordering of calls in the ctor matters. this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.site); } #endregion #region methods public virtual bool CanCreateProjectAsynchronously(ref Guid rguidProjectID, string filename, uint flags) { return true; } public void OnBeforeCreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { } public virtual IVsTask CreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { Guid iid = typeof(IVsHierarchy).GUID; return VsTaskLibraryHelper.CreateAndStartTask(taskSchedulerService.Value, VsTaskRunContext.UIThreadBackgroundPriority, VsTaskLibraryHelper.CreateTaskBody(() => { IntPtr project; int cancelled; CreateProject(filename, location, pszName, flags, ref iid, out project, out cancelled); if (cancelled != 0) { throw new OperationCanceledException(); } return Marshal.GetObjectForIUnknown(project); })); } #endregion #region abstract methods protected abstract ProjectNode CreateProject(); #endregion #region overriden methods /// <summary> /// Rather than directly creating the project, ask VS to initate the process of /// creating an aggregated project in case we are flavored. We will be called /// on the IVsAggregatableProjectFactory to do the real project creation. /// </summary> /// <param name="fileName">Project file</param> /// <param name="location">Path of the project</param> /// <param name="name">Project Name</param> /// <param name="flags">Creation flags</param> /// <param name="projectGuid">Guid of the project</param> /// <param name="project">Project that end up being created by this method</param> /// <param name="canceled">Was the project creation canceled</param> protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled) { project = IntPtr.Zero; canceled = 0; // Get the list of GUIDs from the project/template string guidsList = this.ProjectTypeGuids(fileName); // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation) IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject)); int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project); if(hr == VSConstants.E_ABORT) canceled = 1; ErrorHandler.ThrowOnFailure(hr); // This needs to be done after the aggregation is completed (to avoid creating a non-aggregated CCW) and as a result we have to go through the interface IProjectEventsProvider eventsProvider = (IProjectEventsProvider)Marshal.GetTypedObjectForIUnknown(project, typeof(IProjectEventsProvider)); eventsProvider.ProjectEventsProvider = this.GetProjectEventsProvider(); this.buildProject = null; } /// <summary> /// Instantiate the project class, but do not proceed with the /// initialization just yet. /// Delegate to CreateProject implemented by the derived class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The global property handles is instantiated here and used in the project node that will Dispose it")] protected override object PreCreateForOuter(IntPtr outerProjectIUnknown) { Debug.Assert(this.buildProject != null, "The build project should have been initialized before calling PreCreateForOuter."); // Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node. // The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail // Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method. ProjectNode node = this.CreateProject(); Debug.Assert(node != null, "The project failed to be created"); node.BuildEngine = this.buildEngine; node.BuildProject = this.buildProject; node.Package = this.package as ProjectPackage; return node; } /// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if(String.IsNullOrEmpty(guids)) guids = this.GetType().GUID.ToString("B"); return guids; } #endregion #region helpers private IProjectEvents GetProjectEventsProvider() { ProjectPackage projectPackage = this.package as ProjectPackage; Debug.Assert(projectPackage != null, "Package not inherited from framework"); if(projectPackage != null) { foreach(SolutionListener listener in projectPackage.SolutionListeners) { IProjectEvents projectEvents = listener as IProjectEvents; if(projectEvents != null) { return projectEvents; } } } return null; } #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.ObjectModel; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Runtime { internal partial class ExceptionTrace { private const ushort FailFastEventLogCategory = 6; public void AsInformation(Exception exception) { //Traces an informational trace message } public void AsWarning(Exception exception) { //Traces a warning trace message } public Exception AsError(Exception exception) { // AggregateExceptions are automatically unwrapped. AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return AsError<Exception>(aggregateException); } // TargetInvocationExceptions are automatically unwrapped. TargetInvocationException targetInvocationException = exception as TargetInvocationException; if (targetInvocationException != null && targetInvocationException.InnerException != null) { return AsError(targetInvocationException.InnerException); } return TraceException(exception); } public Exception AsError(Exception exception, string eventSource) { // AggregateExceptions are automatically unwrapped. AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return AsError<Exception>(aggregateException, eventSource); } // TargetInvocationExceptions are automatically unwrapped. TargetInvocationException targetInvocationException = exception as TargetInvocationException; if (targetInvocationException != null && targetInvocationException.InnerException != null) { return AsError(targetInvocationException.InnerException, eventSource); } return TraceException(exception, eventSource); } public Exception AsError(TargetInvocationException targetInvocationException, string eventSource) { Fx.Assert(targetInvocationException != null, "targetInvocationException cannot be null."); // If targetInvocationException contains any fatal exceptions, return it directly // without tracing it or any inner exceptions. if (Fx.IsFatal(targetInvocationException)) { return targetInvocationException; } // A non-null inner exception could require further unwrapping in AsError. Exception innerException = targetInvocationException.InnerException; if (innerException != null) { return AsError(innerException, eventSource); } // A null inner exception is unlikely but possible. // In this case, trace and return the targetInvocationException itself. return TraceException<Exception>(targetInvocationException, eventSource); } public Exception AsError<TPreferredException>(AggregateException aggregateException) { return AsError<TPreferredException>(aggregateException, _eventSourceName); } /// <summary> /// Extracts the first inner exception of type <typeparamref name="TPreferredException"/> /// from the <see cref="AggregateException"/> if one is present. /// </summary> /// <remarks> /// If no <typeparamref name="TPreferredException"/> inner exception is present, this /// method returns the first inner exception. All inner exceptions will be traced, /// including the one returned. The containing <paramref name="aggregateException"/> /// will not be traced unless there are no inner exceptions. /// </remarks> /// <typeparam name="TPreferredException">The preferred type of inner exception to extract. /// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam> /// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param> /// <param name="eventSource">The event source to trace.</param> /// <returns>The extracted exception. It will not be <c>null</c> /// but it may not be of type <typeparamref name="TPreferredException"/>.</returns> public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource) { Fx.Assert(aggregateException != null, "aggregateException cannot be null."); // If aggregateException contains any fatal exceptions, return it directly // without tracing it or any inner exceptions. if (Fx.IsFatal(aggregateException)) { return aggregateException; } // Collapse possibly nested graph into a flat list. // Empty inner exception list is unlikely but possible via public api. ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions; if (innerExceptions.Count == 0) { return TraceException(aggregateException, eventSource); } // Find the first inner exception, giving precedence to TPreferredException Exception favoredException = null; foreach (Exception nextInnerException in innerExceptions) { // AggregateException may wrap TargetInvocationException, so unwrap those as well TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException; Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null) ? targetInvocationException.InnerException : nextInnerException; if (innerException is TPreferredException && favoredException == null) { favoredException = innerException; } // All inner exceptions are traced TraceException(innerException, eventSource); } if (favoredException == null) { Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here."); favoredException = innerExceptions[0]; } return favoredException; } public ArgumentException Argument(string paramName, string message) { return TraceException(new ArgumentException(message, paramName)); } public ArgumentNullException ArgumentNull(string paramName) { return TraceException(new ArgumentNullException(paramName)); } public ArgumentNullException ArgumentNull(string paramName, string message) { return TraceException(new ArgumentNullException(paramName, message)); } public ArgumentException ArgumentNullOrEmpty(string paramName) { return Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName)); } public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message) { return TraceException(new ArgumentOutOfRangeException(paramName, actualValue, message)); } // When throwing ObjectDisposedException, it is highly recommended that you use this ctor // [C#] // public ObjectDisposedException(string objectName, string message); // And provide null for objectName but meaningful and relevant message for message. // It is recommended because end user really does not care or can do anything on the disposed object, commonly an internal or private object. public ObjectDisposedException ObjectDisposed(string message) { // pass in null, not disposedObject.GetType().FullName as per the above guideline return TraceException(new ObjectDisposedException(null, message)); } public void TraceHandledException(Exception exception, TraceEventType traceEventType) { switch (traceEventType) { case TraceEventType.Error: if (!TraceCore.HandledExceptionErrorIsEnabled(_diagnosticTrace)) break; TraceCore.HandledExceptionError(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception); break; case TraceEventType.Warning: if (!TraceCore.HandledExceptionWarningIsEnabled(_diagnosticTrace)) break; TraceCore.HandledExceptionWarning(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception); break; case TraceEventType.Verbose: if (!TraceCore.HandledExceptionVerboseIsEnabled(_diagnosticTrace)) break; TraceCore.HandledExceptionVerbose(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception); break; default: if (!TraceCore.HandledExceptionIsEnabled(_diagnosticTrace)) break; TraceCore.HandledException(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception); break; } } public void TraceUnhandledException(Exception exception) { TraceCore.UnhandledException(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception); } private TException TraceException<TException>(TException exception) where TException : Exception { return TraceException(exception, _eventSourceName); } private TException TraceException<TException>(TException exception, string eventSource) where TException : Exception { if (TraceCore.ThrowingExceptionIsEnabled(_diagnosticTrace)) { TraceCore.ThrowingException(_diagnosticTrace, eventSource, exception != null ? exception.ToString() : string.Empty, exception); } BreakOnException(exception); return exception; } private void BreakOnException(Exception exception) { } [MethodImpl(MethodImplOptions.NoInlining)] internal void TraceFailFast(string message) { } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Collections; using System.Diagnostics; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Globalization; #if HAVE_METHOD_IMPL_ATTRIBUTE using System.Runtime.CompilerServices; #endif using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { internal static class CollectionUtils { /// <summary> /// Determines whether the collection is <c>null</c> or empty. /// </summary> /// <param name="collection">The collection.</param> /// <returns> /// <c>true</c> if the collection is <c>null</c> or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty<T>(ICollection<T> collection) { if (collection != null) { return (collection.Count == 0); } return true; } /// <summary> /// Adds the elements of the specified collection to the specified generic <see cref="IList{T}"/>. /// </summary> /// <param name="initial">The list to add to.</param> /// <param name="collection">The collection of elements to add.</param> public static void AddRange<T>(this IList<T> initial, IEnumerable<T> collection) { if (initial == null) { throw new ArgumentNullException(nameof(initial)); } if (collection == null) { return; } foreach (T value in collection) { initial.Add(value); } } #if !HAVE_COVARIANT_GENERICS public static void AddRange<T>(this IList<T> initial, IEnumerable collection) { ValidationUtils.ArgumentNotNull(initial, nameof(initial)); // because earlier versions of .NET didn't support covariant generics initial.AddRange(collection.Cast<T>()); } #endif public static bool IsDictionaryType(Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); if (typeof(IDictionary).IsAssignableFrom(type)) { return true; } if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>))) { return true; } #if HAVE_READ_ONLY_COLLECTIONS if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IReadOnlyDictionary<,>))) { return true; } #endif return false; } public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) { Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType); return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument); } public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) { Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); ConstructorInfo match = null; foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { IList<ParameterInfo> parameters = constructor.GetParameters(); if (parameters.Count == 1) { Type parameterType = parameters[0].ParameterType; if (genericEnumerable == parameterType) { // exact match match = constructor; break; } // in case we can't find an exact match, use first inexact if (match == null) { if (parameterType.IsAssignableFrom(constructorArgumentType)) { match = constructor; } } } } return match; } public static bool AddDistinct<T>(this IList<T> list, T value) { return list.AddDistinct(value, EqualityComparer<T>.Default); } public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer) { if (list.ContainsValue(value, comparer)) { return false; } list.Add(value); return true; } // this is here because LINQ Bridge doesn't support Contains with IEqualityComparer<T> public static bool ContainsValue<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer) { if (comparer == null) { comparer = EqualityComparer<TSource>.Default; } if (source == null) { throw new ArgumentNullException(nameof(source)); } foreach (TSource local in source) { if (comparer.Equals(local, value)) { return true; } } return false; } public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer) { bool allAdded = true; foreach (T value in values) { if (!list.AddDistinct(value, comparer)) { allAdded = false; } } return allAdded; } public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { int index = 0; foreach (T value in collection) { if (predicate(value)) { return index; } index++; } return -1; } public static bool Contains<T>(this List<T> list, T value, IEqualityComparer comparer) { for (int i = 0; i < list.Count; i++) { if (comparer.Equals(value, list[i])) { return true; } } return false; } public static int IndexOfReference<T>(this List<T> list, T item) { for (int i = 0; i < list.Count; i++) { if (ReferenceEquals(item, list[i])) { return i; } } return -1; } #if HAVE_FAST_REVERSE // faster reverse in .NET Framework with value types - https://github.com/JamesNK/Newtonsoft.Json/issues/1430 public static void FastReverse<T>(this List<T> list) { int i = 0; int j = list.Count - 1; while (i < j) { T temp = list[i]; list[i] = list[j]; list[j] = temp; i++; j--; } } #endif private static IList<int> GetDimensions(IList values, int dimensionsCount) { IList<int> dimensions = new List<int>(); IList currentArray = values; while (true) { dimensions.Add(currentArray.Count); // don't keep calculating dimensions for arrays inside the value array if (dimensions.Count == dimensionsCount) { break; } if (currentArray.Count == 0) { break; } object v = currentArray[0]; if (v is IList list) { currentArray = list; } else { break; } } return dimensions; } private static void CopyFromJaggedToMultidimensionalArray(IList values, Array multidimensionalArray, int[] indices) { int dimension = indices.Length; if (dimension == multidimensionalArray.Rank) { multidimensionalArray.SetValue(JaggedArrayGetValue(values, indices), indices); return; } int dimensionLength = multidimensionalArray.GetLength(dimension); IList list = (IList)JaggedArrayGetValue(values, indices); int currentValuesLength = list.Count; if (currentValuesLength != dimensionLength) { throw new Exception("Cannot deserialize non-cubical array as multidimensional array."); } int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } for (int i = 0; i < multidimensionalArray.GetLength(dimension); i++) { newIndices[dimension] = i; CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, newIndices); } } private static object JaggedArrayGetValue(IList values, int[] indices) { IList currentList = values; for (int i = 0; i < indices.Length; i++) { int index = indices[i]; if (i == indices.Length - 1) { return currentList[index]; } else { currentList = (IList)currentList[index]; } } return currentList; } public static Array ToMultidimensionalArray(IList values, Type type, int rank) { IList<int> dimensions = GetDimensions(values, rank); while (dimensions.Count < rank) { dimensions.Add(0); } Array multidimensionalArray = Array.CreateInstance(type, dimensions.ToArray()); CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, ArrayEmpty<int>()); return multidimensionalArray; } // 4.6 has Array.Empty<T> to return a cached empty array. Lacking that in other // frameworks, Enumerable.Empty<T> happens to be implemented as a cached empty // array in all versions (in .NET Core the same instance as Array.Empty<T>). // This includes the internal Linq bridge for 2.0. // Since this method is simple and only 11 bytes long in a release build it's // pretty much guaranteed to be inlined, giving us fast access of that cached // array. With 4.5 and up we use AggressiveInlining just to be sure, so it's // effectively the same as calling Array.Empty<T> even when not available. #if HAVE_METHOD_IMPL_ATTRIBUTE [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static T[] ArrayEmpty<T>() { T[] array = Enumerable.Empty<T>() as T[]; Debug.Assert(array != null); // Defensively guard against a version of Linq where Enumerable.Empty<T> doesn't // return an array, but throw in debug versions so a better strategy can be // used if that ever happens. return array ?? new T[0]; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Lucene.Net.Documents; using Lucene.Net.Search; using Lucene.Net.Index; using TermInfo = Lucene.Net.Search.Vectorhighlight.FieldTermStack.TermInfo; using QueryPhraseMap = Lucene.Net.Search.Vectorhighlight.FieldQuery.QueryPhraseMap; namespace Lucene.Net.Search.Vectorhighlight { /// <summary> /// FieldPhraseList has a list of WeightedPhraseInfo that is used by FragListBuilder /// to create a FieldFragList object. /// </summary> public class FieldPhraseList { public LinkedList<WeightedPhraseInfo> phraseList = new LinkedList<WeightedPhraseInfo>(); /// <summary> /// a constructor. /// </summary> /// <param name="fieldTermStack">FieldTermStack object</param> /// <param name="fieldQuery">FieldQuery object</param> public FieldPhraseList(FieldTermStack fieldTermStack, FieldQuery fieldQuery) { String field = fieldTermStack.GetFieldName(); LinkedList<TermInfo> phraseCandidate = new LinkedList<TermInfo>(); QueryPhraseMap currMap = null; QueryPhraseMap nextMap = null; while (!fieldTermStack.IsEmpty()) { phraseCandidate.Clear(); TermInfo ti = fieldTermStack.Pop(); currMap = fieldQuery.GetFieldTermMap(field, ti.GetText()); // if not found, discard top TermInfo from stack, then try next element if (currMap == null) continue; // if found, search the longest phrase phraseCandidate.AddLast(ti); while (true) { ti = fieldTermStack.Pop(); nextMap = null; if (ti != null) nextMap = currMap.GetTermMap(ti.GetText()); if (ti == null || nextMap == null) { if (ti != null) fieldTermStack.Push(ti); if (currMap.IsValidTermOrPhrase(new List<TermInfo>(phraseCandidate))) { AddIfNoOverlap(new WeightedPhraseInfo(phraseCandidate, currMap.GetBoost(), currMap.GetTermOrPhraseNumber())); } else { while (phraseCandidate.Count > 1) { TermInfo last = phraseCandidate.Last.Value; phraseCandidate.RemoveLast(); fieldTermStack.Push(last); currMap = fieldQuery.SearchPhrase(field, new List<TermInfo>(phraseCandidate)); if (currMap != null) { AddIfNoOverlap(new WeightedPhraseInfo(phraseCandidate, currMap.GetBoost(), currMap.GetTermOrPhraseNumber())); break; } } } break; } else { phraseCandidate.AddLast(ti); currMap = nextMap; } } } } void AddIfNoOverlap(WeightedPhraseInfo wpi) { foreach (WeightedPhraseInfo existWpi in phraseList) { if (existWpi.IsOffsetOverlap(wpi)) return; } phraseList.AddLast(wpi); } public class WeightedPhraseInfo { internal String text; // unnecessary member, just exists for debugging purpose internal List<Toffs> termsOffsets; // usually termsOffsets.size() == 1, // but if position-gap > 1 and slop > 0 then size() could be greater than 1 internal float boost; // query boost internal int seqnum; public WeightedPhraseInfo(LinkedList<TermInfo> terms, float boost): this(terms, boost, 0) { } public WeightedPhraseInfo(LinkedList<TermInfo> terms, float boost, int number) { this.boost = boost; this.seqnum = number; termsOffsets = new List<Toffs>(terms.Count); TermInfo ti = terms.First.Value; termsOffsets.Add(new Toffs(ti.GetStartOffset(), ti.GetEndOffset())); if (terms.Count == 1) { text = ti.GetText(); return; } StringBuilder sb = new StringBuilder(); sb.Append(ti.GetText()); int pos = ti.GetPosition(); bool dummy = true; foreach(TermInfo ti2 in terms) //for (int i = 1; i < terms.Count; i++) { if (dummy) { dummy = false; continue; } //Skip First Item {{DIGY}} ti = ti2; //ti = terms.get(i); sb.Append(ti.GetText()); if (ti.GetPosition() - pos == 1) { Toffs to = termsOffsets[termsOffsets.Count - 1]; to.SetEndOffset(ti.GetEndOffset()); } else { termsOffsets.Add(new Toffs(ti.GetStartOffset(), ti.GetEndOffset())); } pos = ti.GetPosition(); } text = sb.ToString(); } public int GetStartOffset() { return termsOffsets[0].startOffset; } public int GetEndOffset() { return termsOffsets[termsOffsets.Count - 1].endOffset; } public bool IsOffsetOverlap(WeightedPhraseInfo other) { int so = GetStartOffset(); int eo = GetEndOffset(); int oso = other.GetStartOffset(); int oeo = other.GetEndOffset(); if (so <= oso && oso < eo) return true; if (so < oeo && oeo <= eo) return true; if (oso <= so && so < oeo) return true; if (oso < eo && eo <= oeo) return true; return false; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(text).Append('(').Append(boost.ToString(".0").Replace(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator,".")).Append(")("); foreach (Toffs to in termsOffsets) { sb.Append(to); } sb.Append(')'); return sb.ToString(); } public class Toffs { internal int startOffset; internal int endOffset; public Toffs(int startOffset, int endOffset) { this.startOffset = startOffset; this.endOffset = endOffset; } internal void SetEndOffset(int endOffset) { this.endOffset = endOffset; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('(').Append(startOffset).Append(',').Append(endOffset).Append(')'); return sb.ToString(); } } } } }
// 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; namespace System.Collections.Immutable { /// <summary> /// Extension methods for immutable types. /// </summary> internal static partial class ImmutableExtensions { #if EqualsStructurally /// <summary> /// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/> /// that allows nulls, considers reference equality and count before beginning the enumeration. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="sequence1">The first sequence.</param> /// <param name="sequence2">The second sequence.</param> /// <param name="equalityComparer">The equality comparer to use for the elements.</param> /// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns> internal static bool CollectionEquals<T>(this IEnumerable<T> sequence1, IEnumerable<T> sequence2, IEqualityComparer<T> equalityComparer = null) { if (sequence1 == sequence2) { return true; } if ((sequence1 == null) ^ (sequence2 == null)) { return false; } int count1, count2; if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount(out count2)) { if (count1 != count2) { return false; } if (count1 == 0 && count2 == 0) { return true; } } return sequence1.SequenceEqual(sequence2, equalityComparer); } /// <summary> /// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/> /// that allows nulls, considers reference equality and count before beginning the enumeration. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="sequence1">The first sequence.</param> /// <param name="sequence2">The second sequence.</param> /// <param name="equalityComparer">The equality comparer to use for the elements.</param> /// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns> internal static bool CollectionEquals<T>(this IEnumerable<T> sequence1, IEnumerable sequence2, IEqualityComparer equalityComparer = null) { if (sequence1 == sequence2) { return true; } if ((sequence1 == null) ^ (sequence2 == null)) { return false; } int count1, count2; if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount<T>(out count2)) { if (count1 != count2) { return false; } if (count1 == 0 && count2 == 0) { return true; } } if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } // If we have generic types we can use, use them to avoid boxing. var sequence2OfT = sequence2 as IEnumerable<T>; var equalityComparerOfT = equalityComparer as IEqualityComparer<T>; if (sequence2OfT != null && equalityComparerOfT != null) { return sequence1.SequenceEqual(sequence2OfT, equalityComparerOfT); } else { // We have to fall back to doing it manually since the underlying collection // being compared isn't a (matching) generic type. using (var enumerator = sequence1.GetEnumerator()) { var enumerator2 = sequence2.GetEnumerator(); try { while (enumerator.MoveNext()) { if (!enumerator2.MoveNext() || !equalityComparer.Equals(enumerator.Current, enumerator2.Current)) { return false; } } if (enumerator2.MoveNext()) { return false; } return true; } finally { var enum2Disposable = enumerator2 as IDisposable; if (enum2Disposable != null) { enum2Disposable.Dispose(); } } } } } #endif /// <summary> /// Provides a known wrapper around a sequence of elements that provides the number of elements /// and an indexer into its contents. /// </summary> /// <typeparam name="T">The type of elements in the collection.</typeparam> /// <param name="sequence">The collection.</param> /// <returns>An ordered collection. May not be thread-safe. Never null.</returns> internal static IOrderedCollection<T> AsOrderedCollection<T>(this IEnumerable<T> sequence) { Requires.NotNull(sequence, nameof(sequence)); Contract.Ensures(Contract.Result<IOrderedCollection<T>>() != null); var orderedCollection = sequence as IOrderedCollection<T>; if (orderedCollection != null) { return orderedCollection; } var listOfT = sequence as IList<T>; if (listOfT != null) { return new ListOfTWrapper<T>(listOfT); } // It would be great if SortedSet<T> and SortedDictionary<T> provided indexers into their collections, // but since they don't we have to clone them to an array. return new FallbackWrapper<T>(sequence); } /// <summary> /// Clears the specified stack. For empty stacks, it avoids the call to <see cref="Stack{T}.Clear"/>, which /// avoids a call into the runtime's implementation of <see cref="Array.Clear"/>, helping performance, /// in particular around inlining. <see cref="Stack{T}.Count"/> typically gets inlined by today's JIT, while /// <see cref="Stack{T}.Clear"/> and <see cref="Array.Clear"/> typically don't. /// </summary> /// <typeparam name="T">Specifies the type of data in the stack to be cleared.</typeparam> /// <param name="stack">The stack to clear.</param> internal static void ClearFastWhenEmpty<T>(this Stack<T> stack) { if (stack.Count > 0) { stack.Clear(); } } /// <summary> /// Gets a disposable enumerable that can be used as the source for a C# foreach loop /// that will not box the enumerator if it is of a particular type. /// </summary> /// <typeparam name="T">The type of value to be enumerated.</typeparam> /// <typeparam name="TEnumerator">The type of the Enumerator struct.</typeparam> /// <param name="enumerable">The collection to be enumerated.</param> /// <returns>A struct that enumerates the collection.</returns> internal static DisposableEnumeratorAdapter<T, TEnumerator> GetEnumerableDisposable<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct, IStrongEnumerator<T>, IEnumerator<T> { Requires.NotNull(enumerable, nameof(enumerable)); var strongEnumerable = enumerable as IStrongEnumerable<T, TEnumerator>; if (strongEnumerable != null) { return new DisposableEnumeratorAdapter<T, TEnumerator>(strongEnumerable.GetEnumerator()); } else { // Consider for future: we could add more special cases for common // mutable collection types like List<T>+Enumerator and such. return new DisposableEnumeratorAdapter<T, TEnumerator>(enumerable.GetEnumerator()); } } /// <summary> /// Wraps a <see cref="IList{T}"/> as an ordered collection. /// </summary> /// <typeparam name="T">The type of element in the collection.</typeparam> private class ListOfTWrapper<T> : IOrderedCollection<T> { /// <summary> /// The list being exposed. /// </summary> private readonly IList<T> _collection; /// <summary> /// Initializes a new instance of the <see cref="ListOfTWrapper{T}"/> class. /// </summary> /// <param name="collection">The collection.</param> internal ListOfTWrapper(IList<T> collection) { Requires.NotNull(collection, nameof(collection)); _collection = collection; } /// <summary> /// Gets the count. /// </summary> public int Count { get { return _collection.Count; } } /// <summary> /// Gets the <typeparamref name="T"/> at the specified index. /// </summary> public T this[int index] { get { return _collection[index]; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return _collection.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } /// <summary> /// Wraps any <see cref="IEnumerable{T}"/> as an ordered, indexable list. /// </summary> /// <typeparam name="T">The type of element in the collection.</typeparam> private class FallbackWrapper<T> : IOrderedCollection<T> { /// <summary> /// The original sequence. /// </summary> private readonly IEnumerable<T> _sequence; /// <summary> /// The list-ified sequence. /// </summary> private IList<T> _collection; /// <summary> /// Initializes a new instance of the <see cref="FallbackWrapper{T}"/> class. /// </summary> /// <param name="sequence">The sequence.</param> internal FallbackWrapper(IEnumerable<T> sequence) { Requires.NotNull(sequence, nameof(sequence)); _sequence = sequence; } /// <summary> /// Gets the count. /// </summary> public int Count { get { if (_collection == null) { int count; if (_sequence.TryGetCount(out count)) { return count; } _collection = _sequence.ToArray(); } return _collection.Count; } } /// <summary> /// Gets the <typeparamref name="T"/> at the specified index. /// </summary> public T this[int index] { get { if (_collection == null) { _collection = _sequence.ToArray(); } return _collection[index]; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return _sequence.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImageAnnotationExamples.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace ExampleLibrary { using System; using System.Reflection; using OxyPlot; using OxyPlot.Annotations; using OxyPlot.Axes; using OxyPlot.Series; [Examples("ImageAnnotation"), Tags("Annotations")] public static class ImageAnnotationExamples { [Example("ImageAnnotation")] public static PlotModel ImageAnnotation() { var model = new PlotModel { Title = "ImageAnnotation", PlotMargins = new OxyThickness(60, 4, 4, 60) }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); OxyImage image; var assembly = typeof(ImageAnnotationExamples).GetTypeInfo().Assembly; using (var stream = assembly.GetManifestResourceStream("ExampleLibrary.Resources.OxyPlot.png")) { image = new OxyImage(stream); } // Centered in plot area, filling width model.Annotations.Add(new ImageAnnotation { ImageSource = image, Opacity = 0.2, Interpolate = false, X = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea), Width = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Middle }); // Relative to plot area, inside top/right corner, 120pt wide model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Width = new PlotLength(120, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top }); // Relative to plot area, above top/left corner, 20pt high model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), OffsetY = new PlotLength(-5, PlotLengthUnit.ScreenUnits), Height = new PlotLength(20, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); // At the point (50,50), 200pt wide model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(50, PlotLengthUnit.Data), Y = new PlotLength(50, PlotLengthUnit.Data), Width = new PlotLength(200, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); // At the point (50,20), 50 x units wide model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(50, PlotLengthUnit.Data), Y = new PlotLength(20, PlotLengthUnit.Data), Width = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top }); // Relative to the viewport, centered at the bottom, with offset (could also use bottom vertical alignment) model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(0.5, PlotLengthUnit.RelativeToViewport), Y = new PlotLength(1, PlotLengthUnit.RelativeToViewport), OffsetY = new PlotLength(-35, PlotLengthUnit.ScreenUnits), Height = new PlotLength(30, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top }); // Changing opacity for (int y = 0; y < 10; y++) { model.Annotations.Add( new ImageAnnotation { ImageSource = image, Opacity = (y + 1) / 10.0, X = new PlotLength(10, PlotLengthUnit.Data), Y = new PlotLength(y * 2, PlotLengthUnit.Data), Width = new PlotLength(100, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom }); } return model; } [Example("ImageAnnotation - gradient backgrounds")] public static PlotModel ImageAnnotationAsBackgroundGradient() { // http://en.wikipedia.org/wiki/Chartjunk var model = new PlotModel { Title = "Using ImageAnnotations to draw a gradient backgrounds", Subtitle = "But do you really want this? This is called 'chartjunk'!", PlotMargins = new OxyThickness(60, 4, 4, 60) }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); // create a gradient image of height n int n = 256; var imageData1 = new OxyColor[1, n]; for (int i = 0; i < n; i++) { imageData1[0, i] = OxyColor.Interpolate(OxyColors.Blue, OxyColors.Red, i / (n - 1.0)); } var image1 = OxyImage.Create(imageData1, ImageFormat.Png); // png is required for silverlight // or create a gradient image of height 2 (requires bitmap interpolation to be supported) var imageData2 = new OxyColor[1, 2]; imageData2[0, 0] = OxyColors.Yellow; // top color imageData2[0, 1] = OxyColors.Gray; // bottom color var image2 = OxyImage.Create(imageData2, ImageFormat.Png); // png is required for silverlight // gradient filling the viewport model.Annotations.Add(new ImageAnnotation { ImageSource = image2, Interpolate = true, Layer = AnnotationLayer.BelowAxes, X = new PlotLength(0, PlotLengthUnit.RelativeToViewport), Y = new PlotLength(0, PlotLengthUnit.RelativeToViewport), Width = new PlotLength(1, PlotLengthUnit.RelativeToViewport), Height = new PlotLength(1, PlotLengthUnit.RelativeToViewport), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); // gradient filling the plot area model.Annotations.Add(new ImageAnnotation { ImageSource = image1, Interpolate = true, Layer = AnnotationLayer.BelowAxes, X = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Width = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), Height = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); // verify that a series is rendered above the gradients model.Series.Add(new FunctionSeries(Math.Sin, 0, 7, 0.01)); return model; } [Example("ImageAnnotation - normal axes")] public static PlotModel ImageAnnotation_NormalAxes() { var model = new PlotModel { Title = "ImageAnnotation - normal axes" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); // create an image var pixels = new OxyColor[2, 2]; pixels[0, 0] = OxyColors.Blue; pixels[1, 0] = OxyColors.Yellow; pixels[0, 1] = OxyColors.Green; pixels[1, 1] = OxyColors.Red; var image = OxyImage.Create(pixels, ImageFormat.Png); model.Annotations.Add( new ImageAnnotation { ImageSource = image, Interpolate = false, X = new PlotLength(0, PlotLengthUnit.Data), Y = new PlotLength(0, PlotLengthUnit.Data), Width = new PlotLength(80, PlotLengthUnit.Data), Height = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); return model; } [Example("ImageAnnotation - reverse horizontal axis")] public static PlotModel ImageAnnotation_ReverseHorizontalAxis() { var model = new PlotModel { Title = "ImageAnnotation - reverse horizontal axis" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, StartPosition = 1, EndPosition = 0 }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); // create an image var pixels = new OxyColor[2, 2]; pixels[0, 0] = OxyColors.Blue; pixels[1, 0] = OxyColors.Yellow; pixels[0, 1] = OxyColors.Green; pixels[1, 1] = OxyColors.Red; var image = OxyImage.Create(pixels, ImageFormat.Png); model.Annotations.Add( new ImageAnnotation { ImageSource = image, Interpolate = false, X = new PlotLength(100, PlotLengthUnit.Data), Y = new PlotLength(0, PlotLengthUnit.Data), Width = new PlotLength(80, PlotLengthUnit.Data), Height = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); return model; } [Example("ImageAnnotation - reverse vertical axis")] public static PlotModel ImageAnnotation_ReverseVerticalAxis() { var model = new PlotModel { Title = "ImageAnnotation - reverse vertical axis" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, StartPosition = 1, EndPosition = 0 }); // create an image var pixels = new OxyColor[2, 2]; pixels[0, 0] = OxyColors.Blue; pixels[1, 0] = OxyColors.Yellow; pixels[0, 1] = OxyColors.Green; pixels[1, 1] = OxyColors.Red; var image = OxyImage.Create(pixels, ImageFormat.Png); model.Annotations.Add( new ImageAnnotation { ImageSource = image, Interpolate = false, X = new PlotLength(0, PlotLengthUnit.Data), Y = new PlotLength(100, PlotLengthUnit.Data), Width = new PlotLength(80, PlotLengthUnit.Data), Height = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); return model; } } }
// <copyright file=ColorRangeDrawer company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using Hydra.HydraCommon.Editor.Extensions; using Hydra.HydraCommon.Editor.Utils; using Hydra.HydraCommon.Extensions; using Hydra.HydraCommon.PropertyAttributes.RangeAttributes; using Hydra.HydraCommon.Utils; using UnityEditor; using UnityEngine; namespace Hydra.HydraCommon.Editor.Drawers.RangeDrawers { /// <summary> /// ColorRangeDrawer presents the ColorRangeAttribute in the inspector. /// </summary> [CustomPropertyDrawer(typeof(ColorRangeAttribute))] public class ColorRangeDrawer : PropertyDrawer { private static readonly GUIContent s_LinearLabel = new GUIContent("Linear", "When enabled a random color on the line between color " + "A and B will be chosen. When disabled each channel is randomised."); private static readonly GUIContent s_RandomBlendLabel = new GUIContent("Random Blend", "Determines the color-space in which random colors " + "are picked. HSL is good for yielding visually similar colors, " + "whereas RGB is useful when individual channels are important."); private static readonly GUIContent s_GradientWrapModeLabel = new GUIContent("Wrap Mode", "Determines how the gradient is extrapolated."); private static readonly GUIContent s_GradientLengthLabel = new GUIContent("Gradient Length", "Important when the gradient does not represent " + "a simple scale, for example a distance or time value."); private SerializedProperty m_RangeModeProperty; private SerializedProperty m_LinearProperty; private SerializedProperty m_GradientWrapModeProperty; private SerializedProperty m_GradientLengthProperty; private SerializedProperty m_RandomBlendProperty; private SerializedProperty m_ConstValueAProperty; private SerializedProperty m_ConstValueBProperty; private SerializedProperty m_GradientAProperty; private SerializedProperty m_GradientBProperty; /// <summary> /// Finds the properties. /// </summary> /// <param name="prop">Property.</param> private void FindProperties(SerializedProperty prop) { m_RangeModeProperty = prop.FindPropertyRelative("m_RangeMode"); m_LinearProperty = prop.FindPropertyRelative("m_Linear"); m_GradientWrapModeProperty = prop.FindPropertyRelative("m_GradientWrapMode"); m_GradientLengthProperty = prop.FindPropertyRelative("m_GradientLength"); m_RandomBlendProperty = prop.FindPropertyRelative("m_RandomBlend"); m_ConstValueAProperty = prop.FindPropertyRelative("m_ConstValueA"); m_ConstValueBProperty = prop.FindPropertyRelative("m_ConstValueB"); m_GradientAProperty = prop.FindPropertyRelative("m_GradientA"); m_GradientBProperty = prop.FindPropertyRelative("m_GradientB"); } #region Methods /// <summary> /// Override this method to make your own GUI for the property /// </summary> /// <param name="position">Position</param> /// <param name="prop">Property</param> /// <param name="label">Label</param> public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label) { label = EditorGUI.BeginProperty(position, label, prop); FindProperties(prop); position.height = EditorGUIUtility.singleLineHeight; position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); HydraEditorUtils.DrawUnindented( () => HydraEditorUtils.EnumPopupField<ColorRangeAttribute.RangeMode>(position, GUIContent.none, m_RangeModeProperty, HydraEditorGUIStyles.enumStyle)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; switch (m_RangeModeProperty.GetEnumValue<ColorRangeAttribute.RangeMode>()) { case ColorRangeAttribute.RangeMode.Constant: OnConstant(position); break; case ColorRangeAttribute.RangeMode.Gradient: OnGradient(position); break; case ColorRangeAttribute.RangeMode.RandomInGradient: OnRandomInGradient(position); break; case ColorRangeAttribute.RangeMode.RandomBetweenTwoConstants: OnRandomBetweenTwoConstants(position); break; case ColorRangeAttribute.RangeMode.RandomBetweenTwoGradients: OnRandomBetweenTwoGradients(position); break; default: throw new ArgumentOutOfRangeException(); } EditorGUI.EndProperty(); } /// <summary> /// Gets the height of the property. /// </summary> /// <returns>The property height.</returns> /// <param name="property">Property.</param> /// <param name="label">Label.</param> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { FindProperties(property); int lines; switch (m_RangeModeProperty.GetEnumValue<ColorRangeAttribute.RangeMode>()) { case ColorRangeAttribute.RangeMode.Constant: lines = 2; break; case ColorRangeAttribute.RangeMode.Gradient: lines = 4; break; case ColorRangeAttribute.RangeMode.RandomInGradient: lines = 2; break; case ColorRangeAttribute.RangeMode.RandomBetweenTwoConstants: lines = 4; break; case ColorRangeAttribute.RangeMode.RandomBetweenTwoGradients: lines = 6; break; default: throw new ArgumentOutOfRangeException(); } return EditorGUIUtility.singleLineHeight * lines + EditorGUIUtility.standardVerticalSpacing * (lines - 1); } #endregion /// <summary> /// Raises when constant has been selected. /// </summary> /// <param name="position">Position.</param> private void OnConstant(Rect position) { HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(position, m_ConstValueAProperty, GUIContent.none)); } /// <summary> /// Raises when Gradient has been selected. /// </summary> /// <param name="position">Position.</param> private void OnGradient(Rect position) { HydraEditorUtils.DrawUnindented(() => GradientWrapField(position)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; HydraEditorUtils.DrawUnindented( () => EditorGUI.PropertyField(position, m_GradientLengthProperty, s_GradientLengthLabel)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(position, m_GradientAProperty, GUIContent.none)); } /// <summary> /// Raises when Random In Gradient has been selected. /// </summary> /// <param name="position">Position.</param> private void OnRandomInGradient(Rect position) { HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(position, m_GradientAProperty, GUIContent.none)); } /// <summary> /// Raises when Random Between Two Constants has been selected. /// </summary> /// <param name="position">Position.</param> private void OnRandomBetweenTwoConstants(Rect position) { HydraEditorUtils.DrawUnindented(() => HydraEditorUtils.ToggleLeftField(position, s_LinearLabel, m_LinearProperty)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; HydraEditorUtils.DrawUnindented(() => RandomBlendField(position)); Rect gradientRect = new Rect(position); gradientRect.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; gradientRect.width = (gradientRect.width - HydraEditorUtils.STANDARD_HORIZONTAL_SPACING) / 2.0f; HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(gradientRect, m_ConstValueAProperty, GUIContent.none)); gradientRect.x += gradientRect.width; HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(gradientRect, m_ConstValueBProperty, GUIContent.none)); } /// <summary> /// Raises when Random Between Two Gradients has been selected. /// </summary> /// <param name="position">Position.</param> private void OnRandomBetweenTwoGradients(Rect position) { HydraEditorUtils.DrawUnindented(() => HydraEditorUtils.ToggleLeftField(position, s_LinearLabel, m_LinearProperty)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; HydraEditorUtils.DrawUnindented(() => RandomBlendField(position)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; HydraEditorUtils.DrawUnindented(() => GradientWrapField(position)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; HydraEditorUtils.DrawUnindented( () => EditorGUI.PropertyField(position, m_GradientLengthProperty, s_GradientLengthLabel)); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; Rect gradientRect = new Rect(position); gradientRect.width = (gradientRect.width - HydraEditorUtils.STANDARD_HORIZONTAL_SPACING) / 2.0f; HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(gradientRect, m_GradientAProperty, GUIContent.none)); gradientRect.x += gradientRect.width; HydraEditorUtils.DrawUnindented(() => EditorGUI.PropertyField(gradientRect, m_GradientBProperty, GUIContent.none)); } /// <summary> /// Gets the wrap mode. /// </summary> /// <returns>The wrap mode.</returns> /// <param name="property">Property.</param> private GradientExtensions.GradientWrapMode GetWrapMode(SerializedProperty property) { return (GradientExtensions.GradientWrapMode)property.enumValueIndex; } /// <summary> /// Draws the random blend field. /// </summary> /// <param name="position">Position.</param> private void RandomBlendField(Rect position) { HydraEditorUtils.EnumPopupField<ColorUtils.Gamut>(position, s_RandomBlendLabel, m_RandomBlendProperty, HydraEditorGUIStyles.enumStyle); } /// <summary> /// Draws the gradient wrap field. /// </summary> /// <param name="position">Position.</param> private void GradientWrapField(Rect position) { HydraEditorUtils.EnumPopupField<GradientExtensions.GradientWrapMode>(position, s_GradientWrapModeLabel, m_GradientWrapModeProperty, HydraEditorGUIStyles.enumStyle); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Examples { using System; using System.Linq; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Linq; /// <summary> /// This example populates cache with sample data and runs several LINQ queries over this data. /// </summary> public class LinqExample { /// <summary>Organization cache name.</summary> private const string OrganizationCacheName = "dotnet_cache_query_organization"; /// <summary>Employee cache name.</summary> private const string EmployeeCacheName = "dotnet_cache_query_employee"; /// <summary>Colocated employee cache name.</summary> private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated"; [STAThread] public static void Run() { var ignite = Ignition.TryGetIgnite() ?? Ignition.StartFromApplicationConfiguration(); Console.WriteLine(); Console.WriteLine(">>> Cache LINQ example started."); var employeeCache = ignite.GetOrCreateCache<int, Employee>( new CacheConfiguration(EmployeeCacheName, new QueryEntity(typeof(Employee)))); var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>( new CacheConfiguration(EmployeeCacheNameColocated, new QueryEntity(typeof(Employee)))); var organizationCache = ignite.GetOrCreateCache<int, Organization>( new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization)))); // Populate cache with sample data entries. PopulateCache(employeeCache); PopulateCache(employeeCacheColocated); PopulateCache(organizationCache); // Run SQL query example. QueryExample(employeeCache); // Run compiled SQL query example. CompiledQueryExample(employeeCache); // Run SQL query with join example. JoinQueryExample(employeeCacheColocated, organizationCache); // Run SQL query with distributed join example. DistributedJoinQueryExample(employeeCache, organizationCache); // Run SQL fields query example. FieldsQueryExample(employeeCache); } /// <summary> /// Queries employees that have specific salary. /// </summary> /// <param name="cache">Cache.</param> private static void QueryExample(ICache<int, Employee> cache) { const int minSalary = 10000; var qry = cache.AsCacheQueryable().Where(emp => emp.Value.Salary > minSalary); Console.WriteLine(); Console.WriteLine($">>> Employees with salary > {minSalary}:"); foreach (var entry in qry) Console.WriteLine(">>> " + entry.Value); Console.WriteLine(); Console.WriteLine(">>> Generated SQL: " + qry.ToCacheQueryable().GetFieldsQuery().Sql); } /// <summary> /// Queries employees that have specific salary with a compiled query. /// </summary> /// <param name="cache">Cache.</param> private static void CompiledQueryExample(ICache<int, Employee> cache) { const int minSalary = 10000; var cache0 = cache.AsCacheQueryable(); // Compile cache query to eliminate LINQ overhead on multiple runs. Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry = CompiledQuery.Compile((int ms) => cache0.Where(emp => emp.Value.Salary > ms)); Console.WriteLine(); Console.WriteLine($">>> Employees with salary > {minSalary} using compiled query:"); foreach (var entry in qry(minSalary)) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that work for organization with provided name. /// </summary> /// <param name="employeeCache">Employee cache.</param> /// <param name="organizationCache">Organization cache.</param> private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache, ICache<int, Organization> organizationCache) { const string orgName = "Apache"; var employees = employeeCache.AsCacheQueryable(); var organizations = organizationCache.AsCacheQueryable(); var qry = from employee in employees from organization in organizations where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName select employee; Console.WriteLine(); Console.WriteLine(">>> Employees working for " + orgName + ":"); foreach (var entry in qry) Console.WriteLine(">>> " + entry.Value); Console.WriteLine(); Console.WriteLine(">>> Generated SQL: " + qry.ToCacheQueryable().GetFieldsQuery().Sql); } /// <summary> /// Queries employees that work for organization with provided name. /// </summary> /// <param name="employeeCache">Employee cache.</param> /// <param name="organizationCache">Organization cache.</param> private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache, ICache<int, Organization> organizationCache) { const string orgName = "Apache"; var queryOptions = new QueryOptions {EnableDistributedJoins = true}; var employees = employeeCache.AsCacheQueryable(queryOptions); var organizations = organizationCache.AsCacheQueryable(queryOptions); var qry = from employee in employees from organization in organizations where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName select employee; Console.WriteLine(); Console.WriteLine(">>> Employees working for " + orgName + " (distributed joins):"); foreach (var entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries names and salaries for all employees. /// </summary> /// <param name="cache">Cache.</param> private static void FieldsQueryExample(ICache<int, Employee> cache) { var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary}); Console.WriteLine(); Console.WriteLine(">>> Employee names and their salaries:"); foreach (var row in qry) Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']'); Console.WriteLine(); Console.WriteLine(">>> Generated SQL: " + qry.ToCacheQueryable().GetFieldsQuery().Sql); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, Organization> cache) { cache.Put(1, new Organization("Apache")); cache.Put(2, new Organization("Microsoft")); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<AffinityKey, Employee> cache) { cache.Put(new AffinityKey(1, 1), new Employee("James Wilson", 12500, 1)); cache.Put(new AffinityKey(2, 1), new Employee("Daniel Adams", 11000, 1)); cache.Put(new AffinityKey(3, 1), new Employee("Cristian Moss", 12500, 1)); cache.Put(new AffinityKey(4, 2), new Employee("Allison Mathis", 25300, 2)); cache.Put(new AffinityKey(5, 2), new Employee("Breana Robbin", 6500, 2)); cache.Put(new AffinityKey(6, 2), new Employee("Philip Horsley", 19800, 2)); cache.Put(new AffinityKey(7, 2), new Employee("Brian Peters", 10600, 2)); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, Employee> cache) { cache.Put(1, new Employee("James Wilson", 12500, 1)); cache.Put(2, new Employee("Daniel Adams", 11000, 1)); cache.Put(3, new Employee("Cristian Moss", 12500, 1)); cache.Put(4, new Employee("Allison Mathis", 25300, 2)); cache.Put(5, new Employee("Breana Robbin", 6500, 2)); cache.Put(6, new Employee("Philip Horsley", 19800, 2)); cache.Put(7, new Employee("Brian Peters", 10600, 2)); } } }
// 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.Diagnostics; using System.IO.PortsTests; using System.Threading; using Legacy.Support; using Xunit; using Xunit.NetCore.Extensions; using ThreadState = System.Threading.ThreadState; namespace System.IO.Ports.Tests { public class SerialStream_WriteTimeout_Property : PortsTest { // The default number of bytes to write with when testing timeout with Write(byte[], int, int) private static readonly int s_DEFAULT_WRITE_BYTE_ARRAY_SIZE = TCSupport.MinimumBlockingByteCount; // The large number of bytes to write with when testing timeout with Write(byte[], int, int) // This needs to be large enough for Write timeout private const int DEFAULT_WRITE_BYTE_LARGE_ARRAY_SIZE = 1024 * 100; // The BaudRate to use to make Write timeout when writing DEFAULT_WRITE_BYTE_LARGE_ARRAY_SIZE bytes private const int LARGEWRITE_BAUDRATE = 1200; // The timeout to use to make Write timeout when writing DEFAULT_WRITE_BYTE_LARGE_ARRAY_SIZE private const int LARGEWRITE_TIMEOUT = 750; // The default byte to call with WriteByte private const byte DEFAULT_WRITE_BYTE = 33; // The amount of time to wait when expecting an long timeout private const int DEFAULT_WAIT_LONG_TIMEOUT = 250; // The maximum acceptable time allowed when a write method should timeout immediately private const int MAX_ACCEPTABLE_ZERO_TIMEOUT = 100; // The maximum acceptable time allowed when a write method should timeout immediately when it is called for the first time private const int MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT = 1000; // The maximum acceptable percentage difference allowed when a write method is called for the first time private const double MAX_ACCEPTABLE_WARMUP_PERCENTAGE_DIFFERENCE = .5; // The maximum acceptable percentage difference allowed private const double MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE = .15; private const int SUCCESSIVE_WriteTimeout_SOMEDATA = 950; private const int NUM_TRYS = 5; private delegate void WriteMethodDelegate(Stream stream); #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void WriteTimeout_DefaultValue() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); Stream stream = com.BaseStream; Debug.WriteLine("Verifying the default value of WriteTimeout"); Assert.True(stream.WriteTimeout == -1, string.Format( "Err_1707azhpbn Verifying the default value of WriteTimeout Expected={0} Actual={1} FAILED", -1, stream.WriteTimeout)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteTimeout_AfterClose() { Debug.WriteLine("Verifying setting WriteTimeout after the SerialPort was closed"); VerifyException(2048, null, typeof(ObjectDisposedException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteTimeout_Int32MinValue() { Debug.WriteLine("Verifying Int32.MinValue WriteTimeout"); VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteTimeout_NEG2() { Debug.WriteLine("Verifying -2 WriteTimeout"); VerifyException(-2, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteTimeout_ZERO() { Debug.WriteLine("Verifying 0 WriteTimeout"); VerifyException(0, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_Default_Write_byte_int_int() { Debug.WriteLine("Verifying default WriteTimeout with Write(byte[] buffer, int offset, int count)"); VerifyDefaultTimeout(Write_byte_int_int); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasSingleByteTransmitBlocking))] public void WriteTimeout_Default_WriteByte() { Debug.WriteLine("Verifying default WriteTimeout with WriteByte()"); VerifyDefaultTimeout(WriteByte); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_Infinite_Write_byte_int_int() { Debug.WriteLine("Verifying infinite WriteTimeout with Write(byte[] buffer, int offset, int count)"); VerifyLongTimeout(Write_byte_int_int, -1); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasSingleByteTransmitBlocking))] public void WriteTimeout_Infinite_WriteByte() { Debug.WriteLine("Verifying infinite WriteTimeout with WriteByte()"); VerifyLongTimeout(WriteByte, -1); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_Int32MaxValue_Write_byte_int_int() { Debug.WriteLine("Verifying Int32.MaxValue WriteTimeout with Write(byte[] buffer, int offset, int count)"); VerifyLongTimeout(Write_byte_int_int, int.MaxValue - 1); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasSingleByteTransmitBlocking))] public void WriteTimeout_Int32MaxValue_WriteByte() { Debug.WriteLine("Verifying Int32.MaxValue WriteTimeout with WriteByte()"); VerifyLongTimeout(WriteByte, int.MaxValue - 1); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_750_Write_byte_int_int() { Debug.WriteLine("Verifying 750 WriteTimeout with Write(byte[] buffer, int offset, int count)"); VerifyTimeout(Write_byte_int_int, 750); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasSingleByteTransmitBlocking))] public void WriteTimeout_750_WriteByte() { Debug.WriteLine("Verifying 750 WriteTimeout with WriteByte()"); VerifyTimeout(WriteByte, 750); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveWriteTimeoutNoData_Write_byte_int_int() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); com.Handshake = Handshake.RequestToSend; Stream stream = com.BaseStream; stream.WriteTimeout = 850; Debug.WriteLine("Verifying WriteTimeout={0} with successive call to Write(byte[], int, int) and no data", stream.WriteTimeout); Assert.Throws<TimeoutException>(() => stream.Write(new byte[s_DEFAULT_WRITE_BYTE_ARRAY_SIZE], 0, s_DEFAULT_WRITE_BYTE_ARRAY_SIZE)); VerifyTimeout(Write_byte_int_int, stream); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveWriteTimeoutSomeData_Write_byte_int_int() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var asyncEnableRts = new AsyncEnableRts(); var t = new Thread(asyncEnableRts.EnableRTS); int waitTime; com1.Open(); com1.Handshake = Handshake.RequestToSend; Stream stream = com1.BaseStream; stream.WriteTimeout = SUCCESSIVE_WriteTimeout_SOMEDATA; Debug.WriteLine( "Verifying WriteTimeout={0} with successive call to Write(byte[], int, int) and some data being received in the first call", stream.WriteTimeout); // Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed // before the timeout is reached t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { // Wait for the thread to start Thread.Sleep(50); waitTime += 50; } try { stream.Write(new byte[s_DEFAULT_WRITE_BYTE_ARRAY_SIZE], 0, s_DEFAULT_WRITE_BYTE_ARRAY_SIZE); } catch (TimeoutException) { } asyncEnableRts.Stop(); // Wait for the thread to finish while (t.IsAlive) Thread.Sleep(50); // Make sure there is no bytes in the buffer so the next call to write will timeout com1.DiscardInBuffer(); VerifyTimeout(Write_byte_int_int, stream); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasSingleByteTransmitBlocking))] public void SuccessiveWriteTimeoutNoData_WriteByte() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); com.Handshake = Handshake.RequestToSend; Stream stream = com.BaseStream; stream.WriteTimeout = 850; Debug.WriteLine("Verifying WriteTimeout={0} with successive call to WriteByte() and no data", stream.WriteTimeout); Assert.Throws<TimeoutException>(() => stream.WriteByte(DEFAULT_WRITE_BYTE)); VerifyTimeout(WriteByte, stream); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveWriteTimeoutSomeData_WriteByte() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var asyncEnableRts = new AsyncEnableRts(); var t = new Thread(asyncEnableRts.EnableRTS); int waitTime; com1.Open(); com1.Handshake = Handshake.RequestToSend; Stream stream = com1.BaseStream; stream.WriteTimeout = SUCCESSIVE_WriteTimeout_SOMEDATA; Debug.WriteLine( "Verifying WriteTimeout={0} with successive call to WriteByte() and some data being received in the first call", stream.WriteTimeout); // Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed // before the timeout is reached t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { // Wait for the thread to start Thread.Sleep(50); waitTime += 50; } try { stream.WriteByte(DEFAULT_WRITE_BYTE); } catch (TimeoutException) { } asyncEnableRts.Stop(); // Wait for the thread to finish while (t.IsAlive) Thread.Sleep(50); // Make sure there is no bytes in the buffer so the next call to write will timeout com1.DiscardInBuffer(); VerifyTimeout(WriteByte, stream); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_0_Write_byte_int_int() { Debug.WriteLine("Verifying 0 WriteTimeout with Write(byte[] buffer, int offset, int count)"); Verify0Timeout(Write_byte_int_int); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_0_WriteByte() { Debug.WriteLine("Verifying 0 WriteTimeout with WriteByte()"); Verify0Timeout(WriteByte); } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void WriteTimeout_LargeWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); com.BaudRate = LARGEWRITE_BAUDRATE; com.Handshake = Handshake.RequestToSend; Stream stream = com.BaseStream; stream.WriteTimeout = LARGEWRITE_TIMEOUT; Debug.WriteLine("Verifying {0} WriteTimeout with Write(byte[] , int, int) and writing {1} bytes", LARGEWRITE_TIMEOUT, DEFAULT_WRITE_BYTE_LARGE_ARRAY_SIZE); VerifyTimeout(Write_byte_int_int_Large, stream); } } private class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { int sleepPeriod = SUCCESSIVE_WriteTimeout_SOMEDATA / 2; // Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } #endregion #region Verification for Test Cases private void VerifyDefaultTimeout(WriteMethodDelegate writeMethod) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) { Debug.WriteLine("Serial port being used : " + com1.PortName); com1.Open(); com1.Handshake = Handshake.RequestToSend; com1.BaseStream.ReadTimeout = 1; Assert.Equal(-1, com1.BaseStream.WriteTimeout); VerifyLongTimeout(writeMethod, com1); } } private void VerifyLongTimeout(WriteMethodDelegate writeMethod, int writeTimeout) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) { com1.Open(); com1.Handshake = Handshake.RequestToSend; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.WriteTimeout = 1; com1.BaseStream.WriteTimeout = writeTimeout; Assert.Equal(writeTimeout, com1.BaseStream.WriteTimeout); VerifyLongTimeout(writeMethod, com1); } } private void VerifyLongTimeout(WriteMethodDelegate writeMethod, SerialPort com1) { var writeThread = new WriteDelegateThread(com1.BaseStream, writeMethod); var t = new Thread(writeThread.CallWrite); t.Start(); Thread.Sleep(DEFAULT_WAIT_LONG_TIMEOUT); Assert.True(t.IsAlive, string.Format("Err_17071ahpa!!! {0} terminated with a long timeout of {1}ms", writeMethod.Method.Name, com1.BaseStream.WriteTimeout)); com1.Handshake = Handshake.None; while (t.IsAlive) Thread.Sleep(10); } private void VerifyTimeout(WriteMethodDelegate writeMethod, int WriteTimeout) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com1.Open(); com1.Handshake = Handshake.RequestToSend; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.WriteTimeout = 1; com1.BaseStream.WriteTimeout = WriteTimeout; Assert.Equal(WriteTimeout, com1.BaseStream.WriteTimeout); VerifyTimeout(writeMethod, com1.BaseStream); } } private void VerifyTimeout(WriteMethodDelegate writeMethod, Stream stream) { var timer = new Stopwatch(); int expectedTime = stream.WriteTimeout; int actualTime; double percentageDifference; // Warmup the write method. When called for the first time the write method seems to take much longer then subsequent calls timer.Start(); try { writeMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime = (int)timer.ElapsedMilliseconds; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference Assert.True(percentageDifference <= MAX_ACCEPTABLE_WARMUP_PERCENTAGE_DIFFERENCE, string.Format("Err_88558amuph!!!: The write method timedout in {0} expected {1} percentage difference: {2} when called for the first time", actualTime, expectedTime, percentageDifference)); actualTime = 0; timer.Reset(); // Perform the actual test verifying that the write method times out in approximately WriteTimeout milliseconds Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { writeMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference Assert.True(percentageDifference <= MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE, string.Format("Err_56485ahpbz!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference)); } private void Verify0Timeout(WriteMethodDelegate writeMethod) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com1.Open(); com1.Handshake = Handshake.RequestToSend; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.WriteTimeout = 1; com1.BaseStream.WriteTimeout = 1; Assert.Equal(1, com1.BaseStream.WriteTimeout); Verify0Timeout(writeMethod, com1.BaseStream); } } private void Verify0Timeout(WriteMethodDelegate writeMethod, Stream stream) { var timer = new Stopwatch(); int actualTime; // Warmup the write method. When called for the first time the write method seems to take much longer then subsequent calls timer.Start(); try { writeMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime = (int)timer.ElapsedMilliseconds; // Verify that the time the method took to timeout is less then the maximum acceptable time Assert.True(actualTime <= MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT, string.Format("Err_277a0ahpsb!!!: With a timeout of 0 the write method timedout in {0} expected something less then {1} when called for the first time", actualTime, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT)); actualTime = 0; timer.Reset(); // Perform the actual test verifying that the write method times out in approximately WriteTimeout milliseconds Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { writeMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; // Verify that the time the method took to timeout is less then the maximum acceptable time Assert.True(actualTime <= MAX_ACCEPTABLE_ZERO_TIMEOUT, string.Format("Err_112389ahbp!!!: With a timeout of 0 the write method timedout in {0} expected something less then {1}", actualTime, MAX_ACCEPTABLE_ZERO_TIMEOUT)); } private void VerifyException(int readTimeout, Type expectedException) { VerifyException(readTimeout, expectedException, expectedException); } private void VerifyException(int readTimeout, Type expectedExceptionAfterOpen, Type expectedExceptionAfterClose) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); Stream stream = com.BaseStream; VerifyException(stream, readTimeout, expectedExceptionAfterOpen); com.Close(); VerifyException(stream, readTimeout, expectedExceptionAfterClose); } } private void VerifyException(Stream stream, int WriteTimeout, Type expectedException) { int origWriteTimeout = stream.WriteTimeout; if (expectedException == null) { stream.WriteTimeout = WriteTimeout; Assert.Equal(WriteTimeout, stream.WriteTimeout); } else { Assert.Throws(expectedException, () => stream.WriteTimeout = WriteTimeout); Assert.Equal(origWriteTimeout, stream.WriteTimeout); } } private void Write_byte_int_int(Stream stream) { stream.Write(new byte[s_DEFAULT_WRITE_BYTE_ARRAY_SIZE], 0, s_DEFAULT_WRITE_BYTE_ARRAY_SIZE); } private void Write_byte_int_int_Large(Stream stream) { stream.Write(new byte[DEFAULT_WRITE_BYTE_LARGE_ARRAY_SIZE], 0, DEFAULT_WRITE_BYTE_LARGE_ARRAY_SIZE); } private void WriteByte(Stream stream) { stream.WriteByte(DEFAULT_WRITE_BYTE); } private class WriteDelegateThread { public WriteDelegateThread(Stream stream, WriteMethodDelegate writeMethod) { _stream = stream; _writeMethod = writeMethod; } public void CallWrite() { _writeMethod(_stream); } private readonly WriteMethodDelegate _writeMethod; private readonly Stream _stream; } #endregion } }
using System; using System.Diagnostics; using System.Text; namespace CleanSqlite { public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that splits an SQL input string up into ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <stdlib.h> /* ** The charMap() macro maps alphabetic characters into their ** lower-case ASCII equivalent. On ASCII machines, this is just ** an upper-to-lower case map. On EBCDIC machines we also need ** to adjust the encoding. Only alphabetic characters and underscores ** need to be translated. */ #if SQLITE_ASCII //# define charMap(X) sqlite3UpperToLower[(unsigned char)X] #endif //#if SQLITE_EBCDIC //# define charMap(X) ebcdicToAscii[(unsigned char)X] //const unsigned char ebcdicToAscii[] = { ///* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ // 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ // 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ // 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ // 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ // 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ // 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ //}; //#endif /* ** The sqlite3KeywordCode function looks up an identifier to determine if ** it is a keyword. If it is a keyword, the token code of that keyword is ** returned. If the input is not a keyword, TK_ID is returned. ** ** The implementation of this routine was generated by a program, ** mkkeywordhash.h, located in the tool subdirectory of the distribution. ** The output of the mkkeywordhash.c program is written into a file ** named keywordhash.h and then included into this source file by ** the #include below. */ //#include "keywordhash.h" /* ** If X is a character that can be used in an identifier then ** IdChar(X) will be true. Otherwise it is false. ** ** For ASCII, any character with the high-order bit set is ** allowed in an identifier. For 7-bit characters, ** sqlite3IsIdChar[X] must be 1. ** ** For EBCDIC, the rules are more complex but have the same ** end result. ** ** Ticket #1066. the SQL standard does not allow '$' in the ** middle of identfiers. But many SQL implementations do. ** SQLite will allow '$' in identifiers for compatibility. ** But the feature is undocumented. */ #if SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif //#if SQLITE_EBCDIC //const char sqlite3IsEbcdicIdChar[] = { ///* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ // 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ // 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ //}; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) //#endif /* ** Return the length of the token that begins at z[iOffset + 0]. ** Store the token type in *tokenType before returning. */ static int sqlite3GetToken( string z, int iOffset, ref int tokenType ) { int i; byte c = 0; switch ( z[iOffset + 0] ) { case ' ': case '\t': case '\n': case '\f': case '\r': { testcase( z[iOffset + 0] == ' ' ); testcase( z[iOffset + 0] == '\t' ); testcase( z[iOffset + 0] == '\n' ); testcase( z[iOffset + 0] == '\f' ); testcase( z[iOffset + 0] == '\r' ); for ( i = 1; z.Length > iOffset + i && sqlite3Isspace( z[iOffset + i] ); i++ ) { } tokenType = TK_SPACE; return i; } case '-': { if ( z.Length > iOffset + 1 && z[iOffset + 1] == '-' ) { /* IMP: R-15891-05542 -- syntax diagram for comments */ for ( i = 2; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0 && c != '\n'; i++ ) { } tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } tokenType = TK_MINUS; return 1; } case '(': { tokenType = TK_LP; return 1; } case ')': { tokenType = TK_RP; return 1; } case ';': { tokenType = TK_SEMI; return 1; } case '+': { tokenType = TK_PLUS; return 1; } case '*': { tokenType = TK_STAR; return 1; } case '/': { if ( iOffset + 2 >= z.Length || z[iOffset + 1] != '*' ) { tokenType = TK_SLASH; return 1; } /* IMP: R-15891-05542 -- syntax diagram for comments */ for ( i = 3, c = (byte)z[iOffset + 2]; iOffset + i < z.Length && ( c != '*' || ( z[iOffset + i] != '/' ) && ( c != 0 ) ); i++ ) { c = (byte)z[iOffset + i]; } if ( iOffset + i == z.Length ) c = 0; if ( c != 0 ) i++; tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } case '%': { tokenType = TK_REM; return 1; } case '=': { tokenType = TK_EQ; return 1 + ( z[iOffset + 1] == '=' ? 1 : 0 ); } case '<': { if ( ( c = (byte)z[iOffset + 1] ) == '=' ) { tokenType = TK_LE; return 2; } else if ( c == '>' ) { tokenType = TK_NE; return 2; } else if ( c == '<' ) { tokenType = TK_LSHIFT; return 2; } else { tokenType = TK_LT; return 1; } } case '>': { if ( z.Length > iOffset + 1 && ( c = (byte)z[iOffset + 1] ) == '=' ) { tokenType = TK_GE; return 2; } else if ( c == '>' ) { tokenType = TK_RSHIFT; return 2; } else { tokenType = TK_GT; return 1; } } case '!': { if ( z[iOffset + 1] != '=' ) { tokenType = TK_ILLEGAL; return 2; } else { tokenType = TK_NE; return 2; } } case '|': { if ( z[iOffset + 1] != '|' ) { tokenType = TK_BITOR; return 1; } else { tokenType = TK_CONCAT; return 2; } } case ',': { tokenType = TK_COMMA; return 1; } case '&': { tokenType = TK_BITAND; return 1; } case '~': { tokenType = TK_BITNOT; return 1; } case '`': case '\'': case '"': { int delim = z[iOffset + 0]; testcase( delim == '`' ); testcase( delim == '\'' ); testcase( delim == '"' ); for ( i = 1; ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { if ( c == delim ) { if ( z.Length > iOffset + i + 1 && z[iOffset + i + 1] == delim ) { i++; } else { break; } } } if ( ( iOffset + i == z.Length && c != delim ) || z[iOffset + i] != delim ) { tokenType = TK_ILLEGAL; return i + 1; } if ( c == '\'' ) { tokenType = TK_STRING; return i + 1; } else if ( c != 0 ) { tokenType = TK_ID; return i + 1; } else { tokenType = TK_ILLEGAL; return i; } } case '.': { #if !SQLITE_OMIT_FLOATING_POINT if ( !sqlite3Isdigit( z[iOffset + 1] ) ) #endif { tokenType = TK_DOT; return 1; } /* If the next character is a digit, this is a floating point ** number that begins with ".". Fall thru into the next case */ goto case '0'; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { testcase( z[iOffset] == '0' ); testcase( z[iOffset] == '1' ); testcase( z[iOffset] == '2' ); testcase( z[iOffset] == '3' ); testcase( z[iOffset] == '4' ); testcase( z[iOffset] == '5' ); testcase( z[iOffset] == '6' ); testcase( z[iOffset] == '7' ); testcase( z[iOffset] == '8' ); testcase( z[iOffset] == '9' ); tokenType = TK_INTEGER; for ( i = 0; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } #if !SQLITE_OMIT_FLOATING_POINT if ( z.Length > iOffset + i && z[iOffset + i] == '.' ) { i++; while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) ) { i++; } tokenType = TK_FLOAT; } if ( z.Length > iOffset + i + 1 && ( z[iOffset + i] == 'e' || z[iOffset + i] == 'E' ) && ( sqlite3Isdigit( z[iOffset + i + 1] ) || z.Length > iOffset + i + 2 && ( ( z[iOffset + i + 1] == '+' || z[iOffset + i + 1] == '-' ) && sqlite3Isdigit( z[iOffset + i + 2] ) ) ) ) { i += 2; while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) ) { i++; } tokenType = TK_FLOAT; } #endif while ( iOffset + i < z.Length && IdChar( (byte)z[iOffset + i] ) ) { tokenType = TK_ILLEGAL; i++; } return i; } case '[': { for ( i = 1, c = (byte)z[iOffset + 0]; c != ']' && ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { } tokenType = c == ']' ? TK_ID : TK_ILLEGAL; return i; } case '?': { tokenType = TK_VARIABLE; for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } return i; } case '#': { for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } if ( i > 1 ) { /* Parameters of the form #NNN (where NNN is a number) are used ** internally by sqlite3NestedParse. */ tokenType = TK_REGISTER; return i; } /* Fall through into the next case if the '#' is not followed by ** a digit. Try to match #AAAA where AAAA is a parameter name. */ goto case ':'; } #if !SQLITE_OMIT_TCL_VARIABLE case '$': #endif case '@': /* For compatibility with MS SQL Server */ case ':': { int n = 0; testcase( z[iOffset + 0] == '$' ); testcase( z[iOffset + 0] == '@' ); testcase( z[iOffset + 0] == ':' ); tokenType = TK_VARIABLE; for ( i = 1; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { if ( IdChar( c ) ) { n++; #if !SQLITE_OMIT_TCL_VARIABLE } else if ( c == '(' && n > 0 ) { do { i++; } while ( ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0 && !sqlite3Isspace( c ) && c != ')' ); if ( c == ')' ) { i++; } else { tokenType = TK_ILLEGAL; } break; } else if ( c == ':' && z[iOffset + i + 1] == ':' ) { i++; #endif } else { break; } } if ( n == 0 ) tokenType = TK_ILLEGAL; return i; } #if !SQLITE_OMIT_BLOB_LITERAL case 'x': case 'X': { testcase( z[iOffset + 0] == 'x' ); testcase( z[iOffset + 0] == 'X' ); if ( z.Length > iOffset + 1 && z[iOffset + 1] == '\'' ) { tokenType = TK_BLOB; for ( i = 2; z.Length > iOffset + i && sqlite3Isxdigit( z[iOffset + i] ); i++ ) { } if ( iOffset + i == z.Length || z[iOffset + i] != '\'' || i % 2 != 0 ) { tokenType = TK_ILLEGAL; while ( z.Length > iOffset + i && z[iOffset + i] != '\'' ) { i++; } } if ( z.Length > iOffset + i ) i++; return i; } goto default; /* Otherwise fall through to the next case */ } #endif default: { if ( !IdChar( (byte)z[iOffset] ) ) { break; } for ( i = 1; i < z.Length - iOffset && IdChar( (byte)z[iOffset + i] ); i++ ) { } tokenType = keywordCode( z, iOffset, i ); return i; } } tokenType = TK_ILLEGAL; return 1; } /* ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs ** then an and attempt is made to write an error message into ** memory obtained from sqlite3_malloc() and to make pzErrMsg point to that ** error message. */ static int sqlite3RunParser( Parse pParse, string zSql, ref string pzErrMsg ) { int nErr = 0; /* Number of errors encountered */ int i; /* Loop counter */ yyParser pEngine; /* The LEMON-generated LALR(1) parser */ int tokenType = 0; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ byte enableLookaside; /* Saved value of db->lookaside.bEnabled */ sqlite3 db = pParse.db; /* The database connection */ int mxSqlLen; /* Max length of an SQL string */ mxSqlLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; if ( db.activeVdbeCnt == 0 ) { db.u1.isInterrupted = false; } pParse.rc = SQLITE_OK; pParse.zTail = new StringBuilder( zSql ); i = 0; Debug.Assert( pzErrMsg != null ); pEngine = sqlite3ParserAlloc();//sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc); //if ( pEngine == null ) //{ // db.mallocFailed = 1; // return SQLITE_NOMEM; //} Debug.Assert( pParse.pNewTable == null ); Debug.Assert( pParse.pNewTrigger == null ); Debug.Assert( pParse.nVar == 0 ); Debug.Assert( pParse.nzVar == 0 ); Debug.Assert( pParse.azVar == null ); enableLookaside = db.lookaside.bEnabled; if ( db.lookaside.pStart != 0 ) db.lookaside.bEnabled = 1; while ( /* 0 == db.mallocFailed && */ i < zSql.Length ) { Debug.Assert( i >= 0 ); //pParse->sLastToken.z = &zSql[i]; pParse.sLastToken.n = sqlite3GetToken( zSql, i, ref tokenType ); pParse.sLastToken.z = zSql.Substring( i ); i += pParse.sLastToken.n; if ( i > mxSqlLen ) { pParse.rc = SQLITE_TOOBIG; break; } switch ( tokenType ) { case TK_SPACE: { if ( db.u1.isInterrupted ) { sqlite3ErrorMsg( pParse, "interrupt" ); pParse.rc = SQLITE_INTERRUPT; goto abort_parse; } break; } case TK_ILLEGAL: { sqlite3DbFree( db, ref pzErrMsg ); pzErrMsg = sqlite3MPrintf( db, "unrecognized token: \"%T\"", (object)pParse.sLastToken ); nErr++; goto abort_parse; } case TK_SEMI: { //pParse.zTail = new StringBuilder(zSql.Substring( i,zSql.Length-i )); /* Fall thru into the default case */ goto default; } default: { sqlite3Parser( pEngine, tokenType, pParse.sLastToken, pParse ); lastTokenParsed = tokenType; if ( pParse.rc != SQLITE_OK ) { goto abort_parse; } break; } } } abort_parse: pParse.zTail = new StringBuilder( zSql.Length <= i ? "" : zSql.Substring( i, zSql.Length - i ) ); if ( zSql.Length >= i && nErr == 0 && pParse.rc == SQLITE_OK ) { if ( lastTokenParsed != TK_SEMI ) { sqlite3Parser( pEngine, TK_SEMI, pParse.sLastToken, pParse ); } sqlite3Parser( pEngine, 0, pParse.sLastToken, pParse ); } #if YYTRACKMAXSTACKDEPTH sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK, sqlite3ParserStackPeak(pEngine) ); #endif //* YYDEBUG */ sqlite3ParserFree( pEngine, null );//sqlite3_free ); db.lookaside.bEnabled = enableLookaside; //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if ( pParse.rc != SQLITE_OK && pParse.rc != SQLITE_DONE && pParse.zErrMsg == "" ) { sqlite3SetString( ref pParse.zErrMsg, db, sqlite3ErrStr( pParse.rc ) ); } //assert( pzErrMsg!=0 ); if ( pParse.zErrMsg != null ) { pzErrMsg = pParse.zErrMsg; sqlite3_log( pParse.rc, "%s", pzErrMsg ); pParse.zErrMsg = ""; nErr++; } if ( pParse.pVdbe != null && pParse.nErr > 0 && pParse.nested == 0 ) { sqlite3VdbeDelete( ref pParse.pVdbe ); pParse.pVdbe = null; } #if !SQLITE_OMIT_SHARED_CACHE if ( pParse.nested == 0 ) { sqlite3DbFree( db, ref pParse.aTableLock ); pParse.aTableLock = null; pParse.nTableLock = 0; } #endif #if !SQLITE_OMIT_VIRTUALTABLE pParse.apVtabLock = null;//sqlite3_free( pParse.apVtabLock ); #endif if ( !IN_DECLARE_VTAB(pParse) ) { /* If the pParse.declareVtab flag is set, do not delete any table ** structure built up in pParse.pNewTable. The calling code (see vtab.c) ** will take responsibility for freeing the Table structure. */ sqlite3DeleteTable( db, ref pParse.pNewTable ); } #if !SQLITE_OMIT_TRIGGER sqlite3DeleteTrigger( db, ref pParse.pNewTrigger ); #endif //for ( i = pParse.nzVar - 1; i >= 0; i-- ) // sqlite3DbFree( db, pParse.azVar[i] ); sqlite3DbFree( db, ref pParse.azVar ); sqlite3DbFree( db, ref pParse.aAlias ); while ( pParse.pAinc != null ) { AutoincInfo p = pParse.pAinc; pParse.pAinc = p.pNext; sqlite3DbFree( db, ref p ); } while ( pParse.pZombieTab != null ) { Table p = pParse.pZombieTab; pParse.pZombieTab = p.pNextZombie; sqlite3DeleteTable( db, ref p ); } if ( nErr > 0 && pParse.rc == SQLITE_OK ) { pParse.rc = SQLITE_ERROR; } return nErr; } } }
/* * BmpResizer.cs - Implementation of the "DotGNU.Images.BmpResizer" class. * * Copyright (C) 2003 Neil Cawse. * * 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 DotGNU.Images { using System; internal sealed class BmpResizer { public static Frame Resize(Frame originalFrame, int x, int y, int width, int height, int destWidth, int destHeight) { Frame newFrame = originalFrame.CloneFrameEmpty(destWidth, destHeight, originalFrame.pixelFormat); newFrame.data = new byte[newFrame.Height * newFrame.Stride]; if (originalFrame.Palette != null) { newFrame.Palette = (int[])originalFrame.Palette.Clone(); } if (destWidth <= width && destHeight <= height) { ShrinkBmp(originalFrame, newFrame, x, y, width, height); } else if (destWidth>= width && destHeight >= height) { ExpandBmp(originalFrame, newFrame, x, y, width, height); } else if (destWidth < width) { //TODO: Currently this is a two pass operation. // A temporary frame to hold the partially resized data Frame f = new Frame(null, destWidth, height, originalFrame.pixelFormat); ShrinkBmp(originalFrame, f, x, y, width, height); ExpandBmp(f, newFrame, 0, 0, destWidth, height); } else if (destHeight < height) { //TODO: currently this is a two pass operation. // A temporary frame to hold the partially resized data Frame f = new Frame(null, width, destHeight, originalFrame.pixelFormat); ShrinkBmp(originalFrame, f, x, y, width, height); ExpandBmp(f, newFrame, 0, 0, width, destHeight); } return newFrame; } // This is an integer, generic, low quality algorithm for expanding bitmaps. // A significant speed improvement could be optained by splitting out 1bpp & 4 bpp // Eliminating the many if's. private static void ExpandBmp(Frame oldFrame, Frame newFrame, int oldX, int oldY, int oldWidth, int oldHeight) { byte[] data = oldFrame.Data; byte[] dataOut = newFrame.Data; int sumY = 0; int lineStartNew = 0; int bytesPerPixel = Utils.FormatToBitCount(oldFrame.pixelFormat) / 8; int lineStartBit = 0; bool lineStartNibble = false; // Offset to the oldY. int lineStartOld = oldY * oldFrame.Stride; if (oldFrame.pixelFormat == PixelFormat.Format1bppIndexed) { lineStartOld = oldX / 8; lineStartBit = 7 - (oldX & 0x07); } else if (oldFrame.pixelFormat == PixelFormat.Format4bppIndexed) { lineStartOld = oldX / 2; lineStartNibble = ((oldX & 0x01) == 0); } else { lineStartOld =bytesPerPixel * oldX; } int y = 0; while(y < oldHeight) { int newPixel = lineStartNew; int newPixelBit = 7; bool newPixelNibble = true; int newPixelByte = 0; lineStartNew += newFrame.Stride; int oldPixelBit = lineStartBit; int oldPixel = lineStartOld; int oldPixelByte = -1; bool oldPixelNibble = lineStartNibble; int pix = 0; int x = 0; int sumX = 0; while(x < oldWidth) { sumX += oldWidth; // Write the pixel. // 1bpp format. if (oldFrame.pixelFormat == PixelFormat.Format1bppIndexed) { if (oldPixelByte == -1) oldPixelByte = data[oldPixel]; if ( (oldPixelByte & 1<<oldPixelBit) != 0) newPixelByte |= 1<<newPixelBit; if (newPixelBit == 0) { dataOut[newPixel++] = (byte)(newPixelByte); newPixelBit = 7; newPixelByte = 0; } else newPixelBit--; if(sumX >= newFrame.Width) { x++; // Get the next nibble if (oldPixelBit==0) { oldPixelByte = -1; oldPixel++; oldPixelBit = 7; } else oldPixelBit--; sumX -= newFrame.Width; } } // 4bpp format. else if (oldFrame.pixelFormat == PixelFormat.Format4bppIndexed) { if (oldPixelByte == -1) oldPixelByte = data[oldPixel]; if (oldPixelNibble) pix = oldPixelByte >> 4; else pix = oldPixelByte & 0x0F; if (newPixelNibble) newPixelByte = pix << 4; else dataOut[newPixel++] = (byte)(newPixelByte | pix); newPixelNibble = !newPixelNibble; if(sumX >= newFrame.Width) { x++; // Get the next nibble if (!oldPixelNibble) { oldPixelByte = -1; oldPixel++; } oldPixelNibble = !oldPixelNibble; sumX -= newFrame.Width; } } // All other formats. else { for(int i = 0; i < bytesPerPixel; i++, newPixel++) dataOut[newPixel] = data[oldPixel + i]; if(sumX >= newFrame.Width) { x++; oldPixel += bytesPerPixel; sumX -= newFrame.Width; } } } // There maybe some bits left we need to write if (oldFrame.pixelFormat == PixelFormat.Format1bppIndexed && newPixelBit != 7) dataOut[newPixel++] = (byte)(newPixelByte); if (oldFrame.pixelFormat == PixelFormat.Format4bppIndexed && !newPixelNibble) dataOut[newPixel++] = (byte)(newPixelByte); sumY += oldHeight; if(sumY >= newFrame.Height) { y++; lineStartOld += oldFrame.Stride; oldPixel = lineStartOld; sumY -= newFrame.Height; } } } // This is an integer, generic high quality algorithm for shrinking bitmaps. // A significant speed improvement could be optained by splitting out the formats // Eliminating the many if's. private static void ShrinkBmp(Frame oldFrame, Frame newFrame, int oldX, int oldY, int oldWidth, int oldHeight) { byte[] data = oldFrame.Data; byte[] dataOut = newFrame.Data; int[] palette = oldFrame.Palette; int lineStart = 0; int lineStartBit = 0; bool lineStartNibble = false; // Calculate the right line start based on the oldX if (oldFrame.pixelFormat == PixelFormat.Format1bppIndexed) { lineStart = oldX / 8; lineStartBit = 7 - (oldX & 0x07); } else if (oldFrame.pixelFormat == PixelFormat.Format4bppIndexed) { lineStart = oldX / 2; lineStartNibble = ((oldX & 0x01) == 0); } else { lineStart =Utils.FormatToBitCount(oldFrame.pixelFormat) / 8 * oldX; } // Offset to the right place based on oldY. lineStart += oldY * oldFrame.Stride; int lineStartOut = 0; int[] rowCoefficients = CreateCoefficients(oldWidth, newFrame.Width); int[] columnCoefficients = CreateCoefficients(oldHeight, newFrame.Height); byte pixelByte1 = 0; byte pixelByte2 = 0; byte pixelByte3 = 0; byte pixelAlpha = 255; byte byteData = 0; // Index for 1bpp format. int bit = lineStartBit; // Preread the byte if we have to. if (oldFrame.pixelFormat == PixelFormat.Format1bppIndexed && lineStartBit > 0) byteData = data[lineStart]; // Index for 4bpp format. bool highNibble = lineStartNibble; // Preread the byte if we have to. if (oldFrame.pixelFormat == PixelFormat.Format4bppIndexed && !highNibble) { byteData = data[lineStart]; } int bufWidth = 4; if (oldFrame.pixelFormat == PixelFormat.Format1bppIndexed) { bufWidth = 1; } int bufLine = bufWidth * newFrame.Width * 4; int bufNextLine = bufWidth * newFrame.Width; uint[] buffer = new uint[bufWidth * 2 * newFrame.Width]; int currentLine = 0; uint temp; int currentYCoeff = 0; int y = 0; while(y < newFrame.Height) { int currentPixel = lineStart; lineStart += oldFrame.Stride; int bufCurrentPixel = currentLine; int bufNextPixel = bufNextLine; int currentXCoeff = 0; int yCoefficient1 = columnCoefficients[currentYCoeff + 1]; bool crossRow = yCoefficient1 > 0; int x = 0; while(x < newFrame.Width) { int yCoefficient = columnCoefficients[currentYCoeff]; int xCoefficient = rowCoefficients[currentXCoeff]; temp = (uint)(xCoefficient * yCoefficient); // Read the color from the particular format. // 1 bpp Format. if (oldFrame.pixelFormat==PixelFormat.Format1bppIndexed) { if (bit == 0) { byteData = data[currentPixel++]; bit = 128; } if ((byteData & bit) > 0) { pixelByte1 = 255; } else { pixelByte1 = 0; } bit = (byte)(bit >>1); buffer[bufCurrentPixel] += temp * pixelByte1; } else { // 32 bpp Format. if (oldFrame.pixelFormat==PixelFormat.Format32bppArgb) { pixelByte1 = data[currentPixel++]; pixelByte2 = data[currentPixel++]; pixelByte3 = data[currentPixel++]; pixelAlpha = data[currentPixel++]; } // 24 bpp Format. else if (oldFrame.pixelFormat==PixelFormat.Format24bppRgb) { pixelByte1 = data[currentPixel++]; pixelByte2 = data[currentPixel++]; pixelByte3 = data[currentPixel++]; } // 16 bpp 555 Format. else if (oldFrame.pixelFormat==PixelFormat.Format16bppRgb555) { pixelByte2 = data[currentPixel++]; pixelByte1 = data[currentPixel++]; pixelByte3 = (byte)(pixelByte2 & 0x1F); pixelByte2 = (byte)(pixelByte1 << 3 & 0x18 | pixelByte2 >> 5 & 0x07); pixelByte1 = (byte)(pixelByte1 >> 2 & 0x1f); pixelByte1 = (byte)((int)pixelByte1 * 255 / 31); pixelByte2 = (byte)((int)pixelByte2 * 255 / 31); pixelByte3 = (byte)((int)pixelByte3 * 255 / 31); } // 16 bpp 565 Format. else if (oldFrame.pixelFormat==PixelFormat.Format16bppRgb565) { pixelByte2 = data[currentPixel++]; pixelByte1 = data[currentPixel++]; pixelByte3 = (byte)(pixelByte2 & 0x1F); pixelByte2 = (byte)(pixelByte1 << 3 & 0x38 | pixelByte2 >> 5 & 0x07); pixelByte1 = (byte)(pixelByte1 >> 3); pixelByte1 = (byte)((int)pixelByte1 * 255 / 31); pixelByte2 = (byte)((int)pixelByte2 * 255 / 63); pixelByte3 = (byte)((int)pixelByte3 * 255 / 31); } // 8 bpp Format. else if (oldFrame.pixelFormat==PixelFormat.Format8bppIndexed) { int paletteColor = palette[data[currentPixel++]]; pixelByte1 = (byte)(paletteColor>>16); pixelByte2 = (byte)(paletteColor>>8); pixelByte3 = (byte)paletteColor; } // 4 bpp Format. else if (oldFrame.pixelFormat==PixelFormat.Format4bppIndexed) { int paletteColor; if (highNibble) { byteData = data[currentPixel++]; paletteColor = palette[byteData >>4]; } else { paletteColor = palette[byteData & 0x0F]; } highNibble = !highNibble; pixelByte1 = (byte)(paletteColor>>16); pixelByte2 = (byte)(paletteColor>>8); pixelByte3 = (byte)paletteColor; } buffer[bufCurrentPixel] += temp * pixelByte1; buffer[bufCurrentPixel+1] += temp * pixelByte2; buffer[bufCurrentPixel+2] += temp * pixelByte3; buffer[bufCurrentPixel+3] += temp * pixelAlpha; } int xCoefficient1 = rowCoefficients[currentXCoeff + 1]; bool crossColumn = xCoefficient1> 0; if(crossColumn) { temp = (uint)(xCoefficient1 * yCoefficient); if (oldFrame.pixelFormat==PixelFormat.Format1bppIndexed) buffer[bufCurrentPixel + 1] += temp * pixelByte1; else { buffer[bufCurrentPixel + 4] += temp * pixelByte1; buffer[bufCurrentPixel + 5] += temp * pixelByte2; buffer[bufCurrentPixel + 6] += temp * pixelByte3; buffer[bufCurrentPixel + 7] += temp * pixelAlpha; } } if(crossRow) { temp = (uint)(xCoefficient * yCoefficient1); if (oldFrame.pixelFormat==PixelFormat.Format1bppIndexed) buffer[bufNextPixel] += temp * pixelByte1; else { buffer[bufNextPixel] += temp * pixelByte1; buffer[bufNextPixel + 1] += temp * pixelByte2; buffer[bufNextPixel + 2] += temp * pixelByte3; buffer[bufNextPixel + 3] += temp * pixelAlpha; } if(crossColumn) { temp = (uint)(xCoefficient1 * yCoefficient1); if (oldFrame.pixelFormat==PixelFormat.Format1bppIndexed) buffer[bufNextPixel + 1] += temp * pixelByte1; else { buffer[bufNextPixel + 4] += temp * pixelByte1; buffer[bufNextPixel + 5] += temp * pixelByte2; buffer[bufNextPixel + 6] += temp * pixelByte3; buffer[bufNextPixel + 7] += temp * pixelAlpha; } } } if(xCoefficient1 != 0) { x++; bufCurrentPixel += bufWidth; bufNextPixel += bufWidth; } currentXCoeff += 2; } if(yCoefficient1 != 0) { // set result line bufCurrentPixel = currentLine; currentPixel = lineStartOut; int endWriteBuffer = bufCurrentPixel + bufWidth * newFrame.Width; // Write the buffer. // 1 bpp format. if (oldFrame.pixelFormat==PixelFormat.Format1bppIndexed) { byte bit1 = 128; byte dataByte1 = 0; for(;bufCurrentPixel < endWriteBuffer; bufCurrentPixel++) { if (buffer[bufCurrentPixel] != 0) { dataByte1 |= bit1; } bit1 =(byte)(bit1 >> 1); if (bit1 == 0) { bit1 = 128; dataOut[currentPixel++] = dataByte1; dataByte1 = 0; } } // Write the last bits if (bit != 128) { dataOut[currentPixel] = dataByte1; } } // 32 bpp format. else if (oldFrame.pixelFormat==PixelFormat.Format32bppArgb) { for(; bufCurrentPixel < endWriteBuffer; bufCurrentPixel++) { dataOut[currentPixel++] = (byte)(buffer[bufCurrentPixel]>> 24); } } // 24 bpp format. else if (oldFrame.pixelFormat==PixelFormat.Format24bppRgb) { while( bufCurrentPixel < endWriteBuffer) { dataOut[currentPixel++] = (byte)(buffer[bufCurrentPixel++]>> 24); dataOut[currentPixel++] = (byte)(buffer[bufCurrentPixel++]>> 24); dataOut[currentPixel++] = (byte)(buffer[bufCurrentPixel++]>> 24); bufCurrentPixel++; // Skip alpha } } // 16 bpp 555 format. else if (oldFrame.pixelFormat==PixelFormat.Format16bppRgb555) { while( bufCurrentPixel < endWriteBuffer) { int r = (byte)(buffer[bufCurrentPixel++]>> 24); int g = (byte)(buffer[bufCurrentPixel++]>> 24); int b = (byte)(buffer[bufCurrentPixel++]>> 24); bufCurrentPixel++; // Skip alpha dataOut[currentPixel++] = (byte)((g<<2 & 0xE0) | (b>>3 & 0x1F)); dataOut[currentPixel++] = (byte)((r>>1 & 0x7C) | (g >>6 & 0x03)); } } // 16 bpp 565 format. else if (oldFrame.pixelFormat==PixelFormat.Format16bppRgb565) { while( bufCurrentPixel < endWriteBuffer) { int r = (byte)(buffer[bufCurrentPixel++]>> 24); int g = (byte)(buffer[bufCurrentPixel++]>> 24); int b = (byte)(buffer[bufCurrentPixel++]>> 24); bufCurrentPixel++; // Skip alpha dataOut[currentPixel++] = (byte)((g<<3 & 0xE0) | (b >> 3 & 0x1F)) ; dataOut[currentPixel++] = (byte)((r & 0xF8) | (g >>5 & 0x07)); } } // 8 bpp format. else if (oldFrame.pixelFormat==PixelFormat.Format8bppIndexed) { while(bufCurrentPixel < endWriteBuffer) { int r = (byte)(buffer[bufCurrentPixel++]>> 24); int g = (byte)(buffer[bufCurrentPixel++]>> 24); int b = (byte)(buffer[bufCurrentPixel++]>> 24); bufCurrentPixel++; // Skip alpha dataOut[currentPixel++] = (byte)Utils.BestPaletteColor(palette, r, g, b); } } // 4 bpp format. else if (oldFrame.pixelFormat==PixelFormat.Format4bppIndexed) { bool highNibble1 = true; int dataByte1 = 0; while(bufCurrentPixel < endWriteBuffer) { int r = (byte)(buffer[bufCurrentPixel++]>> 24); int g = (byte)(buffer[bufCurrentPixel++]>> 24); int b = (byte)(buffer[bufCurrentPixel++]>> 24); bufCurrentPixel++; // Skip alpha int palettePos = (byte)Utils.BestPaletteColor(palette, r, g, b); if (highNibble1) { dataByte1 = palettePos << 4; } else { dataByte1 |= palettePos; dataOut[currentPixel++] = (byte)dataByte1; } highNibble1 = !highNibble1; } // Write the last bits if (!highNibble1) { dataOut[currentPixel] = (byte)dataByte1; } } bufCurrentPixel = bufNextLine; bufNextLine = currentLine; currentLine = bufCurrentPixel; int endClearBuffer = bufNextLine + bufLine/4; for (int c = bufNextLine; c < endClearBuffer; c++) { buffer[c] = 0; } y++; lineStartOut += newFrame.Stride; } currentYCoeff += 2; } } private static int[] CreateCoefficients(int length, int newLength) { int sum = 0; int[] coefficients = new int[2 * length]; int normalize = (newLength << 12) / length; int denominator = length; for(int i = 0; i < coefficients.Length; i += 2) { int sum2 = sum + newLength; if(sum2 > length) { coefficients[i] = ((length - sum) << 12) / denominator; coefficients[i+1] = ((sum2 - length) << 12) / denominator; sum2 -= length; } else { coefficients[i] = normalize; if(sum2 == length) { coefficients[i+1] = -1; sum2 = 0; } } sum = sum2; } return coefficients; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The implementation for a bijection map using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { [ContractVerification(true)] public sealed class BijectiveMap<TKey, TValue> : IDictionary<TKey, TValue> { #region Object Invariant [Pure] [ContractVerification(false)] public bool IsConsistent() { if (directMap.Count != inverseMap.Count) return false; foreach (var key in this.DirectMap.Keys) { if (!this.InverseMap.ContainsKey(this.DirectMap[key])) return false; } foreach (var key in this.InverseMap.Keys) { if (!this.DirectMap.ContainsKey(this.InverseMap[key])) return false; } return true; } [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(inverseMap != null); Contract.Invariant(directMap != null); //Contract.Invariant(this.IsConsistent()); } #endregion #region Private state private Dictionary<TKey, TValue> directMap; // The direct map private Dictionary<TValue, TKey> inverseMap; // The inverse map #endregion #region Constructors /// <summary> /// Construct a Bijective Map of default size /// </summary> public BijectiveMap() { directMap = new Dictionary<TKey, TValue>(); inverseMap = new Dictionary<TValue, TKey>(); } /// <summary> /// Construct a Bijective Map of size <code>n</code> /// </summary> public BijectiveMap(int size) { Contract.Requires(size >= 0); directMap = new Dictionary<TKey, TValue>(size); inverseMap = new Dictionary<TValue, TKey>(size); } /// <summary> /// Copy constructor /// </summary> public BijectiveMap(BijectiveMap<TKey, TValue> toClone) { Contract.Requires(toClone != null); directMap = new Dictionary<TKey, TValue>(toClone.DirectMap); inverseMap = new Dictionary<TValue, TKey>(toClone.InverseMap); } #endregion #region IBijectiveMap<TKey,TValue> Members /// <returns>The key associated with <code>value</code></returns> [ContractVerification(false)] public TKey KeyForValue(TValue value) { return inverseMap[value]; } /// <returns> /// <code>true</code> iff the co-domain of the map contains the value <code>value</code> /// </returns> [ContractVerification(false)] public bool ContainsValue(TValue value) { return inverseMap.ContainsKey(value); } /// <summary> /// Get the direct map /// </summary> public Dictionary<TKey, TValue> DirectMap { get { Contract.Ensures(Contract.Result<Dictionary<TKey, TValue>>() != null); return directMap; } } /// <summary> /// Get the inverse map /// </summary> public Dictionary<TValue, TKey> InverseMap { get { Contract.Ensures(Contract.Result<Dictionary<TValue, TKey>>() != null); return inverseMap; } } [ContractVerification(false)] public BijectiveMap<TKey, TValue> Duplicate() { var result = new BijectiveMap<TKey, TValue>(); foreach (var pair in directMap) { result[pair.Key] = pair.Value; } return result; } #endregion #region IDictionary<TKey,TValue> Members /// <summary> /// Add the pair <code>(key, value)</code> to the map /// </summary> [ContractVerification(false)] public void Add(TKey key, TValue value) { directMap.Add(key, value); if (!inverseMap.ContainsKey(value)) inverseMap.Add(value, key); } /// <returns><code>true</code> iff <code>key</code> is in the map</returns> public bool ContainsKey(TKey key) { return directMap.ContainsKey(key); } /// <summary> /// Gets the keys in this map /// </summary> public ICollection<TKey> Keys { get { return directMap.Keys; } } /// <summary> /// Remove the entry corresponding to <code>key</code> /// </summary> /// <returns>true if the element is successfully removed; otherwise, false. This method also returns false if key was not found in the IDictionary</returns> // [SuppressMessage("Microsoft.Contracts", "Ensures-31-220")] // It seems we can prove it now [ContractVerification(false)] public bool Remove(TKey key) { Contract.Ensures(!Contract.Result<bool>() || this.Count == Contract.OldValue(this.Count) - 1); TValue valForKey = directMap[key]; bool bDirect = directMap.Remove(key); bool bInverse = inverseMap[valForKey].Equals(key) ? inverseMap.Remove(valForKey) : false; if (bInverse) { foreach (TKey otherKey in directMap.Keys) { if (directMap[otherKey].Equals(valForKey)) { inverseMap[valForKey] = otherKey; break; } } } return bDirect; } /// <summary> /// Tries to get a value corresponding to <code>key</code>. If found, the output is in value; /// </summary> /// <returns>true if the object that implements IDictionary contains an element with the specified key; otherwise, false. </returns> [SuppressMessage("Microsoft.Contracts", "Ensures-Contract.Result<bool>() == @this.ContainsKey(key)")] [ContractVerification(false)] public bool TryGetValue(TKey key, out TValue value) { return directMap.TryGetValue(key, out value); } /// <summary> /// Get the values in this map /// </summary> public ICollection<TValue> Values { get { return directMap.Values; } } /// <summary> /// Get/Sets values in this map /// </summary> /// <param name="key"></param> /// <returns></returns> [ContractVerification(false)] public TValue this[TKey key] { get { return directMap[key]; } set { TValue oldVal; if (directMap.TryGetValue(key, out oldVal)) { inverseMap.Remove(oldVal); } TKey oldKey; if (inverseMap.TryGetValue(value, out oldKey)) { directMap.Remove(oldKey); } directMap[key] = value; inverseMap[value] = key; } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members /// <summary> /// Add the KeyValuePair <code>item</code> /// </summary> [ContractVerification(false)] public void Add(KeyValuePair<TKey, TValue> item) { this[item.Key] = item.Value; } /// <summary> /// Clear the map /// </summary> public void Clear() { directMap.Clear(); inverseMap.Clear(); } /// <summary> /// Does this map contain the <code>item</code>? /// </summary> [ContractVerification(false)] public bool Contains(KeyValuePair<TKey, TValue> item) { TValue val; if (directMap.TryGetValue(item.Key, out val) && val.Equals(item.Value)) { return true; } return false; } /// <summary> /// Copy all the elements of this collection into the <code>array</code>, starting from <code>arrayIndex</code> /// </summary> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { int i = 0; foreach (var pair in directMap) {// F: we do not know that i ranges over the elements of the collection Contract.Assume(arrayIndex + i < array.Length); array[arrayIndex + (i++)] = pair; } } /// <summary> /// The number of items in the map /// </summary> public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() == directMap.Count); return directMap.Count; } } /// <summary> /// Always <code>false</code> /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Remove the <code>item</code> from the collection /// </summary> [ContractVerification(false)] public bool Remove(KeyValuePair<TKey, TValue> item) { var b1 = directMap.Remove(item.Key); var b2 = inverseMap.Remove(item.Value); return b1 && b2; } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members [Pure] public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return directMap.GetEnumerator(); } #endregion #region IEnumerable Members //^ [Pure] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return directMap.GetEnumerator(); } #endregion #region Overridden public override string ToString() { var consistent = IsConsistent() ? "Map Consistent" : "WARNING: Map inconsistent"; var direct = ToString<TKey, TValue>(directMap); var indirect = ToString<TValue, TKey>(inverseMap); return string.Format("{0}" + Environment.NewLine + "({1}, {2})", consistent, direct, indirect); } [ContractVerification(false)] static private string ToString<A, B>(IDictionary<A, B> s) { Contract.Requires(s != null); Contract.Ensures(Contract.Result<string>() != null); var result = new StringBuilder(); foreach (var key in s.Keys) { result.Append("(" + key.ToString() + "," + s[key] + ")"); } return result.ToString(); } #endregion } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Globalization; using Amazon.Util.Internal; namespace Amazon.Util { public static class PaginatedResourceFactory { public static object Create<ItemType, RequestType, ResponseType>(PaginatedResourceInfo pri) { pri.Verify(); return Create<ItemType, RequestType, ResponseType>(pri.Client, pri.MethodName, pri.Request, pri.TokenRequestPropertyPath, pri.TokenResponsePropertyPath, pri.ItemListPropertyPath); } private static PaginatedResource<ItemType> Create<ItemType, RequestType, ResponseType> (object client, string methodName, object request, string tokenRequestPropertyPath, string tokenResponsePropertyPath, string itemListPropertyPath) { ITypeInfo clientType = TypeFactory.GetTypeInfo(client.GetType()); MethodInfo fetcherMethod = clientType.GetMethod(methodName, new ITypeInfo[] { TypeFactory.GetTypeInfo(typeof(RequestType)) }); Func<RequestType, ResponseType> call = (req) => { return (ResponseType)fetcherMethod.Invoke(client, new object[] { req }); }; return Create<ItemType, RequestType, ResponseType>(call, (RequestType)request, tokenRequestPropertyPath, tokenResponsePropertyPath, itemListPropertyPath); } private static PaginatedResource<ItemType> Create<ItemType, RequestType, ResponseType> (Func<RequestType, ResponseType> call, RequestType request, string tokenRequestPropertyPath, string tokenResponsePropertyPath, string itemListPropertyPath) { Func<string, Marker<ItemType>> fetcher = token => { List<ItemType> currentItems; string nextToken; SetPropertyValueAtPath(request, tokenRequestPropertyPath, token); ResponseType nextSet = call(request); nextToken = GetPropertyValueFromPath<string>(nextSet, tokenResponsePropertyPath); currentItems = GetPropertyValueFromPath<List<ItemType>>(nextSet, itemListPropertyPath); return new Marker<ItemType>(currentItems, nextToken); }; return new PaginatedResource<ItemType>(fetcher); } private static void SetPropertyValueAtPath(object instance, string path, string value) { String[] propPath = path.Split('.'); object currentValue = instance; Type currentType = instance.GetType(); PropertyInfo currentProperty = null; int i = 0; for (; i < propPath.Length - 1; i++) { string property = propPath[i]; currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(property); currentValue = currentProperty.GetValue(currentValue, null); currentType = currentProperty.PropertyType; } currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(propPath[i]); currentProperty.SetValue(currentValue, value, null); } private static T GetPropertyValueFromPath<T>(object instance, string path) { String[] propPath = path.Split('.'); object currentValue = instance; Type currentType = instance.GetType(); PropertyInfo currentProperty = null; foreach (string property in propPath) { currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(property); currentValue = currentProperty.GetValue(currentValue, null); currentType = currentProperty.PropertyType; } return (T)currentValue; } internal static Type GetPropertyTypeFromPath(Type start, string path) { String[] propPath = path.Split('.'); Type currentType = start; PropertyInfo currentProperty = null; foreach (string property in propPath) { currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(property); currentType = currentProperty.PropertyType; } return currentType; } private static Type GetFuncType<T, U>() { return typeof(Func<T, U>); } internal static T Cast<T>(object o) { return (T)o; } } public class PaginatedResourceInfo { private string tokenRequestPropertyPath; private string tokenResponsePropertyPath; internal object Client { get; set; } internal string MethodName { get; set; } internal object Request { get; set; } internal string TokenRequestPropertyPath { get { string ret = tokenRequestPropertyPath; if (String.IsNullOrEmpty(ret)) { ret = "NextToken"; } return ret; } set { tokenRequestPropertyPath = value; } } internal string TokenResponsePropertyPath { get { string ret = tokenResponsePropertyPath; if (String.IsNullOrEmpty(ret)) { ret = "{0}"; if (Client != null && !String.IsNullOrEmpty(MethodName)) { MethodInfo mi = TypeFactory.GetTypeInfo(Client.GetType()).GetMethod(MethodName); if (mi != null) { Type responseType = mi.ReturnType; string baseName = responseType.Name; if (baseName.EndsWith("Response", StringComparison.Ordinal)) { baseName = baseName.Substring(0, baseName.Length - 8); } if (TypeFactory.GetTypeInfo(responseType).GetProperty(string.Format(CultureInfo.InvariantCulture, "{0}Result", baseName)) != null) { ret = string.Format(CultureInfo.InvariantCulture, ret, string.Format(CultureInfo.InvariantCulture, "{0}Result.{1}", baseName, "{0}")); } } } ret = string.Format(CultureInfo.InvariantCulture, ret, "NextToken"); } return ret; } set { tokenResponsePropertyPath = value; } } internal string ItemListPropertyPath { get; set; } public PaginatedResourceInfo WithClient(object client) { Client = client; return this; } public PaginatedResourceInfo WithMethodName(string methodName) { MethodName = methodName; return this; } public PaginatedResourceInfo WithRequest(object request) { Request = request; return this; } public PaginatedResourceInfo WithTokenRequestPropertyPath(string tokenRequestPropertyPath) { TokenRequestPropertyPath = tokenRequestPropertyPath; return this; } public PaginatedResourceInfo WithTokenResponsePropertyPath(string tokenResponsePropertyPath) { TokenResponsePropertyPath = tokenResponsePropertyPath; return this; } public PaginatedResourceInfo WithItemListPropertyPath(string itemListPropertyPath) { ItemListPropertyPath = itemListPropertyPath; return this; } internal void Verify() { //Client is set if (Client == null) { throw new ArgumentException("PaginatedResourceInfo.Client needs to be set."); } //MethodName exists on Client and takes one argument of the declared request type Type clientType = Client.GetType(); MethodInfo mi = TypeFactory.GetTypeInfo(clientType).GetMethod(MethodName, new ITypeInfo[] { TypeFactory.GetTypeInfo(Request.GetType()) }); if (mi == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} has no method called {1}", clientType.Name, MethodName)); } //Request is valid type. Type requestType = mi.GetParameters()[0].ParameterType; try { Convert.ChangeType(Request, requestType, CultureInfo.InvariantCulture); } catch (Exception) { throw new ArgumentException("PaginatedResourcInfo.Request is an incompatible type."); } //Properties exist Type responseType = mi.ReturnType; VerifyProperty("TokenRequestPropertyPath", requestType, TokenRequestPropertyPath, typeof(string)); VerifyProperty("TokenResponsePropertyPath", responseType, TokenResponsePropertyPath, typeof(string)); VerifyProperty("ItemListPropertyPath", responseType, ItemListPropertyPath, typeof(string), true); } private static void VerifyProperty(string propName, Type start, string path, Type expectedType) { VerifyProperty(propName, start, path, expectedType, false); } private static void VerifyProperty(string propName, Type start, string path, Type expectedType, bool skipTypecheck) { Type type = null; if (String.IsNullOrEmpty(path)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} must contain a value.", propName)); } try { type = PaginatedResourceFactory.GetPropertyTypeFromPath(start, path); } catch (Exception) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} does not exist on {1}", path, start.Name)); } if (!skipTypecheck && type != expectedType) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} on {1} is not of type {2}", path, start.Name, expectedType.Name)); } } } }
using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; namespace Vanara.PInvoke { /// <summary> /// CLIPFORMAT is a 2-byte value representing a clipboard format. /// <para> /// This cannot be used as a drop-in replacement for many of the winuser.h function as they expect a 4-byte value. However, this can /// automatically convert between the 4-byte values and the 2-byte value. /// </para> /// </summary> /// <seealso cref="System.IComparable"/> /// <seealso cref="System.IComparable{CLIPFORMAT}"/> /// <seealso cref="System.IEquatable{CLIPFORMAT}"/> [StructLayout(LayoutKind.Sequential)] [PInvokeData("wtypes.h", MSDNShortId = "fe42baec-6b00-4816-b379-7f335da8a197")] public partial struct CLIPFORMAT : IComparable, IComparable<CLIPFORMAT>, IEquatable<CLIPFORMAT> { internal readonly ushort _value; /// <summary>Initializes a new instance of the <see cref="CLIPFORMAT"/> structure.</summary> /// <param name="rawValue">The raw clipboard format value.</param> public CLIPFORMAT(ushort rawValue) => _value = rawValue; /// <summary>Compares the current object with another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has the following /// meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal /// to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(CLIPFORMAT other) => _value.CompareTo(other._value); /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current /// instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less /// than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the /// sort order as <paramref name="obj"/> . Greater than zero This instance follows <paramref name="obj"/> in the sort order. /// </returns> public int CompareTo(object obj) { if (!(obj is IConvertible c)) throw new ArgumentException(@"Object cannot be converted to a UInt16 value for comparison.", nameof(obj)); return _value.CompareTo(c.ToUInt16(null)); } /// <summary>Determines whether the specified <see cref="object"/>, is equal to this instance.</summary> /// <param name="obj">The <see cref="object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) => obj is IConvertible c ? _value.Equals(c.ToUInt16(null)) : false; /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns> public bool Equals(CLIPFORMAT other) => other._value == _value; /// <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() => _value.GetHashCode(); /// <summary>Returns a <see cref="string"/> that represents this instance.</summary> /// <returns>A <see cref="string"/> that represents this instance.</returns> public override string ToString() { var type = GetType(); foreach (var fi in type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.FieldType == type && f.IsInitOnly)) if (fi.GetValue(null) is CLIPFORMAT cf && cf._value == _value) return $"{fi.Name} ({HexStr(this)})"; return HexStr(this); string HexStr(in CLIPFORMAT cf) => string.Format(CultureInfo.InvariantCulture, "0x{0:X4}", cf._value); } /// <summary>Implements the operator ==.</summary> /// <param name="hrLeft">The first <see cref="CLIPFORMAT"/>.</param> /// <param name="hrRight">The second <see cref="CLIPFORMAT"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(CLIPFORMAT hrLeft, CLIPFORMAT hrRight) => hrLeft._value == hrRight._value; /// <summary>Implements the operator ==.</summary> /// <param name="hrLeft">The first <see cref="CLIPFORMAT"/>.</param> /// <param name="hrRight">The second <see cref="ushort"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(CLIPFORMAT hrLeft, ushort hrRight) => hrLeft._value == hrRight; /// <summary>Implements the operator !=.</summary> /// <param name="hrLeft">The first <see cref="CLIPFORMAT"/>.</param> /// <param name="hrRight">The second <see cref="CLIPFORMAT"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(CLIPFORMAT hrLeft, CLIPFORMAT hrRight) => !(hrLeft == hrRight); /// <summary>Implements the operator !=.</summary> /// <param name="hrLeft">The first <see cref="CLIPFORMAT"/>.</param> /// <param name="hrRight">The second <see cref="ushort"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(CLIPFORMAT hrLeft, ushort hrRight) => !(hrLeft == hrRight); /// <summary>Performs an implicit conversion from <see cref="ushort"/> to <see cref="CLIPFORMAT"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator CLIPFORMAT(ushort value) => new CLIPFORMAT(value); /// <summary>Performs an implicit conversion from <see cref="short"/> to <see cref="CLIPFORMAT"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator CLIPFORMAT(short value) => new CLIPFORMAT(unchecked((ushort)value)); /// <summary>Performs an implicit conversion from <see cref="uint"/> to <see cref="CLIPFORMAT"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator CLIPFORMAT(uint value) => new CLIPFORMAT((ushort)value); /// <summary>Performs an implicit conversion from <see cref="uint"/> to <see cref="CLIPFORMAT"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator CLIPFORMAT(int value) => new CLIPFORMAT((ushort)value); /// <summary>Performs an explicit conversion from <see cref="CLIPFORMAT"/> to <see cref="System.UInt16"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator ushort(CLIPFORMAT value) => value._value; /// <summary>Performs an explicit conversion from <see cref="CLIPFORMAT"/> to <see cref="System.Int16"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator short(CLIPFORMAT value) => unchecked((short)value._value); /// <summary>Performs an explicit conversion from <see cref="CLIPFORMAT"/> to <see cref="System.UInt32"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator uint(CLIPFORMAT value) => value._value; /// <summary>Performs an explicit conversion from <see cref="CLIPFORMAT"/> to <see cref="System.Int32"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator int(CLIPFORMAT value) => value._value; /// <summary>A handle to a bitmap (HBITMAP).</summary> public static readonly CLIPFORMAT CF_BITMAP = 2; /// <summary>A memory object containing a BITMAPINFO structure followed by the bitmap bits.</summary> public static readonly CLIPFORMAT CF_DIB = 8; /// <summary> /// A memory object containing a BITMAPV5HEADER structure followed by the bitmap color space information and the bitmap bits. /// </summary> public static readonly CLIPFORMAT CF_DIBV5 = 17; /// <summary>Software Arts' Data Interchange Format.</summary> public static readonly CLIPFORMAT CF_DIF = 5; /// <summary> /// Bitmap display format associated with a private format. The hMem parameter must be a handle to data that can be displayed in /// bitmap format in lieu of the privately formatted data. /// </summary> public static readonly CLIPFORMAT CF_DSPBITMAP = 0x0082; /// <summary> /// Enhanced metafile display format associated with a private format. The hMem parameter must be a handle to data that can be /// displayed in enhanced metafile format in lieu of the privately formatted data. /// </summary> public static readonly CLIPFORMAT CF_DSPENHMETAFILE = 0x008E; /// <summary> /// Metafile-picture display format associated with a private format. The hMem parameter must be a handle to data that can be /// displayed in metafile-picture format in lieu of the privately formatted data. /// </summary> public static readonly CLIPFORMAT CF_DSPMETAFILEPICT = 0x0083; /// <summary> /// Text display format associated with a private format. The hMem parameter must be a handle to data that can be displayed in text /// format in lieu of the privately formatted data. /// </summary> public static readonly CLIPFORMAT CF_DSPTEXT = 0x0081; /// <summary>A handle to an enhanced metafile (HENHMETAFILE).</summary> public static readonly CLIPFORMAT CF_ENHMETAFILE = 14; /// <summary> /// Start of a range of integer values for application-defined GDI object clipboard formats. The end of the range is CF_GDIOBJLAST. /// <para> /// Handles associated with clipboard formats in this range are not automatically deleted using the GlobalFree function when the /// clipboard is emptied. Also, when using values in this range, the hMem parameter is not a handle to a GDI object, but is a handle /// allocated by the GlobalAlloc function with the GMEM_MOVEABLE flag. /// </para> /// </summary> public static readonly CLIPFORMAT CF_GDIOBJFIRST = 0x0300; /// <summary>See CF_GDIOBJFIRST.</summary> public static readonly CLIPFORMAT CF_GDIOBJLAST = 0x03FF; /// <summary> /// A handle to type HDROP that identifies a list of files. An application can retrieve information about the files by passing the /// handle to the DragQueryFile function. /// </summary> public static readonly CLIPFORMAT CF_HDROP = 15; /// <summary> /// The data is a handle to the locale identifier associated with text in the clipboard. When you close the clipboard, if it contains /// CF_TEXT data but no CF_LOCALE data, the system automatically sets the CF_LOCALE format to the current input language. You can use /// the CF_LOCALE format to associate a different locale with the clipboard text. /// <para> /// An application that pastes text from the clipboard can retrieve this format to determine which character set was used to generate /// the text. /// </para> /// <para> /// Note that the clipboard does not support plain text in multiple character sets. To achieve this, use a formatted text data type /// such as RTF instead. /// </para> /// <para> /// The system uses the code page associated with CF_LOCALE to implicitly convert from CF_TEXT to CF_UNICODETEXT. Therefore, the /// correct code page table is used for the conversion. /// </para> /// </summary> public static readonly CLIPFORMAT CF_LOCALE = 16; /// <summary> /// Handle to a metafile picture format as defined by the METAFILEPICT structure. When passing a CF_METAFILEPICT handle by means of /// DDE, the application responsible for deleting hMem should also free the metafile referred to by the CF_METAFILEPICT handle. /// </summary> public static readonly CLIPFORMAT CF_METAFILEPICT = 3; /// <summary> /// Text format containing characters in the OEM character set. Each line ends with a carriage return/linefeed (CR-LF) combination. A /// null character signals the end of the data. /// </summary> public static readonly CLIPFORMAT CF_OEMTEXT = 7; /// <summary> /// Owner-display format. The clipboard owner must display and update the clipboard viewer window, and receive the /// WM_ASKCBFORMATNAME, WM_HSCROLLCLIPBOARD, WM_PAINTCLIPBOARD, WM_SIZECLIPBOARD, and WM_VSCROLLCLIPBOARD messages. The hMem /// parameter must be NULL. /// </summary> public static readonly CLIPFORMAT CF_OWNERDISPLAY = 0x0080; /// <summary> /// Handle to a color palette. Whenever an application places data in the clipboard that depends on or assumes a color palette, it /// should place the palette on the clipboard as well. /// <para> /// If the clipboard contains data in the CF_PALETTE (logical color palette) format, the application should use the SelectPalette and /// RealizePalette functions to realize (compare) any other data in the clipboard against that logical palette. /// </para> /// <para> /// When displaying clipboard data, the clipboard always uses as its current palette any object on the clipboard that is in the /// CF_PALETTE format. /// </para> /// </summary> public static readonly CLIPFORMAT CF_PALETTE = 9; /// <summary>Data for the pen extensions to the Microsoft Windows for Pen Computing.</summary> public static readonly CLIPFORMAT CF_PENDATA = 10; /// <summary> /// Start of a range of integer values for private clipboard formats. The range ends with CF_PRIVATELAST. Handles associated with /// private clipboard formats are not freed automatically; the clipboard owner must free such handles, typically in response to the /// WM_DESTROYCLIPBOARD message. /// </summary> public static readonly CLIPFORMAT CF_PRIVATEFIRST = 0x0200; /// <summary>See CF_PRIVATEFIRST.</summary> public static readonly CLIPFORMAT CF_PRIVATELAST = 0x02FF; /// <summary>Represents audio data more complex than can be represented in a CF_WAVE standard wave format.</summary> public static readonly CLIPFORMAT CF_RIFF = 11; /// <summary>Microsoft Symbolic Link (SYLK) format.</summary> public static readonly CLIPFORMAT CF_SYLK = 4; /// <summary> /// Text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data. /// Use this format for ANSI text. /// </summary> public static readonly CLIPFORMAT CF_TEXT = 1; /// <summary>Tagged-image file format.</summary> public static readonly CLIPFORMAT CF_TIFF = 6; /// <summary> /// Unicode text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data. /// </summary> public static readonly CLIPFORMAT CF_UNICODETEXT = 13; /// <summary>Represents audio data in one of the standard wave formats, such as 11 kHz or 22 kHz PCM.</summary> public static readonly CLIPFORMAT CF_WAVE = 12; } }
// // Application.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using Mono.Unix; using Hyena; using Banshee.Library; using Banshee.Playlist; using Banshee.SmartPlaylist; using Banshee.Sources; using Banshee.Base; namespace Banshee.ServiceStack { public delegate bool ShutdownRequestHandler (); public delegate bool TimeoutHandler (); public delegate bool IdleHandler (); public delegate bool IdleTimeoutRemoveHandler (uint id); public delegate uint TimeoutImplementationHandler (uint milliseconds, TimeoutHandler handler); public delegate uint IdleImplementationHandler (IdleHandler handler); public delegate bool IdleTimeoutRemoveImplementationHandler (uint id); public static class Application { public static event ShutdownRequestHandler ShutdownRequested; public static event Action<Client> ClientAdded; private static event Action<Client> client_started; public static event Action<Client> ClientStarted { add { lock (running_clients) { foreach (Client client in running_clients) { if (client.IsStarted) { OnClientStarted (client); } } } client_started += value; } remove { client_started -= value; } } private static Stack<Client> running_clients = new Stack<Client> (); private static bool shutting_down; public static void Initialize () { ServiceManager.DefaultInitialize (); } #if WIN32 [DllImport("msvcrt.dll") /* willfully unmapped */] public static extern int _putenv (string varName); #endif public static void Run () { #if WIN32 // There are two sets of environement variables we need to impact with our LANG. // refer to : http://article.gmane.org/gmane.comp.gnu.mingw.user/8272 var lang_code = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName; string env = String.Concat ("LANG=", lang_code); Environment.SetEnvironmentVariable ("LANG", lang_code); _putenv (env); #endif Catalog.Init (Application.InternalName, System.IO.Path.Combine ( Hyena.Paths.InstalledApplicationDataRoot, "locale")); if (!DBusConnection.ConnectTried) { DBusConnection.Connect (); } ServiceManager.Run (); ServiceManager.SourceManager.AddSource (new MusicLibrarySource (), true); ServiceManager.SourceManager.AddSource (new VideoLibrarySource (), false); ServiceManager.SourceManager.LoadExtensionSources (); } public static bool ShuttingDown { get { return shutting_down; } } public static void Shutdown () { shutting_down = true; if (Banshee.Kernel.Scheduler.IsScheduled (typeof (Banshee.Kernel.IInstanceCriticalJob)) || ServiceManager.JobScheduler.HasAnyDataLossJobs || Banshee.Kernel.Scheduler.CurrentJob is Banshee.Kernel.IInstanceCriticalJob) { if (shutdown_prompt_handler != null && !shutdown_prompt_handler ()) { shutting_down = false; return; } } if (OnShutdownRequested ()) { Dispose (); } shutting_down = false; } public static void PushClient (Client client) { lock (running_clients) { running_clients.Push (client); client.Started += OnClientStarted; } Action<Client> handler = ClientAdded; if (handler != null) { handler (client); } } public static Client PopClient () { lock (running_clients) { return running_clients.Pop (); } } public static Client ActiveClient { get { lock (running_clients) { return running_clients.Peek (); } } } private static void OnClientStarted (Client client) { client.Started -= OnClientStarted; Action<Client> handler = client_started; if (handler != null) { handler (client); } } static bool paths_initialized; public static void InitializePaths () { if (!paths_initialized) { // We changed banshee-1 to banshee everywhere except the // ~/.config/banshee-1/ and ~/.cache/banshee-1 directories, and // for gconf Paths.UserApplicationName = "banshee-1"; Paths.ApplicationName = InternalName; paths_initialized = true; } } [DllImport ("libglib-2.0-0.dll")] static extern IntPtr g_get_language_names (); public static void DisplayHelp (string page) { DisplayHelp ("banshee", page); } private static void DisplayHelp (string project, string page) { bool shown = false; foreach (var lang in GLib.Marshaller.NullTermPtrToStringArray (g_get_language_names (), false)) { string path = String.Format ("{0}/gnome/help/{1}/{2}", Paths.InstalledApplicationDataRoot, project, lang); if (System.IO.Directory.Exists (path)) { shown = Banshee.Web.Browser.Open (String.Format ("ghelp:{0}", path), false); break; } } if (!shown) { Banshee.Web.Browser.Open (String.Format ("http://library.gnome.org/users/{0}/", project)); } } private static bool OnShutdownRequested () { ShutdownRequestHandler handler = ShutdownRequested; if (handler != null) { foreach (ShutdownRequestHandler del in handler.GetInvocationList ()) { if (!del ()) { return false; } } } return true; } public static void Invoke (InvokeHandler handler) { RunIdle (delegate { handler (); return false; }); } public static uint RunIdle (IdleHandler handler) { if (idle_handler == null) { throw new NotImplementedException ("The application client must provide an IdleImplementationHandler"); } return idle_handler (handler); } public static uint RunTimeout (uint milliseconds, TimeoutHandler handler) { if (timeout_handler == null) { throw new NotImplementedException ("The application client must provide a TimeoutImplementationHandler"); } return timeout_handler (milliseconds, handler); } public static bool IdleTimeoutRemove (uint id) { if (idle_timeout_remove_handler == null) { throw new NotImplementedException ("The application client must provide a IdleTimeoutRemoveImplementationHandler"); } return idle_timeout_remove_handler (id); } private static void Dispose () { ServiceManager.JobScheduler.CancelAll (true); ServiceManager.Shutdown (); lock (running_clients) { while (running_clients.Count > 0) { running_clients.Pop ().Dispose (); } } } private static ShutdownRequestHandler shutdown_prompt_handler = null; public static ShutdownRequestHandler ShutdownPromptHandler { get { return shutdown_prompt_handler; } set { shutdown_prompt_handler = value; } } private static TimeoutImplementationHandler timeout_handler = null; public static TimeoutImplementationHandler TimeoutHandler { get { return timeout_handler; } set { timeout_handler = value; } } private static IdleImplementationHandler idle_handler = null; public static IdleImplementationHandler IdleHandler { get { return idle_handler; } set { idle_handler = value; } } private static IdleTimeoutRemoveImplementationHandler idle_timeout_remove_handler = null; public static IdleTimeoutRemoveImplementationHandler IdleTimeoutRemoveHandler { get { return idle_timeout_remove_handler; } set { idle_timeout_remove_handler = value; } } public static string InternalName { get { return "banshee"; } } public static string IconName { get { return "media-player-banshee"; } } private static string api_version; public static string ApiVersion { get { if (api_version != null) { return api_version; } try { AssemblyName name = Assembly.GetEntryAssembly ().GetName (); api_version = String.Format ("{0}.{1}.{2}", name.Version.Major, name.Version.Minor, name.Version.Build); } catch { api_version = "unknown"; } return api_version; } } private static string version; public static string Version { get { return version ?? (version = GetVersion ("ReleaseVersion")); } } private static string display_version; public static string DisplayVersion { get { return display_version ?? (display_version = GetVersion ("DisplayVersion")); } } private static string build_time; public static string BuildTime { get { return build_time ?? (build_time = GetBuildInfo ("BuildTime")); } } private static string build_host_os; public static string BuildHostOperatingSystem { get { return build_host_os ?? (build_host_os = GetBuildInfo ("HostOperatingSystem")); } } private static string build_host_cpu; public static string BuildHostCpu { get { return build_host_cpu ?? (build_host_cpu = GetBuildInfo ("HostCpu")); } } private static string build_vendor; public static string BuildVendor { get { return build_vendor ?? (build_vendor = GetBuildInfo ("Vendor")); } } private static string build_display_info; public static string BuildDisplayInfo { get { if (build_display_info != null) { return build_display_info; } build_display_info = String.Format ("{0} ({1}, {2}) @ {3}", BuildVendor, BuildHostOperatingSystem, BuildHostCpu, BuildTime); return build_display_info; } } private static string GetVersion (string versionName) { return GetCustomAssemblyMetadata ("ApplicationVersionAttribute", versionName) ?? Catalog.GetString ("Unknown"); } private static string GetBuildInfo (string buildField) { return GetCustomAssemblyMetadata ("ApplicationBuildInformationAttribute", buildField); } private static string GetCustomAssemblyMetadata (string attrName, string field) { Assembly assembly = Assembly.GetEntryAssembly (); if (assembly == null) { return null; } foreach (Attribute attribute in assembly.GetCustomAttributes (false)) { Type type = attribute.GetType (); PropertyInfo property = type.GetProperty (field); if (type.Name == attrName && property != null && property.PropertyType == typeof (string)) { return (string)property.GetValue (attribute, null); } } return null; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal sealed class CSharpSyntaxContext : AbstractSyntaxContext { public readonly TypeDeclarationSyntax ContainingTypeDeclaration; public readonly BaseTypeDeclarationSyntax ContainingTypeOrEnumDeclaration; public readonly bool IsInNonUserCode; public readonly bool IsPreProcessorKeywordContext; public readonly bool IsPreProcessorExpressionContext; public readonly bool IsGlobalStatementContext; public readonly bool IsNonAttributeExpressionContext; public readonly bool IsConstantExpressionContext; public readonly bool IsLabelContext; public readonly bool IsTypeArgumentOfConstraintContext; public readonly bool IsNamespaceDeclarationNameContext; public readonly bool IsIsOrAsContext; public readonly bool IsObjectCreationTypeContext; public readonly bool IsDefiniteCastTypeContext; public readonly bool IsGenericTypeArgumentContext; public readonly bool IsEnumBaseListContext; public readonly bool IsIsOrAsTypeContext; public readonly bool IsLocalVariableDeclarationContext; public readonly bool IsDeclarationExpressionContext; public readonly bool IsFixedVariableDeclarationContext; public readonly bool IsParameterTypeContext; public readonly bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext; public readonly bool IsImplicitOrExplicitOperatorTypeContext; public readonly bool IsPrimaryFunctionExpressionContext; public readonly bool IsDelegateReturnTypeContext; public readonly bool IsTypeOfExpressionContext; public readonly ISet<SyntaxKind> PrecedingModifiers; public readonly bool IsInstanceContext; public readonly bool IsCrefContext; public readonly bool IsCatchFilterContext; private CSharpSyntaxContext( Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken leftToken, SyntaxToken targetToken, TypeDeclarationSyntax containingTypeDeclaration, BaseTypeDeclarationSyntax containingTypeOrEnumDeclaration, bool isInNonUserCode, bool isPreProcessorDirectiveContext, bool isPreProcessorKeywordContext, bool isPreProcessorExpressionContext, bool isTypeContext, bool isNamespaceContext, bool isStatementContext, bool isGlobalStatementContext, bool isAnyExpressionContext, bool isNonAttributeExpressionContext, bool isConstantExpressionContext, bool isAttributeNameContext, bool isEnumTypeMemberAccessContext, bool isInQuery, bool isInImportsDirective, bool isLabelContext, bool isTypeArgumentOfConstraintContext, bool isNamespaceDeclarationNameContext, bool isRightOfDotOrArrowOrColonColon, bool isIsOrAsContext, bool isObjectCreationTypeContext, bool isDefiniteCastTypeContext, bool isGenericTypeArgumentContext, bool isEnumBaseListContext, bool isIsOrAsTypeContext, bool isLocalVariableDeclarationContext, bool isDeclarationExpressionContext, bool isFixedVariableDeclarationContext, bool isParameterTypeContext, bool isPossibleLambdaOrAnonymousMethodParameterTypeContext, bool isImplicitOrExplicitOperatorTypeContext, bool isPrimaryFunctionExpressionContext, bool isDelegateReturnTypeContext, bool isTypeOfExpressionContext, ISet<SyntaxKind> precedingModifiers, bool isInstanceContext, bool isCrefContext, bool isCatchFilterContext) : base(workspace, semanticModel, position, leftToken, targetToken, isTypeContext, isNamespaceContext, isPreProcessorDirectiveContext, isRightOfDotOrArrowOrColonColon, isStatementContext, isAnyExpressionContext, isAttributeNameContext, isEnumTypeMemberAccessContext, isInQuery, isInImportsDirective) { this.ContainingTypeDeclaration = containingTypeDeclaration; this.ContainingTypeOrEnumDeclaration = containingTypeOrEnumDeclaration; this.IsInNonUserCode = isInNonUserCode; this.IsPreProcessorKeywordContext = isPreProcessorKeywordContext; this.IsPreProcessorExpressionContext = isPreProcessorExpressionContext; this.IsGlobalStatementContext = isGlobalStatementContext; this.IsNonAttributeExpressionContext = isNonAttributeExpressionContext; this.IsConstantExpressionContext = isConstantExpressionContext; this.IsLabelContext = isLabelContext; this.IsTypeArgumentOfConstraintContext = isTypeArgumentOfConstraintContext; this.IsNamespaceDeclarationNameContext = isNamespaceDeclarationNameContext; this.IsIsOrAsContext = isIsOrAsContext; this.IsObjectCreationTypeContext = isObjectCreationTypeContext; this.IsDefiniteCastTypeContext = isDefiniteCastTypeContext; this.IsGenericTypeArgumentContext = isGenericTypeArgumentContext; this.IsEnumBaseListContext = isEnumBaseListContext; this.IsIsOrAsTypeContext = isIsOrAsTypeContext; this.IsLocalVariableDeclarationContext = isLocalVariableDeclarationContext; this.IsDeclarationExpressionContext = isDeclarationExpressionContext; this.IsFixedVariableDeclarationContext = isFixedVariableDeclarationContext; this.IsParameterTypeContext = isParameterTypeContext; this.IsPossibleLambdaOrAnonymousMethodParameterTypeContext = isPossibleLambdaOrAnonymousMethodParameterTypeContext; this.IsImplicitOrExplicitOperatorTypeContext = isImplicitOrExplicitOperatorTypeContext; this.IsPrimaryFunctionExpressionContext = isPrimaryFunctionExpressionContext; this.IsDelegateReturnTypeContext = isDelegateReturnTypeContext; this.IsTypeOfExpressionContext = isTypeOfExpressionContext; this.PrecedingModifiers = precedingModifiers; this.IsInstanceContext = isInstanceContext; this.IsCrefContext = isCrefContext; this.IsCatchFilterContext = isCatchFilterContext; } public static CSharpSyntaxContext CreateContext(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var syntaxTree = semanticModel.SyntaxTree; var isInNonUserCode = syntaxTree.IsInNonUserCode(position, cancellationToken); var preProcessorTokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true); var isPreProcessorDirectiveContext = syntaxTree.IsPreProcessorDirectiveContext(position, preProcessorTokenOnLeftOfPosition, cancellationToken); var leftToken = isPreProcessorDirectiveContext ? preProcessorTokenOnLeftOfPosition : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position); var isPreProcessorKeywordContext = isPreProcessorDirectiveContext ? syntaxTree.IsPreProcessorKeywordContext(position, leftToken, cancellationToken) : false; var isPreProcessorExpressionContext = isPreProcessorDirectiveContext ? targetToken.IsPreProcessorExpressionContext() : false; var isStatementContext = !isPreProcessorDirectiveContext ? targetToken.IsBeginningOfStatementContext() : false; var isGlobalStatementContext = !isPreProcessorDirectiveContext ? syntaxTree.IsGlobalStatementContext(position, cancellationToken) : false; var isAnyExpressionContext = !isPreProcessorDirectiveContext ? syntaxTree.IsExpressionContext(position, leftToken, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel) : false; var isNonAttributeExpressionContext = !isPreProcessorDirectiveContext ? syntaxTree.IsExpressionContext(position, leftToken, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModel) : false; var isConstantExpressionContext = !isPreProcessorDirectiveContext ? syntaxTree.IsConstantExpressionContext(position, leftToken, cancellationToken) : false; var containingTypeDeclaration = syntaxTree.GetContainingTypeDeclaration(position, cancellationToken); var containingTypeOrEnumDeclaration = syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken); return new CSharpSyntaxContext( workspace, semanticModel, position, leftToken, targetToken, containingTypeDeclaration, containingTypeOrEnumDeclaration, isInNonUserCode, isPreProcessorDirectiveContext, isPreProcessorKeywordContext, isPreProcessorExpressionContext, syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt: semanticModel), syntaxTree.IsNamespaceContext(position, cancellationToken, semanticModelOpt: semanticModel), isStatementContext, isGlobalStatementContext, isAnyExpressionContext, isNonAttributeExpressionContext, isConstantExpressionContext, syntaxTree.IsAttributeNameContext(position, cancellationToken), syntaxTree.IsEnumTypeMemberAccessContext(semanticModel, position, cancellationToken), leftToken.GetAncestor<QueryExpressionSyntax>() != null, IsLeftSideOfUsingAliasDirective(leftToken, cancellationToken), syntaxTree.IsLabelContext(position, cancellationToken), syntaxTree.IsTypeArgumentOfConstraintClause(position, cancellationToken), syntaxTree.IsNamespaceDeclarationNameContext(position, cancellationToken), syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken), syntaxTree.IsIsOrAsContext(position, leftToken, cancellationToken), syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken), syntaxTree.IsDefiniteCastTypeContext(position, leftToken, cancellationToken), syntaxTree.IsGenericTypeArgumentContext(position, leftToken, cancellationToken), syntaxTree.IsEnumBaseListContext(position, leftToken, cancellationToken), syntaxTree.IsIsOrAsTypeContext(position, leftToken, cancellationToken), syntaxTree.IsLocalVariableDeclarationContext(position, leftToken, cancellationToken), syntaxTree.IsDeclarationExpressionContext(position, leftToken, cancellationToken), syntaxTree.IsFixedVariableDeclarationContext(position, leftToken, cancellationToken), syntaxTree.IsParameterTypeContext(position, leftToken, cancellationToken), syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, leftToken, cancellationToken), syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, leftToken, cancellationToken), syntaxTree.IsPrimaryFunctionExpressionContext(position, leftToken, cancellationToken), syntaxTree.IsDelegateReturnTypeContext(position, leftToken, cancellationToken), syntaxTree.IsTypeOfExpressionContext(position, leftToken, cancellationToken), syntaxTree.GetPrecedingModifiers(position, leftToken, cancellationToken), syntaxTree.IsInstanceContext(position, leftToken, cancellationToken), syntaxTree.IsCrefContext(position, cancellationToken) && !leftToken.MatchesKind(SyntaxKind.DotToken), syntaxTree.IsCatchFilterContext(position, leftToken)); } public static CSharpSyntaxContext CreateContext_Test(SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return CreateContext(/*workspace*/null, semanticModel, position, cancellationToken); } public bool IsTypeAttributeContext(CancellationToken cancellationToken) { // cases: // [ | // class C { [ | var token = this.TargetToken; // Note that we pass the token.SpanStart to IsTypeDeclarationContext below. This is a bit subtle, // but we want to be sure that the attribute itself (i.e. the open square bracket, '[') is in a // type declaration context. if (token.CSharpKind() == SyntaxKind.OpenBracketToken && token.Parent.CSharpKind() == SyntaxKind.AttributeList && this.SyntaxTree.IsTypeDeclarationContext( token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return true; } return false; } public bool IsTypeDeclarationContext( ISet<SyntaxKind> validModifiers = null, ISet<SyntaxKind> validTypeDeclarations = null, bool canBePartial = false, CancellationToken cancellationToken = default(CancellationToken)) { return this.SyntaxTree.IsTypeDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken); } public bool IsMemberAttributeContext(ISet<SyntaxKind> validTypeDeclarations, CancellationToken cancellationToken) { // cases: // class C { [ | var token = this.TargetToken; if (token.CSharpKind() == SyntaxKind.OpenBracketToken && token.Parent.CSharpKind() == SyntaxKind.AttributeList && this.SyntaxTree.IsMemberDeclarationContext( token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: validTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return true; } return false; } public bool IsMemberDeclarationContext( ISet<SyntaxKind> validModifiers = null, ISet<SyntaxKind> validTypeDeclarations = null, bool canBePartial = false, CancellationToken cancellationToken = default(CancellationToken)) { return this.SyntaxTree.IsMemberDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken); } private static bool IsLeftSideOfUsingAliasDirective(SyntaxToken leftToken, CancellationToken cancellationToken) { var usingDirective = leftToken.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null) { // No = token: if (usingDirective.Alias == null || usingDirective.Alias.EqualsToken.IsMissing) { return true; } return leftToken.SpanStart < usingDirective.Alias.EqualsToken.SpanStart; } return false; } } }
namespace FakeItEasy.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FluentAssertions.Execution; public static class NullGuardedAssertion { public static NullGuardedConstraint Should(this Expression<Action> call) { return new NullGuardedConstraint(call); } /// <summary> /// Validates that calls are properly null guarded. /// </summary> /// <seealso cref="BeNullGuarded"/> public class NullGuardedConstraint { private readonly Expression<Action> call; private ConstraintState? state; internal NullGuardedConstraint(Expression<Action> call) { Guard.AgainstNull(call, nameof(call)); this.call = call; } /// <summary> /// Validate a subject action to ensure that the method or constructor call it uses is null guarded. /// </summary> /// <remarks> /// For the supplied call, iterates over all the provided arguments, and for each one that is not null, /// invokes the call with the provided argument values, replacing that one argument with null. /// If the call fails to throw a <see cref="NullReferenceException"/> naming the correct argument (including /// throwing a different exception), the method is considered not to be null guarded properly. /// Note that this means that supplying a null argument value means that the method may accept null /// values for that argument. Since this null will be used for this value in all invocations, if the method /// does mistakenly guard that parameter against having a null value, the method will fail the test. /// </remarks> /// <example> /// <code> /// Expression<Action> call1 = () => methodThatNullGuardsBothParameters("argument1", "argument2"); /// call1.Should().BeNullGuarded(); /// /// Expression<Action> call2 = () => methodThatNullGuardsOnlyTheSeconParameter(null, "argument2"); /// call2.Should().BeNullGuarded(); /// </code> /// </example> public void BeNullGuarded() { var matches = this.Matches(this.call); if (matches) { return; } var builder = ServiceLocator.Resolve<StringBuilderOutputWriter.Factory>().Invoke(); this.WriteDescriptionTo(builder); builder.WriteLine(); this.WriteActualValueTo(builder); var reason = builder.Builder.ToString(); Execute.Assertion.FailWith(reason); } private static ConstraintState CreateCall(Expression<Action> methodCall) { var methodExpression = methodCall.Body as MethodCallExpression; if (methodExpression is not null) { return new MethodCallConstraintState(methodExpression); } return new ConstructorCallConstraintState((NewExpression)methodCall.Body); } private static object? GetValueProducedByExpression(Expression expression) { if (expression is null) { return null; } var lambda = Expression.Lambda(expression); return lambda.Compile().DynamicInvoke(); } private void WriteDescriptionTo(StringBuilderOutputWriter builder) { builder.Write("Expected calls to "); this.state!.WriteTo(builder); builder.Write(" to be null guarded."); } private void WriteActualValueTo(StringBuilderOutputWriter builder) { builder.Write( "When called with the following arguments the method did not throw the appropriate exception:"); builder.WriteLine(); this.state!.WriteFailingCallsDescriptions(builder); } private bool Matches(Expression<Action> expression) { this.state = CreateCall(expression); return this.state.Matches(); } private abstract class ConstraintState { protected readonly IEnumerable<ArgumentInfo> ValidArguments; private IEnumerable<CallThatShouldThrow>? unguardedCalls; protected ConstraintState(IEnumerable<ArgumentInfo> arguments) { this.ValidArguments = arguments; } protected abstract string CallDescription { get; } private IEnumerable<object?> ArgumentValues { get { return this.ValidArguments.Select(x => x.Value); } } public bool Matches() { this.unguardedCalls = this.GetArgumentsForCallsThatAreNotProperlyNullGuarded(); return !this.unguardedCalls.Any(); } public void WriteTo(StringBuilderOutputWriter builder) { builder.Write(this.CallDescription); builder.Write("("); WriteArgumentList(builder, this.ValidArguments); builder.Write(")"); } public void WriteFailingCallsDescriptions(StringBuilderOutputWriter builder) { using (builder.Indent()) { foreach (var call in this.unguardedCalls!) { call.WriteFailingCallDescription(builder); builder.WriteLine(); } } } protected static IEnumerable<ArgumentInfo> GetArgumentInfos(IEnumerable<Expression> callArgumentsValues, ParameterInfo[] callArguments) { var result = new List<ArgumentInfo>(); int index = 0; foreach (var argument in callArgumentsValues) { result.Add(new ArgumentInfo() { ArgumentType = callArguments[index].ParameterType, Name = callArguments[index].Name ?? $"argument {index} had no name", Value = GetValueProducedByExpression(argument) }); index++; } return result; } protected abstract void PerformCall(object?[] arguments); private static bool IsNullableType(Type type) { return !type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); } private static void WriteArgumentList(StringBuilderOutputWriter builder, IEnumerable<ArgumentInfo> arguments) { int lengthWhenStarting = builder.Builder.Length; foreach (var argument in arguments) { if (builder.Builder.Length > lengthWhenStarting) { builder.Write(", "); } WriteArgument(builder, argument); } } private static void WriteArgument(StringBuilderOutputWriter builder, ArgumentInfo argument) { builder.Write("["); builder.Write(argument.ArgumentType.Name); builder.Write("]"); builder.Write(" "); builder.Write(argument.Name); } private IEnumerable<CallThatShouldThrow> GetArgumentsForCallsThatAreNotProperlyNullGuarded() { var result = new List<CallThatShouldThrow>(); foreach (var callThatShouldThrow in this.GetArgumentPermutationsThatShouldThrow()) { try { this.PerformCall(callThatShouldThrow.Arguments); result.Add(callThatShouldThrow); } catch (TargetInvocationException ex) { callThatShouldThrow.SetThrownException(ex.InnerException); var nullException = ex.InnerException as ArgumentNullException; if (nullException == null || callThatShouldThrow.ArgumentName != nullException.ParamName) { result.Add(callThatShouldThrow); } } } return result; } private IEnumerable<CallThatShouldThrow> GetArgumentPermutationsThatShouldThrow() { var result = new List<CallThatShouldThrow>(); int index = 0; foreach (var argument in this.ValidArguments) { if (argument.Value is not null && IsNullableType(argument.ArgumentType)) { result.Add(new CallThatShouldThrow( argument.Name, this.ArgumentValues.Take(index) .Concat(default(object)) .Concat(this.ArgumentValues.Skip(index + 1)) .ToArray())); } index++; } if (!result.Any()) { throw new InvalidOperationException( "Provided call has no non-null nullable arguments, so there's nothing to check."); } return result; } protected struct ArgumentInfo { public string Name { get; set; } public Type ArgumentType { get; set; } public object? Value { get; set; } } private class CallThatShouldThrow { private Exception? thrown; public CallThatShouldThrow(string argumentName, object?[] arguments) { this.ArgumentName = argumentName; this.Arguments = arguments; } public string ArgumentName { get; } public object?[] Arguments { get; } public void SetThrownException(Exception? value) { this.thrown = value; } public void WriteFailingCallDescription(StringBuilderOutputWriter builder) { builder.Write("("); this.WriteArgumentList(builder); builder.Write(") "); this.WriteFailReason(builder); } private void WriteArgumentList(StringBuilderOutputWriter builder) { int lengthWhenStarting = builder.Builder.Length; foreach (var argument in this.Arguments) { if (builder.Builder.Length > lengthWhenStarting) { builder.Write(", "); } builder.WriteArgumentValue(argument); } } private void WriteFailReason(StringBuilderOutputWriter description) { if (this.thrown is null) { description.Write("did not throw any exception."); } else { var argumentNullException = this.thrown as ArgumentNullException; if (argumentNullException is not null) { description.Write( $"threw ArgumentNullException with wrong argument name, it should be {this.ArgumentName}."); } else { description.Write($"threw unexpected {this.thrown.GetType()}."); } } } } } private class MethodCallConstraintState : ConstraintState { private readonly object? target; private readonly MethodInfo method; public MethodCallConstraintState(MethodCallExpression expression) : base(GetExpressionArguments(expression)) { this.method = expression.Method; this.target = NullGuardedConstraint.GetValueProducedByExpression(expression.Object!); } protected override string CallDescription => this.method.ReflectedType?.Name + "." + this.method.Name; protected override void PerformCall(object?[] arguments) { this.method.Invoke(this.target, arguments); } private static IEnumerable<ArgumentInfo> GetExpressionArguments(MethodCallExpression expression) { return ConstraintState.GetArgumentInfos(expression.Arguments, expression.Method.GetParameters()); } } private class ConstructorCallConstraintState : ConstraintState { private readonly ConstructorInfo constructorInfo; public ConstructorCallConstraintState(NewExpression expression) : base(GetArgumentInfos(expression)) { this.constructorInfo = expression.Constructor!; } protected override string CallDescription => this.constructorInfo.ReflectedType + ".ctor"; protected override void PerformCall(object?[] arguments) { this.constructorInfo.Invoke(arguments); } private static IEnumerable<ArgumentInfo> GetArgumentInfos(NewExpression expression) { return GetArgumentInfos(expression.Arguments, expression.Constructor!.GetParameters()); } } } } }
using System.IO; using System.Text; using System.Net.Sockets; using System.Net; using System; namespace AsterNET.IO { /// <summary> /// Socket connection to asterisk. /// </summary> public class SocketConnection { private TcpClient tcpClient; private NetworkStream networkStream; private StreamReader reader; private BinaryWriter writer; private Encoding encoding; private bool initial; #region Constructor - SocketConnection(string host, int port, int receiveTimeout) /// <summary> /// Consructor /// </summary> /// <param name="host">client host</param> /// <param name="port">client port</param> /// <param name="encoding">encoding</param> public SocketConnection(string host, int port, Encoding encoding) :this(new TcpClient(host, port), encoding) { } /// <summary> /// Consructor /// </summary> /// <param name="host">client host</param> /// <param name="port">client port</param> /// <param name="encoding">encoding</param> /// <param name="receiveBufferSize">size of the receive buffer.</param> public SocketConnection(string host, int port,int receiveBufferSize, Encoding encoding) : this (new TcpClient(host, port) {ReceiveBufferSize = receiveBufferSize }, encoding) { } #endregion #region Constructor - SocketConnection(socket) /// <summary> /// Constructor /// </summary> /// <param name="tcpClient">TCP client from Listener</param> /// <param name="encoding">encoding</param> internal SocketConnection(TcpClient tcpClient, Encoding encoding) { initial = true; this.encoding = encoding; this.tcpClient = tcpClient; this.networkStream = this.tcpClient.GetStream(); this.reader = new StreamReader(this.networkStream, encoding); this.writer = new BinaryWriter(this.networkStream, encoding); } #endregion public TcpClient TcpClient { get { return tcpClient; } } public NetworkStream NetworkStream { get { return networkStream; } } public Encoding Encoding { get { return encoding; } } public bool Initial { get { return initial; } set { initial = value; } } #region IsConnected /// <summary> /// Returns the connection state of the socket. /// </summary> public bool IsConnected { get { return tcpClient.Connected; } } #endregion #region LocalAddress public IPAddress LocalAddress { get { return ((IPEndPoint)(tcpClient.Client.LocalEndPoint)).Address; } } #endregion #region LocalPort public int LocalPort { get { return ((IPEndPoint)(tcpClient.Client.LocalEndPoint)).Port; } } #endregion #region RemoteAddress public IPAddress RemoteAddress { get { return ((IPEndPoint)(tcpClient.Client.RemoteEndPoint)).Address; } } #endregion #region RemotePort public int RemotePort { get { return ((IPEndPoint)(tcpClient.Client.LocalEndPoint)).Port; } } #endregion #region ReadLine() /// <summary> /// Reads a line of text from the socket connection. The current thread is /// blocked until either the next line is received or an IOException /// encounters. /// </summary> /// <returns>the line of text received excluding any newline character</returns> /// <throws> IOException if the connection has been closed. </throws> public string ReadLine() { string line = null; try { line = reader.ReadLine(); } catch { line = null; } return line; } #endregion #region Write(string s) /// <summary> /// Sends a given String to the socket connection. /// </summary> /// <param name="s">the String to send.</param> /// <throws> IOException if the String cannot be sent, maybe because the </throws> /// <summary>connection has already been closed.</summary> public void Write(string s) { writer.Write(encoding.GetBytes(s)); writer.Flush(); } #endregion #region Write(string msg) /// <summary> /// Sends a given String to the socket connection. /// </summary> /// <param name="msg">the String to send.</param> /// <throws> IOException if the String cannot be sent, maybe because the </throws> /// <summary>connection has already been closed.</summary> public void WriteEx(string msg) { byte[] data = encoding.GetBytes(msg); networkStream.BeginWrite(data, 0, data.Length, onWriteFinished, networkStream); networkStream.Flush(); } private void onWriteFinished(IAsyncResult ar) { NetworkStream stream = (NetworkStream)ar.AsyncState; stream.EndWrite(ar); } #endregion #region Close /// <summary> /// Closes the socket connection including its input and output stream and /// frees all associated ressources.<br/> /// When calling close() any Thread currently blocked by a call to readLine() /// will be unblocked and receive an IOException. /// </summary> /// <throws> IOException if the socket connection cannot be closed. </throws> public void Close() { try { tcpClient.Client.Shutdown(SocketShutdown.Both); tcpClient.Client.Close(); tcpClient.Close(); } catch { } } #endregion } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal partial class NavigationBarController { /// <summary> /// The computation of the last model. /// </summary> private Task<NavigationBarModel> _modelTask; private NavigationBarModel _lastCompletedModel; private CancellationTokenSource _modelTaskCancellationSource = new CancellationTokenSource(); /// <summary> /// Starts a new task to compute the model based on the current text. /// </summary> private void StartModelUpdateAndSelectedItemUpdateTasks(int modelUpdateDelay, int selectedItemUpdateDelay, bool updateUIWhenDone) { AssertIsForeground(); var textSnapshot = _subjectBuffer.CurrentSnapshot; var document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } // Cancel off any existing work _modelTaskCancellationSource.Cancel(); _modelTaskCancellationSource = new CancellationTokenSource(); var cancellationToken = _modelTaskCancellationSource.Token; // Enqueue a new computation for the model var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".StartModelUpdateTask"); _modelTask = Task.Delay(modelUpdateDelay, cancellationToken) .SafeContinueWithFromAsync( _ => ComputeModelAsync(document, textSnapshot, cancellationToken), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); _modelTask.CompletesAsyncOperation(asyncToken); StartSelectedItemUpdateTask(selectedItemUpdateDelay, updateUIWhenDone); } /// <summary> /// Computes a model for the given snapshot. /// </summary> private async Task<NavigationBarModel> ComputeModelAsync(Document document, ITextSnapshot snapshot, CancellationToken cancellationToken) { // TODO: remove .FirstOrDefault() var languageService = document.Project.LanguageServices.GetService<INavigationBarItemService>(); if (languageService != null) { // check whether we can re-use lastCompletedModel. otherwise, update lastCompletedModel here. // the model should be only updated here if (_lastCompletedModel != null) { var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(CancellationToken.None).ConfigureAwait(false); if (_lastCompletedModel.SemanticVersionStamp == semanticVersion && SpanStillValid(_lastCompletedModel, snapshot, cancellationToken)) { // it looks like we can re-use previous model return _lastCompletedModel; } } using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken)) { var items = await languageService.GetItemsAsync(document, cancellationToken).ConfigureAwait(false); if (items != null) { items.Do(i => i.InitializeTrackingSpans(snapshot)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); _lastCompletedModel = new NavigationBarModel(items, version, languageService); return _lastCompletedModel; } } } _lastCompletedModel = _lastCompletedModel ?? new NavigationBarModel(SpecializedCollections.EmptyList<NavigationBarItem>(), new VersionStamp(), null); return _lastCompletedModel; } private Task<NavigationBarSelectedTypeAndMember> _selectedItemInfoTask; private CancellationTokenSource _selectedItemInfoTaskCancellationSource = new CancellationTokenSource(); /// <summary> /// Starts a new task to compute what item should be selected. /// </summary> private void StartSelectedItemUpdateTask(int delay, bool updateUIWhenDone) { AssertIsForeground(); var currentView = _presenter.TryGetCurrentView(); if (currentView == null) { return; } // Cancel off any existing work _selectedItemInfoTaskCancellationSource.Cancel(); _selectedItemInfoTaskCancellationSource = new CancellationTokenSource(); var cancellationToken = _selectedItemInfoTaskCancellationSource.Token; var subjectBufferCaretPosition = currentView.GetCaretPoint(_subjectBuffer); if (!subjectBufferCaretPosition.HasValue) { return; } var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".StartSelectedItemUpdateTask"); // Enqueue a new computation for the selected item _selectedItemInfoTask = _modelTask.ContinueWithAfterDelay( t => t.IsCanceled ? new NavigationBarSelectedTypeAndMember(null, null) : ComputeSelectedTypeAndMember(t.Result, subjectBufferCaretPosition.Value, cancellationToken), cancellationToken, delay, TaskContinuationOptions.None, TaskScheduler.Default); _selectedItemInfoTask.CompletesAsyncOperation(asyncToken); if (updateUIWhenDone) { asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".StartSelectedItemUpdateTask.UpdateUI"); _selectedItemInfoTask.SafeContinueWith( t => PushSelectedItemsToPresenter(t.Result), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundThreadAffinitizedObject.CurrentForegroundThreadData.TaskScheduler).CompletesAsyncOperation(asyncToken); } } internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember(NavigationBarModel model, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var leftItem = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken); if (leftItem.item == null) { // Nothing to show at all return new NavigationBarSelectedTypeAndMember(null, null); } var rightItem = GetMatchingItem(leftItem.item.ChildItems, caretPosition, model.ItemService, cancellationToken); return new NavigationBarSelectedTypeAndMember(leftItem.item, leftItem.gray, rightItem.item, rightItem.gray); } /// <summary> /// Finds the item that point is in, or if it's not in any items, gets the first item that's /// positioned after the cursor. /// </summary> /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns> private static (T item, bool gray) GetMatchingItem<T>(IEnumerable<T> items, SnapshotPoint point, INavigationBarItemService itemsService, CancellationToken cancellationToken) where T : NavigationBarItem { T exactItem = null; int exactItemStart = 0; T nextItem = null; int nextItemStart = int.MaxValue; foreach (var item in items) { foreach (var span in item.TrackingSpans.Select(s => s.GetSpan(point.Snapshot))) { cancellationToken.ThrowIfCancellationRequested(); if (span.Contains(point) || span.End == point) { // This is the item we should show normally. We'll continue looking at other // items as there might be a nested type that we're actually in. If there // are multiple items containing the point, choose whichever containing span // starts later because that will be the most nested item. if (exactItem == null || span.Start >= exactItemStart) { exactItem = item; exactItemStart = span.Start; } } else if (span.Start > point && span.Start <= nextItemStart) { nextItem = item; nextItemStart = span.Start; } } } if (exactItem != null) { return (exactItem, gray: false); } else { // The second parameter is if we should show it grayed. We'll be nice and say false // unless we actually have an item var itemToGray = nextItem ?? items.LastOrDefault(); if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray)) { itemToGray = null; } return (itemToGray, gray: itemToGray != null); } } private static bool SpanStillValid(NavigationBarModel model, ITextSnapshot snapshot, CancellationToken cancellationToken) { // even if semantic version is same, portion of text could have been copied & pasted with // exact same top level content. // go through spans to see whether this happened. // // paying cost of moving spans forward shouldn't be matter since we need to pay that // price soon or later to figure out selected item. foreach (var type in model.Types) { if (!SpanStillValid(type.TrackingSpans, snapshot)) { return false; } foreach (var member in type.ChildItems) { cancellationToken.ThrowIfCancellationRequested(); if (!SpanStillValid(member.TrackingSpans, snapshot)) { return false; } } } return true; } private static bool SpanStillValid(IList<ITrackingSpan> spans, ITextSnapshot snapshot) { for (var i = 0; i < spans.Count; i++) { var span = spans[i]; var currentSpan = span.GetSpan(snapshot); if (currentSpan.IsEmpty) { return false; } } return true; } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using ApprovalTests; using ApprovalTests.Reporters; using ApprovalUtilities.Utilities; using ConsoleToolkit.ConsoleIO; using ConsoleToolkit.ConsoleIO.Internal; using ConsoleToolkit.Testing; using ConsoleToolkitTests.TestingUtilities; using NUnit.Framework; namespace ConsoleToolkitTests.ConsoleIO.Internal { [TestFixture] [UseReporter(typeof (CustomReporter))] public class TestReadInputItem { private ConsoleInterfaceForTesting _interface; private ConsoleAdapter _adapter; private static readonly PropertyInfo StringProp = typeof (TestReadInputItem).GetProperty("StringVal"); private static readonly PropertyInfo IntProp = typeof (TestReadInputItem).GetProperty("IntVal"); private TextReader _goodStream; private TextReader _selectStream; private TextReader _stringOnlyStream; private TextReader _validationStream; public string StringVal { get; set; } public int IntVal { get; set; } [SetUp] public void SetUp() { _interface = new ConsoleInterfaceForTesting(); _adapter = new ConsoleAdapter(_interface); StringVal = null; IntVal = 0; _goodStream = MakeStream(new [] {"text", "45"}); _stringOnlyStream = MakeStream(new [] {"text"}); _selectStream = MakeStream(new [] {"bad", "2", "C"}); _validationStream = MakeStream(new[] { "2", "10", "11" }); } private TextReader MakeStream(IEnumerable<string> input) { return new StringReader(input.JoinWith(Environment.NewLine)); } [Test] public void StringCanBeRead() { _interface.SetInputStream(_goodStream); var item = new InputItem { Name = "StringVal", Property = StringProp, Type = typeof(string) }; ReadInputItem.GetValue(item, _interface, _adapter); Assert.That(item.Value, Is.EqualTo("text")); } [Test] public void ValidReadReturnsTrue() { _interface.SetInputStream(_stringOnlyStream); var item = new InputItem { Name = "StringVal", Property = StringProp, Type = typeof(string) }; Assert.That(ReadInputItem.GetValue(item, _interface, _adapter), Is.True); } [Test] public void InvalidReadReturnsFalse() { _interface.SetInputStream(_stringOnlyStream); _interface.InputIsRedirected = true; var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int) }; Assert.That(ReadInputItem.GetValue(item, _interface, _adapter), Is.False); } [Test] public void TextIsConvertedToRequiredType() { _interface.SetInputStream(_goodStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int) }; ReadInputItem.GetValue(item, _interface, _adapter); Assert.That(item.Value, Is.EqualTo(45)); } [Test] public void PromptIsDisplayed() { _interface.SetInputStream(_goodStream); var item = new InputItem { Name = "StringVal", Property = StringProp, Type = typeof(string), ReadInfo = Read.String().Prompt("prompt") }; ReadInputItem.GetValue(item, _interface, _adapter); Approvals.Verify(_interface.GetBuffer()); } [Test] public void ErrorIsDisplayedWhenInputIsInvalid() { _interface.SetInputStream(_goodStream); _interface.InputIsRedirected = true; var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Prompt("prompt") }; ReadInputItem.GetValue(item, _interface, _adapter); Approvals.Verify(_interface.GetBuffer()); } [Test] public void InteractiveInputContinuesUntilGoodInputReceived() { _interface.SetInputStream(_goodStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Prompt("prompt") }; ReadInputItem.GetValue(item, _interface, _adapter); Approvals.Verify(_interface.GetBuffer()); } [Test] public void OptionsCanBeSpecified() { _interface.SetInputStream(_selectStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Prompt("prompt") .Option(1, "1", "First") .Option(2, "2", "Second") .Option(3, "3", "Third") }; ReadInputItem.GetValue(item, _interface, _adapter); Approvals.Verify(_interface.GetBuffer()); } [Test] public void OptionsCanBeDisplayedAsAMenu() { _interface.SetInputStream(_selectStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Prompt("prompt") .Option(1, "1", "First") .Option(2, "2", "Second") .Option(3, "3", "Third") .AsMenu("Select one") }; ReadInputItem.GetValue(item, _interface, _adapter); Approvals.Verify(_interface.GetBuffer()); } [Test] public void OptionIsSelected() { _interface.SetInputStream(_selectStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Prompt("prompt") .Option(100, "B", "First") .Option(200, "C", "Second") .Option(300, "D", "Third") }; ReadInputItem.GetValue(item, _interface, _adapter); var value = ((Read<int>)item.Value).Value; Assert.That(value, Is.EqualTo(200)); } [Test] public void ValidationsAreApplied() { _interface.SetInputStream(_validationStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Validate(i => i > 10, "Value must be greater than 10") }; ReadInputItem.GetValue(item, _interface, _adapter); var value = ((Read<int>)item.Value).Value; Assert.That(value, Is.EqualTo(11)); } [Test] public void ValidationErrorMessageIsDisplayed() { _interface.SetInputStream(_validationStream); var item = new InputItem { Name = "IntVal", Property = IntProp, Type = typeof(int), ReadInfo = Read.Int().Validate(i => i > 10, "Value must be greater than 10") }; ReadInputItem.GetValue(item, _interface, _adapter); Approvals.Verify(_interface.GetBuffer()); } } }
// 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.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using Microsoft.OData.Client; using Microsoft.OData.Core; namespace Microsoft.OData.ProxyExtensions { public partial class DataServiceContextWrapper : DataServiceContext { private readonly Func<Task<string>> _accessTokenGetter; private readonly HashSet<EntityBase> _modifiedEntities = new HashSet<EntityBase>(); public void UpdateObject(EntityBase entity) { if (GetEntityDescriptor(entity) != null) { _modifiedEntities.Add(entity); base.UpdateObject(entity); } } public DataServiceContextWrapper(Uri serviceRoot, ODataProtocolVersion maxProtocolVersion, Func<Task<string>> accessTokenGetter) : base(serviceRoot, maxProtocolVersion) { _accessTokenGetter = accessTokenGetter; IgnoreMissingProperties = true; BuildingRequest += async (sender, args) => args.Headers.Add("Authorization", "Bearer " + await _accessTokenGetter()); Configurations.RequestPipeline.OnEntryStarting(args => { var entity = (EntityBase)args.Entity; if ((!entity.ChangedProperties.IsValueCreated || entity.ChangedProperties.Value.Count == 0)) { args.Entry.Properties = new ODataProperty[0]; return; } if (!_modifiedEntities.Contains(entity)) { _modifiedEntities.Add(entity); } IEnumerable<ODataProperty> properties = new ODataProperty[0]; if (entity.ChangedProperties.IsValueCreated) { properties = properties.Concat(args.Entry.Properties.Where(i => entity.ChangedProperties.Value.Contains(i.Name))); } args.Entry.Properties = properties; }); Configurations.ResponsePipeline.OnEntityMaterialized(args => { var entity = (EntityBase)args.Entity; entity.ResetChanges(); }); OnCreated(); } partial void OnCreated(); public Type DefaultResolveTypeInternal(string typeName, string fullNamespace, string languageDependentNamespace) { return DefaultResolveType(typeName, fullNamespace, languageDependentNamespace); } public string DefaultResolveNameInternal(Type clientType, string fullNamespace, string languageDependentNamespace) { if (clientType.Namespace.Equals(languageDependentNamespace, StringComparison.Ordinal)) { return string.Concat(fullNamespace, ".", clientType.Name); } return string.Empty; } public async Task<TInterface> ExecuteSingleAsync<TSource, TInterface>(DataServiceQuery<TSource> inner) { try { return await Task.Factory.FromAsync( inner.BeginExecute, i => inner.EndExecute(i).Cast<TInterface>().SingleOrDefault(), TaskCreationOptions.None); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } public async Task<IBatchElementResult[]> ExecuteBatchAsync(params IReadOnlyQueryableSetBase[] queries) { try { var requests = (from i in queries select (DataServiceRequest)i.Query).ToArray(); var responses = await Task.Factory.FromAsync<DataServiceRequest[], DataServiceResponse>( (q, callback, state) => BeginExecuteBatch(callback, state, q), // need to reorder parameters EndExecuteBatch, requests, null); var retVal = new IBatchElementResult[queries.Length]; var index = 0; foreach (var response in responses) { Type tConcrete = ((IConcreteTypeAccessor)queries[index]).ConcreteType; Type tInterface = ((IConcreteTypeAccessor)queries[index]).ElementType; var pcType = typeof(PagedCollection<,>).MakeGenericType(tInterface, tConcrete); var pcTypeInfo = pcType.GetTypeInfo(); var pcCreator = pcTypeInfo.GetDeclaredMethod("Create"); // Handle an error response. // from http://msdn.microsoft.com/en-us/library/dd744838(v=vs.110).aspx if (response.StatusCode > 299 || response.StatusCode < 200) { retVal[index] = new BatchElementResult(ProcessException(response.Error) ?? response.Error); } else { retVal[index] = new BatchElementResult((IPagedCollection)pcCreator.Invoke(null, new object[] { this, response })); } index++; } return retVal; } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } public async Task<Stream> GetStreamAsync(Uri requestUriTmp, IDictionary<string, string> headers) { using (var client = new System.Net.Http.HttpClient()) { using (var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, requestUriTmp)) { request.Headers.Add("Authorization", "Bearer " + await _accessTokenGetter()); request.Headers.Add("Accept", "*/*"); request.Headers.Add("Accept-Charset", "UTF-8"); if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } // Do not dispose the response. If disposed, it will also dispose the // stream we are returning var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStreamAsync(); } var newException = await ProcessErrorAsync(response); if (newException != null) { throw newException; } response.EnsureSuccessStatusCode(); // unreachable return null; } } } public async Task<DataServiceStreamResponse> GetReadStreamAsync(EntityBase entity, string streamName, string contentType) { try { if (!string.IsNullOrEmpty(streamName)) { var resp = await Task.Factory.FromAsync<object, string, DataServiceRequestArgs, DataServiceStreamResponse>( BeginGetReadStream, EndGetReadStream, entity, streamName, new DataServiceRequestArgs { ContentType = contentType /*, Headers = {todo}*/ }, null); return resp; } else { var resp = await Task.Factory.FromAsync<object, DataServiceRequestArgs, DataServiceStreamResponse>( BeginGetReadStream, EndGetReadStream, entity, new DataServiceRequestArgs { ContentType = contentType /*, Headers = {todo}*/ }, null); return resp; } } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } public async Task<IPagedCollection<TInterface>> ExecuteAsync<TSource, TInterface>(DataServiceQuery<TSource> inner) where TSource : TInterface { try { return await Task.Factory.FromAsync( inner.BeginExecute, new Func<IAsyncResult, IPagedCollection<TInterface>>( r => new PagedCollection<TInterface, TSource>( this, (QueryOperationResponse<TSource>) inner.EndExecute(r))), TaskCreationOptions.None); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } public new Task<IEnumerable<T>> ExecuteAsync<T>(Uri uri, string httpMethod, bool singleResult, params OperationParameter[] operationParameters) { return ExecuteAsyncInternal<T>(uri, httpMethod, singleResult, null, operationParameters); } public Task<IEnumerable<T>> ExecuteAsync<T>(Uri uri, string httpMethod, bool singleResult, Stream stream, params OperationParameter[] operationParameters) { return ExecuteAsyncInternal<T>(uri, httpMethod, singleResult, stream ?? new MemoryStream(), operationParameters); } public async Task<IEnumerable<T>> ExecuteAsyncInternal<T>(Uri uri, string httpMethod, bool singleResult, Stream stream, params OperationParameter[] operationParameters) { try { if (stream != null) { Configurations.RequestPipeline.OnMessageCreating = args => { args.Headers.Remove("Content-Length"); var msg = new HttpWebRequestMessage(args); Task.Factory.FromAsync<Stream>(msg.BeginGetRequestStream, msg.EndGetRequestStream, null) .ContinueWith(s => stream.CopyTo(s.Result)) .Wait(); return msg; }; } return await Task.Factory.FromAsync<IEnumerable<T>>( (callback, state) => BeginExecute<T>(uri, callback, state, httpMethod, singleResult, operationParameters), EndExecute<T>, TaskCreationOptions.None); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } finally { if (stream != null) { Configurations.RequestPipeline.OnMessageCreating = null; } } } public new Task ExecuteAsync(Uri uri, string httpMethod, params OperationParameter[] operationParameters) { return ExecuteAsync(uri, httpMethod, null, operationParameters); } public async Task ExecuteAsync(Uri uri, string httpMethod, Stream stream, params OperationParameter[] operationParameters) { try { if (stream != null) { Configurations.RequestPipeline.OnMessageCreating = args => { args.Headers.Remove("Content-Length"); var msg = new HttpWebRequestMessage(args); Task.Factory.FromAsync<Stream>(msg.BeginGetRequestStream, msg.EndGetRequestStream, null) .ContinueWith(s => stream.CopyTo(s.Result)) .Wait(); return msg; }; } await Task.Factory.FromAsync( (callback, state) => BeginExecute(uri, callback, state, httpMethod, operationParameters), new Action<IAsyncResult>(i => EndExecute(i)), TaskCreationOptions.None); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } finally { if (stream != null) { Configurations.RequestPipeline.OnMessageCreating = null; } } } public async Task<QueryOperationResponse<TSource>> ExecuteAsync<TSource, TInterface>(DataServiceQueryContinuation<TSource> token) { try { return await Task.Factory.FromAsync( (callback, state) => BeginExecute(token, callback, state), i => (QueryOperationResponse<TSource>)EndExecute<TSource>(i), TaskCreationOptions.None); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } public async new Task<DataServiceResponse> SaveChangesAsync(SaveChangesOptions options) { try { var result = await Task.Factory.FromAsync( BeginSaveChanges, new Func<IAsyncResult, DataServiceResponse>(EndSaveChanges), options, null, TaskCreationOptions.None); foreach (var i in _modifiedEntities) { i.ResetChanges(); } _modifiedEntities.Clear(); return result; } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } public new Task<DataServiceResponse> SaveChangesAsync() { return SaveChangesAsync(SaveChangesOptions.None); } #if NOTYET public async Task<IPagedCollection<TInterface>> LoadPropertyAsync<TSource, TInterface>(string path, object entity) where TSource : TInterface { try { return await Task.Factory.FromAsync( (callback, state) => BeginLoadProperty(entity, path, callback, state), new Func<IAsyncResult, IPagedCollection<TInterface>>( r => new PagedCollection<TInterface, TSource>(this, (QueryOperationResponse<TSource>) EndLoadProperty(r))), TaskCreationOptions.None); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } } #endif public static Exception ProcessException(Exception ex) { var dataServiceRequestException = ex as DataServiceRequestException; if (dataServiceRequestException != null) { var response = dataServiceRequestException.Response.FirstOrDefault(); if (response != null) { return ProcessError(dataServiceRequestException, dataServiceRequestException.InnerException as DataServiceClientException, response.Headers); } } var dataServiceQueryException = ex as DataServiceQueryException; if (dataServiceQueryException != null) { return ProcessError(dataServiceQueryException, dataServiceQueryException.InnerException as DataServiceClientException, dataServiceQueryException.Response.Headers); } var dataServiceClientException = ex as DataServiceClientException; if (dataServiceClientException != null) { return ProcessError(dataServiceClientException, dataServiceClientException, new Dictionary<string, string> { {"Content-Type", dataServiceClientException.Message.StartsWith("<") ? "application/xml" : "application/json"} }); } return null; } private static Exception ProcessError(Exception outer, DataServiceClientException inner, IDictionary<string, string> headers) { if (inner == null) { return null; } using (var writer = WriteToStream(inner.Message)) { var httpMessage = new HttpWebResponseMessage( headers, inner.StatusCode, () => writer.BaseStream); var reader = new ODataMessageReader(httpMessage); try { var error = reader.ReadError(); return new ODataErrorException(error.Message, outer, error); } catch { } } return null; } private static async Task<Exception> ProcessErrorAsync(System.Net.Http.HttpResponseMessage response) { if (response.Content == null) { return null; } if (response.Content.Headers.ContentType == null) { return new System.Net.Http.HttpRequestException(await response.Content.ReadAsStringAsync()); } using (var stream = await response.Content.ReadAsStreamAsync()) { var headers = response.Content.Headers.ToDictionary(i => i.Key, i => i.Value.FirstOrDefault()); var httpMessage = new HttpWebResponseMessage( headers, (int)response.StatusCode, () => stream); var reader = new ODataMessageReader(httpMessage); try { var error = reader.ReadError(); return new ODataErrorException(error.Message, null, error); } catch { } } return null; } private static StreamWriter WriteToStream(string contents) { var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(contents); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); return writer; } } }
// 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.IO; using System.IO.MemoryMappedFiles; using Xunit; [Collection("CreateOrOpen")] public class CreateOrOpen : MMFTestBase { private readonly static string s_uniquifier = Guid.NewGuid().ToString(); private readonly static string s_fileNameTest = "CreateOrOpen_test_" + s_uniquifier + ".txt"; [Fact] public static void CreateOrOpenTestCases() { bool bResult = false; CreateOrOpen test = new CreateOrOpen(); try { bResult = test.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine("FAiL! Error Err_9999zzz! Uncaught Exception in main(), exc_main==" + exc_main.ToString()); } Assert.True(bResult, "One or more test cases failed."); } public bool runTest() { try { //////////////////////////////////////////////////////////////////////// // CreateOrOpen(mapName, capcity) //////////////////////////////////////////////////////////////////////// // [] mapName // mapname > 260 chars VerifyCreate("Loc111", "CreateOrOpen" + new String('a', 1000) + s_uniquifier, 4096); // null VerifyException<ArgumentNullException>("Loc112", null, 4096); // empty string disallowed VerifyException<ArgumentException>("Loc113", String.Empty, 4096); // all whitespace VerifyCreate("Loc114", "\t \n\u00A0", 4096); String fileText = "Non-empty file for MMF testing."; if (Interop.IsWindows) // named maps not supported on Unix { // MMF with this mapname already exists (pagefile backed) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_map115a" + s_uniquifier, 1000)) { VerifyOpen("Loc115a", "COO_map115a" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite); } // MMF with this mapname already exists (filesystem backed) File.WriteAllText(s_fileNameTest, fileText); using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(s_fileNameTest, FileMode.Open, "COO_map115b" + s_uniquifier)) { VerifyOpen("Loc115b", "COO_map115b" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite); } } // MMF with this mapname existed, but was closed - new MMF VerifyCreate("Loc116", "COO_map115a" + s_uniquifier, 500); // "global/" prefix VerifyCreate("Loc117", "global/COO_mapname" + s_uniquifier, 4096); // "local/" prefix VerifyCreate("Loc118", "local/COO_mapname" + s_uniquifier, 4096); // [] capacity // >0 capacity VerifyCreate("Loc211", "COO_mapname211" + s_uniquifier, 50); // 0 capacity VerifyException<ArgumentOutOfRangeException>("Loc211", "COO_mapname211" + s_uniquifier, 0); // negative VerifyException<ArgumentOutOfRangeException>("Loc213", "COO_mapname213" + s_uniquifier, -1); // negative VerifyException<ArgumentOutOfRangeException>("Loc214", "COO_mapname214" + s_uniquifier, -4096); // Int64.MaxValue - cannot exceed local address space if (IntPtr.Size == 4) VerifyException<ArgumentOutOfRangeException>("Loc215", "COO_mapname215" + s_uniquifier, Int64.MaxValue); else // 64-bit machine VerifyException<IOException>("Loc215b", "COO_mapname215" + s_uniquifier, Int64.MaxValue); // valid but too large if (Interop.IsWindows) // named maps not supported on Unix { // ignored for existing file (smaller) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname216" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyOpen("Loc216", "COO_mapname216" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } // ignored for existing file (larger) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname217" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyOpen("Loc217", "COO_mapname217" + s_uniquifier, 10000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } // existing file - invalid - still exception using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname218" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyException<ArgumentOutOfRangeException>("Loc218", "COO_mapname218" + s_uniquifier, 0, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } } //////////////////////////////////////////////////////////////////////// // CreateOrOpen(mapName, capcity, MemoryMappedFileAccess) //////////////////////////////////////////////////////////////////////// // [] access // Write is disallowed VerifyException<ArgumentException>("Loc330", "COO_mapname330" + s_uniquifier, 1000, MemoryMappedFileAccess.Write); // valid access - new file MemoryMappedFileAccess[] accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreate("Loc331_" + access, "COO_mapname331_" + access + s_uniquifier, 1000, access); } // invalid enum value accessList = new MemoryMappedFileAccess[] { (MemoryMappedFileAccess)(-1), (MemoryMappedFileAccess)(6), }; foreach (MemoryMappedFileAccess access in accessList) { VerifyException<ArgumentOutOfRangeException>("Loc332_" + ((int)access), "COO_mapname332_" + ((int)access) + s_uniquifier, 1000, access); } if (Interop.IsWindows) // named maps not supported on Unix { // default security - all valid for existing file using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname333" + s_uniquifier, 1000)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyOpen("Loc333_" + access, "COO_mapname333" + s_uniquifier, 1000, access, access); } } } //////////////////////////////////////////////////////////////////////// // CreateOrOpen(String, long, MemoryMappedFileAccess, MemoryMappedFileOptions, // MemoryMappedFileSecurity, HandleInheritability) //////////////////////////////////////////////////////////////////////// // [] mapName // mapname > 260 chars VerifyCreate("Loc411", "CreateOrOpen2" + new String('a', 1000) + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // null VerifyException<ArgumentNullException>("Loc412", null, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // empty string disallowed VerifyException<ArgumentException>("Loc413", String.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // all whitespace VerifyCreate("Loc414", "\t \n\u00A0", 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); if (Interop.IsWindows) // named maps not supported on Unix { // MMF with this mapname already exists (pagefile backed) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_map415a" + s_uniquifier, 1000)) { using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen("COO_map415a" + s_uniquifier, 1000)) { VerifyOpen("Loc415a", "COO_map415a" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } } // MMF with this mapname already exists (filesystem backed) File.WriteAllText(s_fileNameTest, fileText); using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(s_fileNameTest, FileMode.Open, "COO_map415b")) { VerifyOpen("Loc415b", "COO_map415b" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } } // MMF with this mapname existed, but was closed - new MMF VerifyCreate("Loc416", "COO_map415a" + s_uniquifier, 500, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // "global/" prefix VerifyCreate("Loc417", "global/COO_mapname" + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // "local/" prefix VerifyCreate("Loc418", "local/COO_mapname" + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // [] capacity // >0 capacity VerifyCreate("Loc421", "COO_mapname421" + s_uniquifier, 50, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // 0 capacity VerifyException<ArgumentOutOfRangeException>("Loc422", "COO_mapname422" + s_uniquifier, 0, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // negative VerifyException<ArgumentOutOfRangeException>("Loc423", "COO_mapname423" + s_uniquifier, -1, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // negative VerifyException<ArgumentOutOfRangeException>("Loc424", "COO_mapname424" + s_uniquifier, -4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // Int64.MaxValue - cannot exceed local address space if (IntPtr.Size == 4) VerifyException<ArgumentOutOfRangeException>("Loc425", "COO_mapname425" + s_uniquifier, Int64.MaxValue, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); else // 64-bit machine VerifyException<IOException>("Loc425b", "COO_mapname425" + s_uniquifier, Int64.MaxValue, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // valid but too large if (Interop.IsWindows) // named maps not supported on Unix { // ignored for existing file (smaller) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname426" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyOpen("Loc426", "COO_mapname426" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } // ignored for existing file (larger) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname427" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyOpen("Loc427", "COO_mapname427" + s_uniquifier, 10000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } // existing file - invalid - still exception using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname428" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyException<ArgumentOutOfRangeException>("Loc428", "COO_mapname428" + s_uniquifier, 0, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } } // [] access // Write is disallowed for new file VerifyException<ArgumentException>("Loc430", "COO_mapname430" + s_uniquifier, 1000, MemoryMappedFileAccess.Write, MemoryMappedFileOptions.None, HandleInheritability.None); // valid access for a new file accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreate("Loc431_" + access, "COO_mapname431_" + access + s_uniquifier, 1000, access, MemoryMappedFileOptions.None, HandleInheritability.None); } // invalid enum value accessList = new MemoryMappedFileAccess[] { (MemoryMappedFileAccess)(-1), (MemoryMappedFileAccess)(6), }; foreach (MemoryMappedFileAccess access in accessList) { VerifyException<ArgumentOutOfRangeException>("Loc432_" + ((int)access), "COO_mapname432_" + ((int)access) + s_uniquifier, 1000, access, MemoryMappedFileOptions.None, HandleInheritability.None); } if (Interop.IsWindows) // named maps not supported on Unix { // default security - all valid using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname433" + s_uniquifier, 1000)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyOpen("Loc433_" + access, "COO_mapname433" + s_uniquifier, 1000, access, MemoryMappedFileOptions.None, HandleInheritability.None, access); } } // default security, original (lesser) viewAccess is respected using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname434" + s_uniquifier, 1000, MemoryMappedFileAccess.Read)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyOpen("Loc434_" + access, "COO_mapname434" + s_uniquifier, 1000, access, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.Read); } VerifyOpen("Loc434_Write", "COO_mapname434" + s_uniquifier, 1000, MemoryMappedFileAccess.Write, MemoryMappedFileOptions.None, HandleInheritability.None, (MemoryMappedFileAccess)(-1)); // for current architecture, rights=Write implies ReadWrite access but not Read, so no expected access here } } // [] options // Default VerifyCreate("Loc440a", "COO_mapname440a" + s_uniquifier, 4096 * 1000); VerifyCreate("Loc440b", "COO_mapname440b" + s_uniquifier, 4096 * 10000); // None - new file VerifyCreate("Loc441", "COO_mapname441" + s_uniquifier, 4096 * 10000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // DelayAllocatePages - new file VerifyCreate("Loc442", "COO_mapname442" + s_uniquifier, 4096 * 10000, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.None); // invalid VerifyException<ArgumentOutOfRangeException>("Loc443", "COO_mapname443" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, (MemoryMappedFileOptions)(-1), HandleInheritability.None); if (Interop.IsWindows) // named maps not supported on Unix { // ignored for existing file using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname444" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyOpen("Loc444", "COO_mapname444" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } } // [] memoryMappedFileSecurity // null, tested throughout this file // valid non-null VerifyCreate("Loc451", "COO_mapname451" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); if (Interop.IsWindows) // named maps not supported on Unix { // ignored for existing using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("COO_mapname452" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)) { VerifyOpen("Loc452", "COO_mapname452" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } } // [] inheritability // None - new file VerifyCreate("Loc461", "COO_mapname461" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // Inheritable - new file VerifyCreate("Loc462", "COO_mapname462" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.Inheritable); if (Interop.IsWindows) // named maps not supported on Unix { // Mix and match: None - existing file w/Inheritable using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("COO_mapname464" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.Inheritable)) { VerifyOpen("Loc464a", "COO_mapname464" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None, MemoryMappedFileAccess.ReadWrite); } // Mix and match: Inheritable - existing file w/None using (FileStream fs = new FileStream(s_fileNameTest, FileMode.Open)) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, "COO_mapname465" + s_uniquifier, 1000, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false)) { VerifyOpen("Loc465b", "COO_mapname465" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.Inheritable, MemoryMappedFileAccess.ReadWrite); } } } // invalid VerifyException<ArgumentOutOfRangeException>("Loc467", "COO_mapname467" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, (HandleInheritability)(-1)); VerifyException<ArgumentOutOfRangeException>("Loc468", "COO_mapname468" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, (HandleInheritability)(2)); /// END TEST CASES if (iCountErrors == 0) { return true; } else { Console.WriteLine("FAiL! iCountErrors==" + iCountErrors); return false; } } catch (Exception ex) { Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex); return false; } } /// START HELPER FUNCTIONS public void VerifyCreate(String strLoc, String mapName, long capacity) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { VerifyAccess(strLoc, mmf, MemoryMappedFileAccess.ReadWrite, capacity); VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyOpen(String strLoc, String mapName, long capacity, MemoryMappedFileAccess expectedAccess) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None); VerifyAccess(strLoc, mmf, expectedAccess, 10); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyException<EXCTYPE>(String strLoc, String mapName, long capacity) where EXCTYPE : Exception { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreate(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { VerifyAccess(strLoc, mmf, access, capacity); VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyOpen(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileAccess expectedAccess) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None); VerifyAccess(strLoc, mmf, expectedAccess, 10); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyException<EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access) where EXCTYPE : Exception { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreate(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { VerifyAccess(strLoc, mmf, access, capacity); VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyOpen(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability, MemoryMappedFileAccess expectedAccess) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability); VerifyAccess(strLoc, mmf, expectedAccess, 10); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyException<EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) where EXCTYPE : Exception { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } }
using System; using System.Collections; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace DBlog.Tools.WebControls { public enum PagedGridSortDirection { Ascending, Descending } public class PagedGrid : DataGrid { private int mFirst = -1; private ArrayList mPagers = null; private PagedDataSource mPagedDataSource = null; public event EventHandler OnGetDataSource = null; public PagedGrid() { } public int First { get { if (mFirst == -1) { object ViewStateFirst = ViewState["First"]; if (ViewStateFirst != null) { mFirst = (int)ViewStateFirst; } } return mFirst; } set { mFirst = value; ViewState["First"] = value; } } public string SortExpression { get { object result = ViewState["SortExpression"]; return (result == null) ? string.Empty : (string)result; } set { ViewState["SortExpression"] = value; } } public PagedGridSortDirection SortDirection { get { object result = ViewState["SortDirection"]; return (result == null) ? PagedGridSortDirection.Ascending : (PagedGridSortDirection) Enum.Parse(typeof(PagedGridSortDirection), result.ToString()); } set { ViewState["SortDirection"] = value.ToString(); } } public ArrayList Pagers { get { if (mPagers == null) { mPagers = new ArrayList(); } return mPagers; } set { mPagers = value; } } public PagedDataSource PagedDataSource { get { return mPagedDataSource; } set { mPagedDataSource = value; } } protected override void OnPageIndexChanged(DataGridPageChangedEventArgs e) { if (OnGetDataSource != null) { CurrentPageIndex = PagedDataSource.CurrentPageIndex; OnGetDataSource(this, e); DataBind(); } base.OnPageIndexChanged(e); } protected override void InitializePager(DataGridItem item, int columnSpan, PagedDataSource pagedDataSource) { PagedDataSource = pagedDataSource; Pager Pager = new Pager(pagedDataSource, columnSpan, PagerStyle); Pager.PageIndexChanged += new DataGridPageChangedEventHandler(Pager_PageIndexChanged); Pager.First = First; item.Cells.Add(Pager.Navigator); Pagers.Add(Pager); } protected override void OnPreRender(EventArgs e) { foreach (Pager Pager in Pagers) { Pager.First = First; Pager.PreRenderCommands(); } base.OnPreRender(e); } private void Pager_PageIndexChanged(object source, DataGridPageChangedEventArgs e) { First = ((Pager)source).First; } public int FindHeaderColumnIndex(string HeaderValue) { for (int Result = 0; Result < Columns.Count; Result++) { DataGridColumn DataColumn = Columns[Result]; if (DataColumn.HeaderText == HeaderValue) { return Result; } } return -1; } public int FindButtonColumnIndex(string CommandName) { for (int Result = 0; Result < Columns.Count; Result++) { DataGridColumn DataColumn = Columns[Result]; if (DataColumn is ButtonColumn) { ButtonColumn DataButtonColumn = (ButtonColumn)DataColumn; if (DataButtonColumn.CommandName == CommandName) { return Result; } } } return -1; } public int FindBoundColumnIndex(string BoundDataField) { for (int Result = 0; Result < Columns.Count; Result++) { DataGridColumn DataColumn = Columns[Result]; if (DataColumn is BoundColumn) { BoundColumn DataBoundColumn = (BoundColumn)DataColumn; if (DataBoundColumn.DataField == BoundDataField) { return Result; } } } return -1; } protected override void OnItemDataBound(DataGridItemEventArgs e) { switch (e.Item.ItemType) { case ListItemType.AlternatingItem: case ListItemType.Item: case ListItemType.SelectedItem: case ListItemType.EditItem: int DeleteButtonColumnIndex = FindButtonColumnIndex("Delete"); if (DeleteButtonColumnIndex >= 0) { LinkButton DeleteButton = (LinkButton)e.Item.Cells[DeleteButtonColumnIndex].Controls[0]; DeleteButton.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this item?');"); } break; } base.OnItemDataBound(e); } protected override void OnSortCommand(DataGridSortCommandEventArgs e) { if (OnGetDataSource != null) { if (SortExpression == e.SortExpression) { SortDirection = (SortDirection == PagedGridSortDirection.Ascending) ? PagedGridSortDirection.Descending : PagedGridSortDirection.Ascending; } SortExpression = e.SortExpression; CurrentPageIndex = 0; OnGetDataSource(this, e); DataBind(); } base.OnSortCommand(e); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Ink.Runtime { /// <summary> /// Base class for all ink runtime content. /// </summary> public /* TODO: abstract */ class Object { /// <summary> /// Runtime.Objects can be included in the main Story as a hierarchy. /// Usually parents are Container objects. (TODO: Always?) /// </summary> /// <value>The parent.</value> public Runtime.Object parent { get; set; } public Runtime.DebugMetadata debugMetadata { get { if (_debugMetadata == null) { if (parent) { return parent.debugMetadata; } } return _debugMetadata; } set { _debugMetadata = value; } } public Runtime.DebugMetadata ownDebugMetadata { get { return _debugMetadata; } } // TODO: Come up with some clever solution for not having // to have debug metadata on the object itself, perhaps // for serialisation purposes at least. DebugMetadata _debugMetadata; public int? DebugLineNumberOfPath(Path path) { if (path == null) return null; // Try to get a line number from debug metadata var root = this.rootContentContainer; if (root) { Runtime.Object targetContent = root.ContentAtPath (path).obj; if (targetContent) { var dm = targetContent.debugMetadata; if (dm != null) { return dm.startLineNumber; } } } return null; } public Path path { get { if (_path == null) { if (parent == null) { _path = new Path (); } else { // Maintain a Stack so that the order of the components // is reversed when they're added to the Path. // We're iterating up the hierarchy from the leaves/children to the root. var comps = new Stack<Path.Component> (); var child = this; Container container = child.parent as Container; while (container) { var namedChild = child as INamedContent; if (namedChild != null && namedChild.hasValidName) { comps.Push (new Path.Component (namedChild.name)); } else { comps.Push (new Path.Component (container.content.IndexOf(child))); } child = container; container = container.parent as Container; } _path = new Path (comps); } } return _path; } } Path _path; public SearchResult ResolvePath(Path path) { if (path.isRelative) { Container nearestContainer = this as Container; if (!nearestContainer) { Debug.Assert (this.parent != null, "Can't resolve relative path because we don't have a parent"); nearestContainer = this.parent as Container; Debug.Assert (nearestContainer != null, "Expected parent to be a container"); Debug.Assert (path.GetComponent(0).isParent); path = path.tail; } return nearestContainer.ContentAtPath (path); } else { return this.rootContentContainer.ContentAtPath (path); } } public Path ConvertPathToRelative(Path globalPath) { // 1. Find last shared ancestor // 2. Drill up using ".." style (actually represented as "^") // 3. Re-build downward chain from common ancestor var ownPath = this.path; int minPathLength = Math.Min (globalPath.length, ownPath.length); int lastSharedPathCompIndex = -1; for (int i = 0; i < minPathLength; ++i) { var ownComp = ownPath.GetComponent(i); var otherComp = globalPath.GetComponent(i); if (ownComp.Equals (otherComp)) { lastSharedPathCompIndex = i; } else { break; } } // No shared path components, so just use global path if (lastSharedPathCompIndex == -1) return globalPath; int numUpwardsMoves = (ownPath.length-1) - lastSharedPathCompIndex; var newPathComps = new List<Path.Component> (); for(int up=0; up<numUpwardsMoves; ++up) newPathComps.Add (Path.Component.ToParent ()); for (int down = lastSharedPathCompIndex + 1; down < globalPath.length; ++down) newPathComps.Add (globalPath.GetComponent(down)); var relativePath = new Path (newPathComps, relative:true); return relativePath; } // Find most compact representation for a path, whether relative or global public string CompactPathString(Path otherPath) { string globalPathStr = null; string relativePathStr = null; if (otherPath.isRelative) { relativePathStr = otherPath.componentsString; globalPathStr = this.path.PathByAppendingPath(otherPath).componentsString; } else { var relativePath = ConvertPathToRelative (otherPath); relativePathStr = relativePath.componentsString; globalPathStr = otherPath.componentsString; } if (relativePathStr.Length < globalPathStr.Length) return relativePathStr; else return globalPathStr; } public Container rootContentContainer { get { Runtime.Object ancestor = this; while (ancestor.parent) { ancestor = ancestor.parent; } return ancestor as Container; } } public Object () { } public virtual Object Copy() { throw new System.NotImplementedException (GetType ().Name + " doesn't support copying"); } public void SetChild<T>(ref T obj, T value) where T : Runtime.Object { if (obj) obj.parent = null; obj = value; if( obj ) obj.parent = this; } /// Allow implicit conversion to bool so you don't have to do: /// if( myObj != null ) ... public static implicit operator bool (Object obj) { var isNull = object.ReferenceEquals (obj, null); return !isNull; } /// Required for implicit bool comparison public static bool operator ==(Object a, Object b) { return object.ReferenceEquals (a, b); } /// Required for implicit bool comparison public static bool operator !=(Object a, Object b) { return !(a == b); } /// Required for implicit bool comparison public override bool Equals (object obj) { return object.ReferenceEquals (obj, this); } /// Required for implicit bool comparison public override int GetHashCode () { return base.GetHashCode (); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the OrganizationMetaDataLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in OrganizationMetaDataLogicBase by making a partial class of OrganizationMetaDataLogic // and overriding the base methods. namespace VotingInfo.Database.Logic.Data { public partial class OrganizationMetaDataLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run OrganizationMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> public static int? InsertNow(int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue ) { return (new OrganizationMetaDataLogic()).Insert(fldContentInspectionId , fldOrganizationId , fldMetaDataId , fldMetaDataValue ); } /// <summary> /// Run OrganizationMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Insert(fldContentInspectionId , fldOrganizationId , fldMetaDataId , fldMetaDataValue , connection, transaction); } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(OrganizationMetaDataContract row) { return (new OrganizationMetaDataLogic()).Insert(row); } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Insert(row, connection, transaction); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<OrganizationMetaDataContract> rows) { return (new OrganizationMetaDataLogic()).InsertAll(rows); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run OrganizationMetaData_Update. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldOrganizationMetaDataId , int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue ) { return (new OrganizationMetaDataLogic()).Update(fldOrganizationMetaDataId , fldContentInspectionId , fldOrganizationId , fldMetaDataId , fldMetaDataValue ); } /// <summary> /// Run OrganizationMetaData_Update. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldOrganizationMetaDataId , int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Update(fldOrganizationMetaDataId , fldContentInspectionId , fldOrganizationId , fldMetaDataId , fldMetaDataValue , connection, transaction); } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(OrganizationMetaDataContract row) { return (new OrganizationMetaDataLogic()).Update(row); } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Update(row, connection, transaction); } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<OrganizationMetaDataContract> rows) { return (new OrganizationMetaDataLogic()).UpdateAll(rows); } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run OrganizationMetaData_Delete. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldOrganizationMetaDataId ) { return (new OrganizationMetaDataLogic()).Delete(fldOrganizationMetaDataId ); } /// <summary> /// Run OrganizationMetaData_Delete. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldOrganizationMetaDataId , SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Delete(fldOrganizationMetaDataId , connection, transaction); } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(OrganizationMetaDataContract row) { return (new OrganizationMetaDataLogic()).Delete(row); } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Delete(row, connection, transaction); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<OrganizationMetaDataContract> rows) { return (new OrganizationMetaDataLogic()).DeleteAll(rows); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldOrganizationMetaDataId ) { return (new OrganizationMetaDataLogic()).Exists(fldOrganizationMetaDataId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldOrganizationMetaDataId , SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).Exists(fldOrganizationMetaDataId , connection, transaction); } /// <summary> /// Run OrganizationMetaData_Search, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SearchNow(string fldMetaDataValue ) { var driver = new OrganizationMetaDataLogic(); driver.Search(fldMetaDataValue ); return driver.Results; } /// <summary> /// Run OrganizationMetaData_Search, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SearchNow(string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { var driver = new OrganizationMetaDataLogic(); driver.Search(fldMetaDataValue , connection, transaction); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectAll, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectAllNow() { var driver = new OrganizationMetaDataLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectAll, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new OrganizationMetaDataLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationMetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_OrganizationMetaDataIdNow(int fldOrganizationMetaDataId ) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_OrganizationMetaDataId(fldOrganizationMetaDataId ); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationMetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_OrganizationMetaDataIdNow(int fldOrganizationMetaDataId , SqlConnection connection, SqlTransaction transaction) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_OrganizationMetaDataId(fldOrganizationMetaDataId , connection, transaction); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_ContentInspectionId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId ) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId ); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_ContentInspectionId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId , connection, transaction); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_OrganizationIdNow(int fldOrganizationId ) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_OrganizationId(fldOrganizationId ); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_OrganizationIdNow(int fldOrganizationId , SqlConnection connection, SqlTransaction transaction) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_OrganizationId(fldOrganizationId , connection, transaction); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_MetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_MetaDataIdNow(int fldMetaDataId ) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_MetaDataId(fldMetaDataId ); return driver.Results; } /// <summary> /// Run OrganizationMetaData_SelectBy_MetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public static List<OrganizationMetaDataContract> SelectBy_MetaDataIdNow(int fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { var driver = new OrganizationMetaDataLogic(); driver.SelectBy_MetaDataId(fldMetaDataId , connection, transaction); return driver.Results; } /// <summary> /// Read all OrganizationMetaData rows from the provided reader into the list structure of OrganizationMetaDataRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated OrganizationMetaDataRows or an empty OrganizationMetaDataRows if there are no results.</returns> public static List<OrganizationMetaDataContract> ReadAllNow(SqlDataReader reader) { var driver = new OrganizationMetaDataLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a OrganizationMetaData /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A OrganizationMetaData or null if there are no results.</returns> public static OrganizationMetaDataContract ReadOneNow(SqlDataReader reader) { var driver = new OrganizationMetaDataLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(OrganizationMetaDataContract row) { if(row.OrganizationMetaDataId == null) { return InsertNow(row); } else { return UpdateNow(row); } } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { if(row.OrganizationMetaDataId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(row, connection, transaction); } } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<OrganizationMetaDataContract> rows) { return (new OrganizationMetaDataLogic()).SaveAll(rows); } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new OrganizationMetaDataLogic()).SaveAll(rows, connection, transaction); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.cache; using umbraco.cms.businesslogic.property; using umbraco.cms.businesslogic.web; using umbraco.cms.helpers; using umbraco.DataLayer; using umbraco.interfaces; using DataTypeDefinition = umbraco.cms.businesslogic.datatype.DataTypeDefinition; using Language = umbraco.cms.businesslogic.language.Language; namespace umbraco.cms.businesslogic.propertytype { /// <summary> /// Summary description for propertytype. /// </summary> [Obsolete("Use the ContentTypeService instead")] public class PropertyType { #region Declarations private readonly int _contenttypeid; private readonly int _id; private int _DataTypeId; private string _alias; private string _description = ""; private bool _mandatory; private string _name; private int _sortOrder; private int _tabId; private int _propertyTypeGroup; private string _validationRegExp = ""; #endregion protected static ISqlHelper SqlHelper { get { return Application.SqlHelper; } } #region Constructors public PropertyType(int id) { using (IRecordsReader dr = SqlHelper.ExecuteReader( "Select mandatory, DataTypeId, propertyTypeGroupId, ContentTypeId, sortOrder, alias, name, validationRegExp, description from cmsPropertyType where id=@id", SqlHelper.CreateParameter("@id", id))) { if (!dr.Read()) throw new ArgumentException("Propertytype with id: " + id + " doesnt exist!"); _mandatory = dr.GetBoolean("mandatory"); _id = id; if (!dr.IsNull("propertyTypeGroupId")) { _propertyTypeGroup = dr.GetInt("propertyTypeGroupId"); //TODO: Remove after refactoring! _tabId = _propertyTypeGroup; } _sortOrder = dr.GetInt("sortOrder"); _alias = dr.GetString("alias"); _name = dr.GetString("Name"); _validationRegExp = dr.GetString("validationRegExp"); _DataTypeId = dr.GetInt("DataTypeId"); _contenttypeid = dr.GetInt("contentTypeId"); _description = dr.GetString("description"); } } #endregion #region Properties public DataTypeDefinition DataTypeDefinition { get { return DataTypeDefinition.GetDataTypeDefinition(_DataTypeId); } set { _DataTypeId = value.Id; InvalidateCache(); SqlHelper.ExecuteNonQuery( "Update cmsPropertyType set DataTypeId = " + value.Id + " where id=" + Id); } } public int Id { get { return _id; } } /// <summary> /// Setting the tab id is not meant to be used directly in code. Use the ContentType SetTabOnPropertyType method instead /// as that will handle all of the caching properly, this will not. /// </summary> /// <remarks> /// Setting the tab id to a negative value will actually set the value to NULL in the database /// </remarks> [Obsolete("Use the new PropertyTypeGroup parameter", false)] public int TabId { get { return _tabId; } set { _tabId = value; PropertyTypeGroup = value; InvalidateCache(); } } public int PropertyTypeGroup { get { return _propertyTypeGroup; } set { _propertyTypeGroup = value; object dbPropertyTypeGroup = value; if (value < 1) { dbPropertyTypeGroup = DBNull.Value; } SqlHelper.ExecuteNonQuery("Update cmsPropertyType set propertyTypeGroupId = @propertyTypeGroupId where id = @id", SqlHelper.CreateParameter("@propertyTypeGroupId", dbPropertyTypeGroup), SqlHelper.CreateParameter("@id", Id)); } } public bool Mandatory { get { return _mandatory; } set { _mandatory = value; InvalidateCache(); SqlHelper.ExecuteNonQuery( "Update cmsPropertyType set mandatory = @mandatory where id = @id", SqlHelper.CreateParameter("@mandatory", value), SqlHelper.CreateParameter("@id", Id)); } } public string ValidationRegExp { get { return _validationRegExp; } set { _validationRegExp = value; InvalidateCache(); SqlHelper.ExecuteNonQuery( "Update cmsPropertyType set validationRegExp = @validationRegExp where id = @id", SqlHelper.CreateParameter("@validationRegExp", value), SqlHelper.CreateParameter("@id", Id)); } } public string Description { get { if (_description != null) { if (!_description.StartsWith("#")) return _description; else { Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); if (lang != null) { if (Dictionary.DictionaryItem.hasKey(_description.Substring(1, _description.Length - 1))) { var di = new Dictionary.DictionaryItem(_description.Substring(1, _description.Length - 1)); return di.Value(lang.id); } } } return "[" + _description + "]"; } return _description; } set { _description = value; InvalidateCache(); SqlHelper.ExecuteNonQuery( "Update cmsPropertyType set description = @description where id = @id", SqlHelper.CreateParameter("@description", value), SqlHelper.CreateParameter("@id", Id)); } } public int SortOrder { get { return _sortOrder; } set { _sortOrder = value; InvalidateCache(); SqlHelper.ExecuteNonQuery( "Update cmsPropertyType set sortOrder = @sortOrder where id = @id", SqlHelper.CreateParameter("@sortOrder", value), SqlHelper.CreateParameter("@id", Id)); } } public string Alias { get { return _alias; } set { _alias = value; InvalidateCache(); SqlHelper.ExecuteNonQuery("Update cmsPropertyType set alias = @alias where id= @id", SqlHelper.CreateParameter("@alias", Casing.SafeAliasWithForcingCheck(_alias)), SqlHelper.CreateParameter("@id", Id)); } } public int ContentTypeId { get { return _contenttypeid; } } public string Name { get { if (!_name.StartsWith("#")) return _name; else { Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); if (lang != null) { if (Dictionary.DictionaryItem.hasKey(_name.Substring(1, _name.Length - 1))) { var di = new Dictionary.DictionaryItem(_name.Substring(1, _name.Length - 1)); return di.Value(lang.id); } } return "[" + _name + "]"; } } set { _name = value; InvalidateCache(); SqlHelper.ExecuteNonQuery( "UPDATE cmsPropertyType SET name=@name WHERE id=@id", SqlHelper.CreateParameter("@name", _name), SqlHelper.CreateParameter("@id", Id)); } } #endregion #region Methods public string GetRawName() { return _name; } public string GetRawDescription() { return _description; } [MethodImpl(MethodImplOptions.Synchronized)] public static PropertyType MakeNew(DataTypeDefinition dt, ContentType ct, string name, string alias) { //make sure that the alias starts with a letter if (string.IsNullOrEmpty(alias)) throw new ArgumentNullException("alias"); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); if (!Char.IsLetter(alias[0])) throw new ArgumentException("alias must start with a letter", "alias"); PropertyType pt; try { // The method is synchronized, but we'll still look it up with an additional parameter (alias) SqlHelper.ExecuteNonQuery( "INSERT INTO cmsPropertyType (DataTypeId, ContentTypeId, alias, name) VALUES (@DataTypeId, @ContentTypeId, @alias, @name)", SqlHelper.CreateParameter("@DataTypeId", dt.Id), SqlHelper.CreateParameter("@ContentTypeId", ct.Id), SqlHelper.CreateParameter("@alias", alias), SqlHelper.CreateParameter("@name", name)); pt = new PropertyType( SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM cmsPropertyType WHERE alias=@alias", SqlHelper.CreateParameter("@alias", alias))); } finally { // Clear cached items ApplicationContext.Current.ApplicationCache.ClearCacheByKeySearch(CacheKeys.PropertyTypeCacheKey); } return pt; } public static PropertyType[] GetAll() { var result = GetPropertyTypes(); return result.ToArray(); } public static IEnumerable<PropertyType> GetPropertyTypes() { var result = new List<PropertyType>(); using (IRecordsReader dr = SqlHelper.ExecuteReader("select id from cmsPropertyType order by Name")) { while (dr.Read()) { PropertyType pt = GetPropertyType(dr.GetInt("id")); if (pt != null) result.Add(pt); } } return result; } public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId, List<int> contentTypeIds) { return GetPropertyTypesByGroup(groupId).Where(x => contentTypeIds.Contains(x.ContentTypeId)); } public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId) { var result = new List<PropertyType>(); using (IRecordsReader dr = SqlHelper.ExecuteReader("SELECT id FROM cmsPropertyType WHERE propertyTypeGroupId = @groupId order by SortOrder", SqlHelper.CreateParameter("@groupId", groupId))) { while (dr.Read()) { PropertyType pt = GetPropertyType(dr.GetInt("id")); if (pt != null) result.Add(pt); } } return result; } /// <summary> /// Returns all property types based on the data type definition /// </summary> /// <param name="dataTypeDefId"></param> /// <returns></returns> public static IEnumerable<PropertyType> GetByDataTypeDefinition(int dataTypeDefId) { var result = new List<PropertyType>(); using (IRecordsReader dr = SqlHelper.ExecuteReader( "select id, Name from cmsPropertyType where dataTypeId=@dataTypeId order by Name", SqlHelper.CreateParameter("@dataTypeId", dataTypeDefId))) { while (dr.Read()) { PropertyType pt = GetPropertyType(dr.GetInt("id")); if (pt != null) result.Add(pt); } } return result.ToList(); } public void delete() { // flush cache FlushCache(); // Delete all properties of propertytype CleanPropertiesOnDeletion(_contenttypeid); //delete tag refs SqlHelper.ExecuteNonQuery("Delete from cmsTagRelationship where propertyTypeId = " + Id); // Delete PropertyType .. SqlHelper.ExecuteNonQuery("Delete from cmsPropertyType where id = " + Id); // delete cache from either master (via tabid) or current contentype FlushCacheBasedOnTab(); InvalidateCache(); } public void FlushCacheBasedOnTab() { if (TabId != 0) { ContentType.FlushFromCache(ContentType.Tab.GetTab(TabId).ContentType); } else { ContentType.FlushFromCache(ContentTypeId); } } private void CleanPropertiesOnDeletion(int contentTypeId) { // first delete from all master document types //TODO: Verify no endless loops with mixins DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentTypes.Contains(contentTypeId)).ForEach( dt => CleanPropertiesOnDeletion(dt.Id)); //Initially Content.getContentOfContentType() was called, but because this doesn't include members we resort to sql lookups and deletes var tmp = new List<int>(); IRecordsReader dr = SqlHelper.ExecuteReader("SELECT nodeId FROM cmsContent INNER JOIN umbracoNode ON cmsContent.nodeId = umbracoNode.id WHERE ContentType = " + contentTypeId + " ORDER BY umbracoNode.text "); while (dr.Read()) tmp.Add(dr.GetInt("nodeId")); dr.Close(); foreach (var contentId in tmp) { SqlHelper.ExecuteNonQuery("DELETE FROM cmsPropertyData WHERE PropertyTypeId =" + this.Id + " AND contentNodeId = " + contentId); } // invalidate content type cache ContentType.FlushFromCache(contentTypeId); } public IDataType GetEditControl(object value, bool isPostBack) { IDataType dt = DataTypeDefinition.DataType; dt.DataEditor.Editor.ID = Alias; IData df = DataTypeDefinition.DataType.Data; (dt.DataEditor.Editor).ID = Alias; if (!isPostBack) { if (value != null) dt.Data.Value = value; else dt.Data.Value = ""; } return dt; } /// <summary> /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility /// </summary> public virtual void Save() { FlushCache(); } protected virtual void FlushCache() { // clear local cache ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id)); // clear cache in contentype ApplicationContext.Current.ApplicationCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + _contenttypeid); //Ensure that DocumentTypes are reloaded from db by clearing cache - this similar to the Save method on DocumentType. //NOTE Would be nice if we could clear cache by type instead of emptying the entire cache. ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes<IContent>(); ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes<IContentType>(); ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes<IMedia>(); ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes<IMediaType>(); ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes<IMember>(); ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes<IMemberType>(); } public static PropertyType GetPropertyType(int id) { return ApplicationContext.Current.ApplicationCache.GetCacheItem( GetCacheKey(id), TimeSpan.FromMinutes(30), delegate { try { return new PropertyType(id); } catch { return null; } }); } private void InvalidateCache() { ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id)); } private static string GetCacheKey(int id) { return CacheKeys.PropertyTypeCacheKey + id; } #endregion } }
using System; using System.Threading.Tasks; using System.Web; using System.Net; using System.Text; using System.IO; using System.Threading; using System.Collections.Generic; using System.Security.Cryptography; using System.ComponentModel; using SteamBot.SteamGroups; using SteamKit2; using SteamTrade; using SteamKit2.Internal; namespace SteamBot { public class Bot { public string BotControlClass; // If the bot is logged in fully or not. This is only set // when it is. public bool IsLoggedIn = false; // The bot's display name. Changing this does not mean that // the bot's name will change. public string DisplayName { get; private set; } // The response to all chat messages sent to it. public string ChatResponse; // A list of SteamIDs that this bot recognizes as admins. public ulong[] Admins; public SteamFriends SteamFriends; public SteamClient SteamClient; public SteamTrading SteamTrade; public SteamUser SteamUser; public SteamGameCoordinator SteamGameCoordinator; // The current trade; if the bot is not in a trade, this is // null. public Trade CurrentTrade; public bool IsDebugMode = false; // The log for the bot. This logs with the bot's display name. public Log log; public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); public UserHandlerCreator CreateHandler; Dictionary<ulong, UserHandler> userHandlers = new Dictionary<ulong, UserHandler>(); List<SteamID> friends = new List<SteamID>(); // List of Steam groups the bot is in. private readonly List<SteamID> groups = new List<SteamID>(); // The maximum amount of time the bot will trade for. public int MaximumTradeTime { get; private set; } // The maximum amount of time the bot will wait in between // trade actions. public int MaximiumActionGap { get; private set; } //The current game that the bot is playing, for posterity. public int CurrentGame = 0; // The Steam Web API key. string apiKey; // The prefix put in the front of the bot's display name. string DisplayNamePrefix; // Log level to use for this bot Log.LogLevel LogLevel; // The number, in milliseconds, between polls for the trade. int TradePollingInterval; public string MyLoginKey; string sessionId; string token; bool isprocess; public bool IsRunning = false; public string AuthCode { get; set; } SteamUser.LogOnDetails logOnDetails; TradeManager tradeManager; private Task<Inventory> myInventoryTask; public Inventory MyInventory { get { myInventoryTask.Wait(); return myInventoryTask.Result; } } private BackgroundWorker backgroundWorker; public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false) { logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximiumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; Admins = config.Admins; this.apiKey = apiKey; this.isprocess = process; try { LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); } catch (ArgumentException) { Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'"); LogLevel = Log.LogLevel.Info; } log = new Log (config.LogFile, this.DisplayName, LogLevel); CreateHandler = handlerCreator; BotControlClass = config.BotControlClass; // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; log.Debug ("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true }; backgroundWorker.DoWork += BackgroundWorkerOnDoWork; backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; backgroundWorker.RunWorkerAsync(); } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <remarks> /// THIS NEVER RETURNS. /// </remarks> /// <returns><c>true</c>. See remarks</returns> public bool StartBot() { IsRunning = true; log.Info("Connecting..."); if (!backgroundWorker.IsBusy) // background worker is not running backgroundWorker.RunWorkerAsync(); SteamClient.Connect(); log.Success("Done Loading Bot!"); return true; // never get here } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); backgroundWorker.CancelAsync(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade (SteamID other) { if (CurrentTrade != null) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade (); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout(); } public void HandleBotCommand(string command) { try { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } bool HandleTradeSessionStart (SteamID other) { if (CurrentTrade != null) return false; try { tradeManager.InitializeTrade(SteamUser.SteamID, other); CurrentTrade = tradeManager.CreateTrade (SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException ie) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); log.Info ("Bot sent other: " + response); CurrentTrade = null; return false; } } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } void HandleSteamMessage (CallbackMsg msg) { log.Debug(msg.ToString()); #region Login msg.Handle<SteamClient.ConnectedCallback> (callback => { log.Debug ("Connection Callback: " + callback.Result); if (callback.Result == EResult.OK) { UserLogOn(); } else { log.Error ("Failed to connect to Steam Community, trying again..."); SteamClient.Connect (); } }); msg.Handle<SteamUser.LoggedOnCallback> (callback => { log.Debug ("Logged On Callback: " + callback.Result); if (callback.Result == EResult.OK) { MyLoginKey = callback.WebAPIUserNonce; } else { log.Error ("Login Error: " + callback.Result); } if (callback.Result == EResult.AccountLogonDenied) { log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } if (callback.Result == EResult.InvalidLoginAuthCode) { log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); msg.Handle<SteamUser.LoginKeyCallback> (callback => { while (true) { bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey); if (authd) { log.Success ("User Authenticated!"); tradeManager = new TradeManager(apiKey, sessionId, token); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; break; } else { log.Warn ("Authentication failed, retrying in 2s..."); Thread.Sleep (2000); } } if (Trade.CurrentSchema == null) { log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (apiKey); log.Success ("Schema Downloaded!"); } SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName); SteamFriends.SetPersonaState (EPersonaState.Online); log.Success ("Steam Bot Logged In Completely!"); IsLoggedIn = true; GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); // handle a special JobCallback differently than the others if (msg.IsType<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>()) { msg.Handle<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>( jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID) ); } #endregion #region Friends msg.Handle<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { if (friend.SteamID.AccountType == EAccountType.Clan) { if (!groups.Contains(friend.SteamID)) { groups.Add(friend.SteamID); if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } } else { if (friend.Relationship == EFriendRelationship.None) { groups.Remove(friend.SteamID); } } } else if (friend.SteamID.AccountType != EAccountType.Clan) { if (!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); if (friend.Relationship == EFriendRelationship.RequestRecipient && GetUserHandler(friend.SteamID).OnFriendAdd()) { SteamFriends.AddFriend(friend.SteamID); } } else { if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); } } } } }); msg.Handle<SteamFriends.FriendMsgCallback> (callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { log.Info (String.Format ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), callback.Message )); GetUserHandler(callback.Sender).OnMessage(callback.Message, type); } }); #endregion #region Group Chat msg.Handle<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading msg.Handle<SteamTrading.SessionStartCallback> (callback => { bool started = HandleTradeSessionStart (callback.OtherClient); if (!started) log.Error ("Could not start the trade session."); else log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened."); }); msg.Handle<SteamTrading.TradeProposedCallback> (callback => { try { tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient); } catch (WebException we) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade error: " + we.Message); SteamTrade.RespondToTrade(callback.TradeID, false); return; } catch (Exception) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade declined. Could not correctly fetch your backpack."); SteamTrade.RespondToTrade(callback.TradeID, false); return; } //if (tradeManager.OtherInventory.IsPrivate) //{ // SteamFriends.SendChatMessage(callback.OtherClient, // EChatEntryType.ChatMsg, // "Trade declined. Your backpack cannot be private."); // SteamTrade.RespondToTrade (callback.TradeID, false); // return; //} if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ()) SteamTrade.RespondToTrade (callback.TradeID, true); else SteamTrade.RespondToTrade (callback.TradeID, false); }); msg.Handle<SteamTrading.TradeResultCallback> (callback => { if (callback.Response == EEconTradeResponse.Accepted) { log.Debug ("Trade Status: " + callback.Response); log.Info ("Trade Accepted!"); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { log.Warn ("Trade failed: " + callback.Response); CloseTrade (); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect msg.Handle<SteamUser.LoggedOffCallback> (callback => { IsLoggedIn = false; log.Warn ("Logged Off: " + callback.Result); }); msg.Handle<SteamClient.DisconnectedCallback> (callback => { IsLoggedIn = false; CloseTrade (); log.Warn ("Disconnected from Steam Network!"); SteamClient.Connect (); }); #endregion } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } UserHandler GetUserHandler (SteamID sid) { if (!userHandlers.ContainsKey (sid)) { userHandlers [sid.ConvertToUInt64 ()] = CreateHandler (this, sid); } return userHandlers [sid.ConvertToUInt64 ()]; } static byte [] SHAHash (byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash( input ); sha.Clear(); return output; } void OnUpdateMachineAuthCallback (SteamUser.UpdateMachineAuthCallback machineAuth, JobID jobId) { byte[] hash = SHAHash (machineAuth.Data); Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = jobId, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse (authResponse); } /// <summary> /// Gets the bot's inventory and stores it in MyInventory. /// </summary> /// <example> This sample shows how to find items in the bot's inventory from a user handler. /// <code> /// Bot.GetInventory(); // Get the inventory first /// foreach (var item in Bot.MyInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // Bot has a key in its inventory /// } /// } /// </code> /// </example> public void GetInventory() { myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(SteamUser.SteamID, apiKey)); } /// <summary> /// Gets the other user's inventory and stores it in OtherInventory. /// </summary> /// <param name="OtherSID">The SteamID of the other user</param> /// <example> This sample shows how to find items in the other user's inventory from a user handler. /// <code> /// Bot.GetOtherInventory(OtherSID); // Get the inventory first /// foreach (var item in Bot.OtherInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // User has a key in its inventory /// } /// } /// </code> /// </example> public void GetOtherInventory(SteamID OtherSID) { Task.Factory.StartNew(() => Inventory.FetchInventory(OtherSID, apiKey)); } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade (Trade trade, UserHandler handler) { trade.OnSuccess += handler.OnTradeSuccess; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnUserAddItem += handler.OnTradeAddItem; trade.OnUserRemoveItem += handler.OnTradeRemoveItem; trade.OnMessage += handler.OnTradeMessage; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade (UserHandler handler, Trade trade) { trade.OnSuccess -= handler.OnTradeSuccess; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnUserAddItem -= handler.OnTradeAddItem; trade.OnUserRemoveItem -= handler.OnTradeRemoveItem; trade.OnMessage -= handler.OnTradeMessage; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; var s = string.Format("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); log.Error(s); log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } log.Dispose(); } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { CallbackMsg msg; while (!backgroundWorker.CancellationPending) { try { msg = SteamClient.WaitForCallback(true); HandleSteamMessage(msg); } catch (WebException e) { log.Error("URI: " + (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown") + " >> " + e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { log.Error(e.ToString()); log.Warn("Restarting bot..."); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #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 (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 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 TestCases.HSSF.Extractor { using System; using System.IO; using NPOI.HSSF.UserModel; using NPOI.POIFS.FileSystem; using NPOI.HSSF.Extractor; using TestCases.HSSF; using NUnit.Framework; using NPOI.HSSF.Record.Crypto; [TestFixture] public class TestExcelExtractor { private static ExcelExtractor CreateExtractor(String sampleFileName) { Stream is1 = HSSFTestDataSamples.OpenSampleFileStream(sampleFileName); try { return new ExcelExtractor(new POIFSFileSystem(is1)); } catch (IOException) { throw; } } [Test] public void TestSimple() { ExcelExtractor extractor = CreateExtractor("Simple.xls"); Assert.AreEqual("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.Text); // Now turn off sheet names extractor.IncludeSheetNames=false; Assert.AreEqual("replaceMe\n", extractor.Text); } [Test] public void TestNumericFormula() { ExcelExtractor extractor = CreateExtractor("sumifformula.xls"); string expected = "Sheet1\n" + "1000\t1\t5\n" + "2000\t2\n" + "3000\t3\n" + "4000\t4\n" + "5000\t5\n" + "Sheet2\nSheet3\n"; Assert.AreEqual( expected, extractor.Text ); extractor.FormulasNotResults=(true); Assert.AreEqual( "Sheet1\n" + "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + "2000\t2\n" + "3000\t3\n" + "4000\t4\n" + "5000\t5\n" + "Sheet2\nSheet3\n", extractor.Text ); } [Test] public void TestwithContinueRecords() { ExcelExtractor extractor = CreateExtractor("StringContinueRecords.xls"); //extractor.Text; // Has masses of text // Until we fixed bug #41064, this would've // failed by now Assert.IsTrue(extractor.Text.Length > 40960); } [Test] public void TestStringConcat() { ExcelExtractor extractor = CreateExtractor("SimpleWithFormula.xls"); // Comes out as NaN if treated as a number // And as XYZ if treated as a string Assert.AreEqual("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", extractor.Text); extractor.FormulasNotResults = (true); Assert.AreEqual("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.Text); } [Test] public void TestStringFormula() { ExcelExtractor extractor = CreateExtractor("StringFormulas.xls"); // Comes out as NaN if treated as a number // And as XYZ if treated as a string Assert.AreEqual("Sheet1\nXYZ\nSheet2\nSheet3\n", extractor.Text); extractor.FormulasNotResults = (true); Assert.AreEqual("Sheet1\nUPPER(\"xyz\")\nSheet2\nSheet3\n", extractor.Text); } [Test] public void TestEventExtractor() { EventBasedExcelExtractor extractor; // First up, a simple file with string // based formulas in it extractor = new EventBasedExcelExtractor( new POIFSFileSystem( HSSFTestDataSamples.OpenSampleFileStream("SimpleWithFormula.xls") ) ); extractor.IncludeSheetNames = (true); String text = extractor.Text; Assert.AreEqual("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", text); extractor.IncludeSheetNames = (false); extractor.FormulasNotResults = (true); text = extractor.Text; Assert.AreEqual("replaceme\nreplaceme\nCONCATENATE(A1,A2)\n", text); // Now, a slightly longer file with numeric formulas extractor = new EventBasedExcelExtractor( new POIFSFileSystem( HSSFTestDataSamples.OpenSampleFileStream("sumifformula.xls") ) ); extractor.IncludeSheetNames = (false); extractor.FormulasNotResults = (true); text = extractor.Text; Assert.AreEqual( "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + "2000\t2\n" + "3000\t3\n" + "4000\t4\n" + "5000\t5\n", text ); } [Test] public void TestWithComments() { ExcelExtractor extractor = CreateExtractor("SimpleWithComments.xls"); extractor.IncludeSheetNames = (false); // Check without comments Assert.AreEqual( "1\tone\n" + "2\ttwo\n" + "3\tthree\n", extractor.Text ); // Now with extractor.IncludeCellComments = (true); Assert.AreEqual( "1\tone Comment by Yegor Kozlov: Yegor Kozlov: first cell\n" + "2\ttwo Comment by Yegor Kozlov: Yegor Kozlov: second cell\n" + "3\tthree Comment by Yegor Kozlov: Yegor Kozlov: third cell\n", extractor.Text ); } [Test] public void TestWithBlank() { ExcelExtractor extractor = CreateExtractor("MissingBits.xls"); String def = extractor.Text; extractor.IncludeBlankCells = (true); String padded = extractor.Text; Assert.IsTrue(def.StartsWith( "Sheet1\n" + "&[TAB]\t\n" + "Hello\n" + "11\t23\n" )); Assert.IsTrue(padded.StartsWith( "Sheet1\n" + "&[TAB]\t\n" + "Hello\n" + "11\t\t\t23\n" )); } [Test] public void TestFormatting() { ExcelExtractor extractor = CreateExtractor("Formatting.xls"); extractor.IncludeBlankCells = (false); extractor.IncludeSheetNames = false; String text = extractor.Text; // Note - not all the formats in the file // actually quite match what they claim to // be, as some are auto-local builtins... Assert.IsTrue(text.StartsWith( "Dates, all 24th November 2006\n" )); Assert.IsTrue( text.IndexOf( "yyyy/mm/dd\t2006/11/24\n" ) > -1 ); Assert.IsTrue( text.IndexOf( "yyyy-mm-dd\t2006-11-24\n" ) > -1 ); Assert.IsTrue( text.IndexOf( "dd-mm-yy\t24-11-06\n" ) > -1 ); Assert.IsTrue( text.IndexOf( "nn.nn\t10.52\n" ) > -1 ); Assert.IsTrue( text.IndexOf( "nn.nnn\t10.520\n" ) > -1 ); Assert.IsTrue( text.IndexOf( "\u00a3nn.nn\t\u00a310.52\n" ) > -1 ); } /** * Embded in a non-excel file */ [Test] public void TestWithEmbeded() { POIFSFileSystem fs = new POIFSFileSystem( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("word_with_embeded.doc") ); DirectoryNode objPool = (DirectoryNode)fs.Root.GetEntry("ObjectPool"); DirectoryNode dirA = (DirectoryNode)objPool.GetEntry("_1269427460"); DirectoryNode dirB = (DirectoryNode)objPool.GetEntry("_1269427461"); HSSFWorkbook wbA = new HSSFWorkbook(dirA, fs, true); HSSFWorkbook wbB = new HSSFWorkbook(dirB, fs, true); ExcelExtractor exA = new ExcelExtractor(wbA); ExcelExtractor exB = new ExcelExtractor(wbB); Assert.AreEqual("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.Text); Assert.AreEqual("Sample Excel", exA.SummaryInformation.Title); Assert.AreEqual("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.Text); Assert.AreEqual("Sample Excel 2", exB.SummaryInformation.Title); } /** * Excel embeded in excel */ [Test] public void TestWithEmbededInOwn() { POIFSFileSystem fs = new POIFSFileSystem( HSSFTestDataSamples.OpenSampleFileStream("excel_with_embeded.xls") ); DirectoryNode dirA = (DirectoryNode)fs.Root.GetEntry("MBD0000A3B5"); DirectoryNode dirB = (DirectoryNode)fs.Root.GetEntry("MBD0000A3B4"); HSSFWorkbook wbA = new HSSFWorkbook(dirA, fs, true); HSSFWorkbook wbB = new HSSFWorkbook(dirB, fs, true); ExcelExtractor exA = new ExcelExtractor(wbA); ExcelExtractor exB = new ExcelExtractor(wbB); Assert.AreEqual("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.Text); Assert.AreEqual("Sample Excel", exA.SummaryInformation.Title); Assert.AreEqual("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.Text); Assert.AreEqual("Sample Excel 2", exB.SummaryInformation.Title); // And the base file too ExcelExtractor ex = new ExcelExtractor(fs); Assert.AreEqual("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n", ex.Text); Assert.AreEqual("Excel With Embeded", ex.SummaryInformation.Title); } /** * Test that we get text from headers and footers */ [Test] public void Test45538() { String[] files = { "45538_classic_Footer.xls", "45538_form_Footer.xls", "45538_classic_Header.xls", "45538_form_Header.xls" }; for (int i = 0; i < files.Length; i++) { ExcelExtractor extractor = CreateExtractor(files[i]); String text = extractor.Text; Assert.IsTrue(text.IndexOf("testdoc") >= 0, "Unable to find expected word in text\n" + text); Assert.IsTrue(text.IndexOf("test phrase") >= 0, "Unable to find expected word in text\n" + text); } } [Test] public void TestPassword() { Biff8EncryptionKey.CurrentUserPassword = ("password"); ExcelExtractor extractor = CreateExtractor("password.xls"); String text = extractor.Text; Biff8EncryptionKey.CurrentUserPassword = (null); Assert.IsTrue(text.Contains("ZIP")); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.IO.IsolatedStorage; using System.Xml.Serialization; using ExtendedWebBrowser2; using gma.System.Windows; namespace Amnesty_Hypercube { public partial class Form1 : Form { UserActivityHook actHook = new UserActivityHook(); private Point mouse; bool tracking = false; int track; int trackDelta; int trackDistance; int dragFloorIndex = -1; private Rectangle dragBoxFromMouseDown1 = Rectangle.Empty; private int rowIndexFromMouseDown1 = -1; private int rowIndexOfItemUnderMouseToDrop1 = -1; private Rectangle dragBoxFromMouseDown2 = Rectangle.Empty; private int rowIndexFromMouseDown2 = -1; private int rowIndexOfItemUnderMouseToDrop2 = -1; DataGridViewCell currentProvider = null; Keys providerKeyCode = 0; Boolean ignoreProviderSelect = false; string saveProviderTitle = null; ExtendedWebBrowser2.ExtendedWebBrowser browser = null; string providerInfoKey = null; string providerURLString = null; string browserURLString = null; string destinationLinkKey = null; public Form1() { InitializeComponent(); if (System.Environment.OSVersion.Version.Major < 6) { panel2.Width += 8; splitContainer1.Width += 8; } actHook.OnMouseActivity += new MouseEventHandler(global_MouseActivity); int x = Amnesty_Hypercube.Properties.Settings.Default.MainWindowLocation.X; int y = Amnesty_Hypercube.Properties.Settings.Default.MainWindowLocation.Y; int w = Amnesty_Hypercube.Properties.Settings.Default.MainWindowWidth; int h = Amnesty_Hypercube.Properties.Settings.Default.MainWindowHeight; this.WindowState = FormWindowState.Normal; this.SetDesktopBounds(x, y, w, h); if (Amnesty_Hypercube.Properties.Settings.Default.MainWindowMaximized) this.WindowState = FormWindowState.Maximized; if (Amnesty_Hypercube.Properties.Settings.Default.MainWindowMinimized) this.WindowState = FormWindowState.Minimized; if (Amnesty_Hypercube.Properties.Settings.Default.SourcePanelWidth != 0) splitContainer1.SplitterDistance = Amnesty_Hypercube.Properties.Settings.Default.SourcePanelWidth; splitContainer2.Panel2Collapsed = !Amnesty_Hypercube.Properties.Settings.Default.InfoPanelVisible; RestoreColumnWidth(); RestoreColumnOrder(); ToolTip tips = new ToolTip(); tips.SetToolTip(button1, Amnesty_Hypercube.Properties.Resources.TipLaunch); tips.SetToolTip(button2, Amnesty_Hypercube.Properties.Resources.TipExplore); tips.SetToolTip(button3, Amnesty_Hypercube.Properties.Resources.TipShowAll); tips.SetToolTip(button4, Amnesty_Hypercube.Properties.Resources.TipHideAll); tips.SetToolTip(button5, Amnesty_Hypercube.Properties.Resources.TipCloseAll); tips.SetToolTip(button6, Amnesty_Hypercube.Properties.Resources.TipInfo); tips.SetToolTip(button7, Amnesty_Hypercube.Properties.Resources.TipFull); button8.MouseDown += new MouseEventHandler(button8_MouseDown); button8.MouseUp += new MouseEventHandler(button8_MouseUp); button9.MouseDown += new MouseEventHandler(button9_MouseDown); button9.MouseUp += new MouseEventHandler(button9_MouseUp); button9.MouseClick += new MouseEventHandler(button9_MouseClick); button10.MouseDown += new MouseEventHandler(button10_MouseDown); button10.MouseUp += new MouseEventHandler(button10_MouseUp); button10.MouseMove += new MouseEventHandler(button10_MouseMove); contextMenuStrip2.Opening += new CancelEventHandler(contextMenuStrip2_Opening); contextMenuStrip2.Closing += new ToolStripDropDownClosingEventHandler(contextMenuStrip2_Closing); dataGridView1.MouseDown +=new MouseEventHandler(dataGridView1_MouseDown); dataGridView1.MouseMove += new MouseEventHandler(dataGridView1_MouseMove); dataGridView2.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView2_CellBeginEdit); dataGridView2.CellEndEdit += new DataGridViewCellEventHandler(dataGridView2_CellEndEdit); dataGridView2.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView2_CellPainting); dataGridView2.MouseDown += new MouseEventHandler(dataGridView2_MouseDown); dataGridView2.MouseMove += new MouseEventHandler(dataGridView2_MouseMove); dataGridView2.DragOver += new DragEventHandler(dataGridView2_DragOver); dataGridView2.DragDrop += new DragEventHandler(dataGridView2_DragDrop); dataGridView2.KeyDown += new KeyEventHandler(dataGridView2_KeyDown); dataGridView2.SelectionChanged += new EventHandler(dataGridView2_SelectionChanged); splitContainer1.SplitterMoved += new SplitterEventHandler(splitContainer1_SplitterMoved); this.LocationChanged += new EventHandler(Form1_LocationChanged); this.Shown += new EventHandler(Form1_Shown); this.DoubleBuffered = true; } private void InitBrowser() { if(browser != null) return; browser = new ExtendedWebBrowser2.ExtendedWebBrowser(); browser.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); browser.IsWebBrowserContextMenuEnabled = false; browser.Location = new System.Drawing.Point(0, 0); browser.Margin = new System.Windows.Forms.Padding(0); browser.MinimumSize = new System.Drawing.Size(20, 20); browser.ScriptErrorsSuppressed = true; browser.Size = splitContainer1.Panel2.Bounds.Size; browser.TabIndex = 1; browser.Url = new System.Uri("", System.UriKind.Relative); browser.Visible = false; splitContainer1.Panel2.Controls.Add(browser); } public void OpenStore() { } public void CloseStore() { } public void OpenProvider(string urlString) { providerURLString = urlString; OpenBrowser(urlString, null); } public void OpenBrowser(string urlString, string destination) { if (browser == null) InitBrowser(); if(destination != null) destinationLinkKey = destination; if (browser.Visible == false) { label2.Hide(); button6.Enabled = false; browser.Show(); splitContainer2.Hide(); } if (urlString != null) { if(urlString.Equals(browserURLString)) return; browserURLString = urlString; browser.Url = new Uri(urlString); } else browser.Url = new Uri(browserURLString); } public void CloseBrowser() { if (browser != null && browser.Visible) { label2.Show(); button6.Enabled = true; splitContainer2.Show(); browser.Hide(); } } void dataGridView1_MouseDown(object sender, MouseEventArgs e) { dataGridView1.Focus(); providerKeyCode = 0; if ((e.Button & MouseButtons.Right) == MouseButtons.Right) { DataGridView.HitTestInfo hti = dataGridView1.HitTest(e.X, e.Y); if (hti.RowIndex >= 0 && hti.RowIndex < dataGridView1.Rows.Count) { DataGridViewCell c = dataGridView1.Rows[hti.RowIndex].Cells[0]; if (dataGridView1.CurrentCell.Equals(c) == false) dataGridView1.CurrentCell = c; } return; } // Get the index of the item the mouse is below. rowIndexFromMouseDown1 = dataGridView1.HitTest(e.X, e.Y).RowIndex; if (rowIndexFromMouseDown1 != -1) { // Remember the point where the mouse down occurred. // The DragSize indicates the size that the mouse can move // before a drag event should be started. Size dragSize = SystemInformation.DragSize; // Create a rectangle using the DragSize, with the mouse position being // at the center of the rectangle. dragBoxFromMouseDown1 = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize); } else // Reset the rectangle if the mouse is not over an item in the ListBox. dragBoxFromMouseDown1 = Rectangle.Empty; } void dataGridView1_MouseMove(object sender, MouseEventArgs e) { if ((e.Button & MouseButtons.Left) == MouseButtons.Left) { // If the mouse moves outside the rectangle, start the drag. if (dragBoxFromMouseDown1 != Rectangle.Empty && !dragBoxFromMouseDown1.Contains(e.X, e.Y)) { // Proceed with the drag and drop, passing in the list item. Widget.WidgetsRow row = (Widget.WidgetsRow)widget.Widgets.Rows[rowIndexFromMouseDown1]; DragDropEffects dropEffect = dataGridView1.DoDragDrop(row, DragDropEffects.Copy); } } } void dataGridView2_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.Value.ToString().EndsWith(" ")) { Font f = new Font(e.CellStyle.Font, FontStyle.Bold); e.CellStyle.Font = f; e.CellStyle.ForeColor = Color.FromArgb(59, 69, 82); e.PaintContent(e.ClipBounds); } else { bool selected = ((e.State & DataGridViewElementStates.Selected) != 0 ? true : false); if(selected) { Font f = new Font(e.CellStyle.Font, FontStyle.Bold); e.CellStyle.Font = f; } e.PaintBackground(e.ClipBounds, true); String s = dataGridView2.Rows[e.RowIndex].Cells[3].Value.ToString(); Image i = (Image) Amnesty_Hypercube.Properties.Resources.ResourceManager.GetObject(s); Point p = new Point(e.CellBounds.Location.X + 34, e.CellBounds.Location.Y + 4); try { e.Graphics.DrawImage(i, new Rectangle(p, new Size(16, 16))); } catch { } //if (selected) // e.Graphics.DrawLine(new Pen(Color.FromArgb(69, 128, 199)), new Point(e.CellBounds.X, e.CellBounds.Y), new Point(e.CellBounds.X + e.CellBounds.Width, e.CellBounds.Y)); e.CellStyle.Padding = new Padding(53, 0, 0, 0); e.PaintContent(e.ClipBounds); e.Handled = true; } } void dataGridView2_MouseDown(object sender, MouseEventArgs e) { dataGridView2.Focus(); providerKeyCode = 0; if ((e.Button & MouseButtons.Right) == MouseButtons.Right) { DataGridView.HitTestInfo hti = dataGridView2.HitTest(e.X, e.Y); if (hti.RowIndex >= 0 && hti.RowIndex < dataGridView2.Rows.Count) { DataGridViewCell c = dataGridView2.Rows[hti.RowIndex].Cells[0]; if (c.Value.ToString().EndsWith(" ") == false && dataGridView2.CurrentCell.Equals(c) == false) dataGridView2.CurrentCell = c; Boolean canEdit = (Boolean)dataGridView2.Rows[hti.RowIndex].Cells[4].Value; contextMenuStrip1.Enabled = canEdit; } return; } // Get the index of the item the mouse is below. rowIndexFromMouseDown2 = dataGridView2.HitTest(e.X, e.Y).RowIndex; if (rowIndexFromMouseDown2 != -1 && rowIndexFromMouseDown2 >= dragFloorIndex) { // Remember the point where the mouse down occurred. // The DragSize indicates the size that the mouse can move // before a drag event should be started. Size dragSize = SystemInformation.DragSize; // Create a rectangle using the DragSize, with the mouse position being // at the center of the rectangle. dragBoxFromMouseDown2 = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize); } else // Reset the rectangle if the mouse is not over an item in the ListBox. dragBoxFromMouseDown2 = Rectangle.Empty; } void dataGridView2_MouseMove(object sender, MouseEventArgs e) { if ((e.Button & MouseButtons.Left) == MouseButtons.Left) { // If the mouse moves outside the rectangle, start the drag. if (dragBoxFromMouseDown2 != Rectangle.Empty && !dragBoxFromMouseDown2.Contains(e.X, e.Y)) { // Proceed with the drag and drop, passing in the list item. Provider.ProvidersRow row = (Provider.ProvidersRow)provider.Providers.Rows[rowIndexFromMouseDown2]; DragDropEffects dropEffect = dataGridView2.DoDragDrop(row, DragDropEffects.Move); } } } void dataGridView2_DragDrop(object sender, DragEventArgs e) { // The mouse locations are relative to the screen, so they must be // converted to client coordinates. Point clientPoint = dataGridView2.PointToClient(new Point(e.X, e.Y)); // Get the row index of the item the mouse is below. rowIndexOfItemUnderMouseToDrop2 = dataGridView2.HitTest(clientPoint.X, clientPoint.Y).RowIndex; // If the drag operation was a move then remove and insert the row. if (e.Effect == DragDropEffects.Move) { rowIndexOfItemUnderMouseToDrop2++; Provider.ProvidersRow row = e.Data.GetData(typeof(Provider.ProvidersRow)) as Provider.ProvidersRow; Provider.ProvidersRow copy = CopyProvider(row); InsertNewProvider(copy, rowIndexOfItemUnderMouseToDrop2); provider.Providers.RemoveProvidersRow(row); } } void dataGridView2_DragOver(object sender, DragEventArgs e) { Point clientPoint = dataGridView2.PointToClient(new Point(e.X, e.Y)); int dropIndex = dataGridView2.HitTest(clientPoint.X, clientPoint.Y).RowIndex; e.Effect = DragDropEffects.None; if (e.AllowedEffect == DragDropEffects.Move) { if (dropIndex >= dragFloorIndex - 1 && dropIndex != rowIndexFromMouseDown2 && dropIndex != rowIndexFromMouseDown2 - 1) e.Effect = DragDropEffects.Move; else e.Effect = DragDropEffects.None; } else if (e.AllowedEffect == DragDropEffects.Copy) { if (dataGridView2.CurrentCell.RowIndex == dropIndex) return; Boolean canDrop = (Boolean)dataGridView2.Rows[dropIndex].Cells[6].Value; if(canDrop) e.Effect = DragDropEffects.Copy; } } void dataGridView2_KeyDown(object sender, KeyEventArgs e) { providerKeyCode = e.KeyCode; if (providerKeyCode == Keys.Delete) DeleteSelectedProvider(); } void dataGridView2_SelectionChanged(object sender, EventArgs e) { if (dataGridView2.SelectedCells.Count == 0) { contextMenuStrip2.Items[2].Enabled = false; contextMenuStrip2.Items[4].Enabled = false; contextMenuStrip2.Items[5].Enabled = false; return; } DataGridViewCell c = dataGridView2.SelectedCells[0]; Boolean canEdit = (Boolean)dataGridView2.Rows[c.RowIndex].Cells[4].Value; if (canEdit) { contextMenuStrip2.Items[2].Enabled = true; contextMenuStrip2.Items[4].Enabled = true; contextMenuStrip2.Items[5].Enabled = true; } else { contextMenuStrip2.Items[2].Enabled = false; contextMenuStrip2.Items[4].Enabled = false; contextMenuStrip2.Items[5].Enabled = false; } if (ignoreProviderSelect) return; ignoreProviderSelect = true; if (c.Value.ToString().EndsWith(" ") == false) { currentProvider = c; HandleProviderSelection(c.RowIndex); string key = (string)dataGridView2.Rows[c.RowIndex].Cells[1].Value; SwitchInfo(key); } else { if (providerKeyCode == Keys.Up) { if (c.RowIndex > 1) dataGridView2.CurrentCell = dataGridView2.Rows[c.RowIndex - 1].Cells[0]; else dataGridView2.CurrentCell = dataGridView2.Rows[1].Cells[0]; currentProvider = dataGridView2.CurrentCell; } else if (providerKeyCode == Keys.Down) { if (c.RowIndex + 1 < dataGridView2.Rows.Count) dataGridView2.CurrentCell = dataGridView2.Rows[c.RowIndex + 1].Cells[0]; else dataGridView2.CurrentCell = dataGridView2.Rows[c.RowIndex - 1].Cells[0]; currentProvider = dataGridView2.CurrentCell; } else if (currentProvider != null) dataGridView2.CurrentCell = currentProvider; HandleProviderSelection(dataGridView2.CurrentCell.RowIndex); } providerKeyCode = 0; ignoreProviderSelect = false; } private void AddNewProvider() { Provider.ProvidersRow row = provider.Providers.NewProvidersRow(); row.title = "Untitled"; row.key = ""; row.icon = "IconCube"; row.canEdit = true; row.canSelect = true; row.canDrop = true; row.canLink = false; row.status = 0; row.index = 32767; provider.Providers.AddProvidersRow(row); ReindexProviders(); dataGridView2.CurrentCell = dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[0]; dataGridView2.Focus(); } private Provider.ProvidersRow CopyProvider(Provider.ProvidersRow row) { Provider.ProvidersRow copy = provider.Providers.NewProvidersRow(); copy.title = row.title; copy.key = ""; copy.type = "widgets"; copy.icon = "IconCube"; copy.canEdit = true; copy.canSelect = true; copy.canDrop = true; copy.canLink = false; copy.status = 0; copy.index = 32767; return copy; } private void InsertNewProvider(Provider.ProvidersRow row, int rowIndex) { provider.Providers.Rows.InsertAt(row, rowIndex); ReindexProviders(); } private void ReindexProviders() { for (int i = dragFloorIndex; i < provider.Providers.Rows.Count; i++) { Provider.ProvidersRow row = (Provider.ProvidersRow)provider.Providers.Rows[i]; row.index = 32768 + i; } for (int i = dragFloorIndex; i < provider.Providers.Rows.Count; i++) { Provider.ProvidersRow row = (Provider.ProvidersRow)provider.Providers.Rows[i]; row.index = i; } } private void RenameSelectedProvider() { if (dataGridView2.SelectedCells.Count == 1) { DataGridViewCell c = dataGridView2.SelectedCells[0]; Boolean canEdit = (Boolean)dataGridView2.Rows[c.RowIndex].Cells[4].Value; if (canEdit) { dataGridView2.BeginEdit(true); } } } private void DeleteSelectedProvider() { if (dataGridView2.SelectedCells.Count == 1) { DataGridViewCell c = dataGridView2.SelectedCells[0]; Boolean canEdit = (Boolean)dataGridView2.Rows[c.RowIndex].Cells[4].Value; if (canEdit) { string title = (string)dataGridView2.Rows[c.RowIndex].Cells[0].Value; string msg = String.Format(Amnesty_Hypercube.Properties.Resources.ConfirmDeleteProvider, title); DialogResult dr = MessageBox.Show(msg, Amnesty_Hypercube.Properties.Resources.ConfirmDeleteTitle, MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { int nextRow = c.RowIndex; Provider.ProvidersRow row = (Provider.ProvidersRow) provider.Providers.Rows[c.RowIndex]; provider.Providers.RemoveProvidersRow(row); if (nextRow < dataGridView2.Rows.Count) dataGridView2.CurrentCell = dataGridView2.Rows[nextRow].Cells[0]; else { nextRow--; canEdit = (Boolean)dataGridView2.Rows[nextRow].Cells[4].Value; if(canEdit) dataGridView2.CurrentCell = dataGridView2.Rows[nextRow].Cells[0]; else dataGridView2.CurrentCell = dataGridView2.Rows[1].Cells[0]; } dataGridView2.Focus(); } } else System.Media.SystemSounds.Exclamation.Play(); } } private void HandleProviderSelection(int rowIndex) { Boolean canLink = (Boolean) dataGridView2.Rows[rowIndex].Cells[7].Value; string key = dataGridView2.Rows[rowIndex].Cells[1].Value.ToString(); if (key.Equals("_Store")) OpenStore(); else CloseStore(); if (key.Equals("_Showcase")) OpenBrowser("http://www.amnestywidgets.com/hypercube/winhost/fidget.php", null); else if (key.Equals("_Widgetbox")) OpenBrowser("http://www.widgetbox.com/cgallery/hypercube/home", null); else if (key.Equals("_Store")) { if (providerURLString != null) OpenBrowser(providerURLString, null); else CloseBrowser(); } else if (canLink.Equals(true)) { if (key != null) { string destination = key.Substring(1); string linkURL = String.Format("http://www.amnestywidgets.com/hypercube/deskhost/link_{0}.html", destination); OpenBrowser(linkURL, destination); } else CloseBrowser(); } else CloseBrowser(); } private void SwitchInfo(string key) { if (providerInfoKey != null && providerInfoKey.Equals(key)) return; providerInfoKey = key; // todo: switch info views here //this.widgetsTableAdapter.ClearBeforeFill = true; this.widgetsTableAdapter.Fill(this.widget.Widgets, key); } private void SaveColumnOrder() { IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly(); using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("ColumnOrder", FileMode.Create, isoFile)) { int[] displayIndices = new int[dataGridView1.ColumnCount]; for (int i = 0; i < dataGridView1.ColumnCount; i++) displayIndices[i] = dataGridView1.Columns[i].DisplayIndex; XmlSerializer ser = new XmlSerializer(typeof(int[])); ser.Serialize(isoStream, displayIndices); } } private void SaveColumnWidth() { IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly(); using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("ColumnWidth", FileMode.Create, isoFile)) { int[] displayIndices = new int[dataGridView1.ColumnCount]; for (int i = 0; i < dataGridView1.ColumnCount; i++) displayIndices[i] = dataGridView1.Columns[i].Width; XmlSerializer ser = new XmlSerializer(typeof(int[])); ser.Serialize(isoStream, displayIndices); } } private void RestoreColumnOrder() { IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly(); if (UserStoreExists(isoFile, "ColumnOrder") == false) return; using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("ColumnOrder", FileMode.Open, isoFile)) { try { XmlSerializer ser = new XmlSerializer(typeof(int[])); int[] displayIndicies = (int[])ser.Deserialize(isoStream); for (int i = 0; i < displayIndicies.Length; i++) dataGridView1.Columns[i].DisplayIndex = displayIndicies[i]; } catch { } } } private void RestoreColumnWidth() { IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly(); if (UserStoreExists(isoFile, "ColumnWidth") == false) return; using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("ColumnWidth", FileMode.Open, isoFile)) { try { XmlSerializer ser = new XmlSerializer(typeof(int[])); int[] displayIndicies = (int[])ser.Deserialize(isoStream); for (int i = 0; i < displayIndicies.Length; i++) dataGridView1.Columns[i].Width = displayIndicies[i]; } catch { } } } private bool UserStoreExists(IsolatedStorageFile isoFile, string name) { string[] fileNames = isoFile.GetFileNames("*"); foreach (string fileName in fileNames) { if (fileName.Equals(name)) return true; } return false; } void Form1_LocationChanged(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Normal) { Amnesty_Hypercube.Properties.Settings.Default.MainWindowLocation = this.Location; } } void Form1_Shown(object sender, EventArgs e) { Point mainWindowLocation = Amnesty_Hypercube.Properties.Settings.Default.MainWindowLocation; if (mainWindowLocation.X == 0 && mainWindowLocation.Y == 0) this.CenterToScreen(); } private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'widget.Widgets' table. You can move, or remove it, as needed. this.widgetsBindingSource.Sort = "title ASC"; // TODO: This line of code loads data into the 'provider.Providers' table. You can move, or remove it, as needed. { try { this.provider.Providers.ReadXml("ProviderLibrary.xml"); } catch { this.providersTableAdapter.Fill(this.provider.Providers); } } { providerInfoKey = "_Web"; this.widgetsTableAdapter.Fill(this.widget.Widgets, "_Web"); try { if (this.widget.Widgets.Rows.Count == 0) { bool loadDefaultLibrary = true; if (Amnesty_Hypercube.Properties.Settings.Default.FirstLaunch == true) loadDefaultLibrary = true; else { DialogResult dr = MessageBox.Show(Amnesty_Hypercube.Properties.Resources.LoadDefault, Amnesty_Hypercube.Properties.Resources.LoadDefaultTitle, MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) loadDefaultLibrary = true; } if (loadDefaultLibrary) this.widget.Widgets.ReadXml("HypercubeLibrary.xml"); } } catch { } } dataGridView2.CurrentCell = dataGridView2.Rows[1].Cells[0]; dragFloorIndex = 0; foreach (Provider.ProvidersRow r in provider.Providers.Rows) { if (r.canEdit) { break; } dragFloorIndex++; } ReindexProviders(); } protected override void OnClosing(CancelEventArgs e) { SaveColumnOrder(); SaveColumnWidth(); this.provider.AcceptChanges(); this.provider.WriteXml("ProviderLibrary.xml"); this.widgetsTableAdapter.Update(this.widget.Widgets); //this.widget.AcceptChanges(); //this.widget.WriteXml("HypercubeLibrary.xml"); Amnesty_Hypercube.Properties.Settings.Default.InfoPanelVisible = !splitContainer2.Panel2Collapsed; Amnesty_Hypercube.Properties.Settings.Default.SourcePanelWidth = splitContainer1.SplitterDistance; Amnesty_Hypercube.Properties.Settings.Default.MainWindowMaximized = (this.WindowState == FormWindowState.Maximized ? true : false); Amnesty_Hypercube.Properties.Settings.Default.MainWindowMinimized = (this.WindowState == FormWindowState.Minimized ? true : false); if (this.WindowState == FormWindowState.Normal) { Amnesty_Hypercube.Properties.Settings.Default.MainWindowWidth = this.Size.Width; Amnesty_Hypercube.Properties.Settings.Default.MainWindowHeight = this.Size.Height; } Amnesty_Hypercube.Properties.Settings.Default.FirstLaunch = false; Amnesty_Hypercube.Properties.Settings.Default.Save(); base.OnClosing(e); } void dataGridView2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { saveProviderTitle = dataGridView2[e.ColumnIndex, e.RowIndex].Value.ToString(); } void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) { string trim = dataGridView2[e.ColumnIndex, e.RowIndex].Value.ToString().Trim(); dataGridView2[e.ColumnIndex, e.RowIndex].Value = trim; if (dataGridView2[e.ColumnIndex, e.RowIndex].Value.ToString().Length == 0) dataGridView2[e.ColumnIndex, e.RowIndex].Value = saveProviderTitle; } private void button6_Click(object sender, EventArgs e) { splitContainer2.Panel2Collapsed = !splitContainer2.Panel2Collapsed; } void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e) { if (splitContainer1.SplitterDistance > 400) splitContainer1.SplitterDistance = 400; } void button10_MouseDown(object sender, MouseEventArgs e) { tracking = true; track = this.mouse.X; trackDistance = splitContainer1.SplitterDistance; } void button10_MouseUp(object sender, MouseEventArgs e) { tracking = false; } void button10_MouseMove(object sender, MouseEventArgs e) { if (tracking) { int newDistance = trackDistance - (track - this.mouse.X); if (newDistance < splitContainer1.Panel1MinSize) newDistance = splitContainer1.Panel1MinSize; if (newDistance > 400) newDistance = 400; if (splitContainer1.SplitterDistance != newDistance) splitContainer1.SplitterDistance = newDistance; } } void contextMenuStrip2_Opening(object sender, CancelEventArgs e) { button9.BackgroundImage = Amnesty_Hypercube.Properties.Resources.Action_Pressed; } void contextMenuStrip2_Closing(object sender, ToolStripDropDownClosingEventArgs e) { button9.BackgroundImage = Amnesty_Hypercube.Properties.Resources.Action; } void button8_MouseDown(object sender, MouseEventArgs e) { button8.BackgroundImage = Amnesty_Hypercube.Properties.Resources.Add_Pressed; } void button8_MouseUp(object sender, MouseEventArgs e) { button8.BackgroundImage = Amnesty_Hypercube.Properties.Resources.Add; } void button9_MouseDown(object sender, MouseEventArgs e) { button9.BackgroundImage = Amnesty_Hypercube.Properties.Resources.Action_Pressed; } void button9_MouseUp(object sender, MouseEventArgs e) { if (contextMenuStrip2.Visible == false) button9.BackgroundImage = Amnesty_Hypercube.Properties.Resources.Action; } void button9_MouseClick(object sender, MouseEventArgs e) { contextMenuStrip2.Show(button9, e.Location); } private void button8_Click(object sender, EventArgs e) { AddNewProvider(); } void global_MouseActivity(object sender, MouseEventArgs e) { mouse = e.Location; } private void deleteToolStripMenuItem1_Click(object sender, EventArgs e) { DeleteSelectedProvider(); } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { DeleteSelectedProvider(); } private void newCollectionToolStripMenuItem1_Click(object sender, EventArgs e) { AddNewProvider(); } private void renameToolStripMenuItem2_Click(object sender, EventArgs e) { RenameSelectedProvider(); } private void renameToolStripMenuItem_Click(object sender, EventArgs e) { RenameSelectedProvider(); } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } } }
// Copyright (c) 2017-2018 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using SIL.PlatformUtilities; using SIL.Reporting; namespace SIL.IO { /// <summary> /// Desktop-specific utility methods for processing directories, e.g. methods that report to the user. /// </summary> public static class DirectoryUtilities { /// <summary> /// Makes a full copy of the specified directory in the system's temporary directory. /// If the copy fails at any point in the process, the user is notified of the /// problem and an attempt is made to remove the destination directory if the failure /// happened part way through the process. /// </summary> /// <param name="srcDirectory">Directory to copy</param> /// <returns>Null if the copy was unsuccessful, otherwise the path to the copied directory</returns> public static string CopyDirectoryToTempDirectory(string srcDirectory) { string dstDirectory; return (CopyDirectory(srcDirectory, Path.GetTempPath(), out dstDirectory) ? dstDirectory : null); } /// <summary> /// Makes a copy of the specifed source directory and its contents in the specified /// destination directory. The copy has the same directory name as the source, but ends up /// as a sub directory of the specified destination directory. The destination directory must /// already exist. If the copy fails at any point in the process, the user is notified /// of the problem and an attempt is made to remove the destination directory if the /// failure happened part way through the process. /// </summary> /// <param name="srcDirectory">Directory being copied</param> /// <param name="dstDirectoryParent">Destination directory where source directory and its contents are copied</param> /// <returns>true if successful, otherwise, false.</returns> public static bool CopyDirectory(string srcDirectory, string dstDirectoryParent) { string dstDirectory; return CopyDirectory(srcDirectory, dstDirectoryParent, out dstDirectory); } private static bool CopyDirectory(string srcDirectory, string dstDirectoryParent, out string dstDirectory) { dstDirectory = Path.Combine(dstDirectoryParent, Path.GetFileName(srcDirectory)); if (!Directory.Exists(dstDirectoryParent)) { ErrorReport.NotifyUserOfProblem(new DirectoryNotFoundException(dstDirectoryParent + " not found."), "{0} was unable to copy the directory {1} to {2}", EntryAssembly.ProductName, srcDirectory, dstDirectoryParent); return false; } if (DirectoryHelper.AreEquivalent(srcDirectory, dstDirectory)) { ErrorReport.NotifyUserOfProblem(new Exception("Cannot copy directory to itself."), "{0} was unable to copy the directory {1} to {2}", EntryAssembly.ProductName, srcDirectory, dstDirectoryParent); return false; } return CopyDirectoryContents(srcDirectory, dstDirectory); } /// <summary> /// Copies the specified source directory's contents to the specified destination directory. /// If the destination directory does not exist, it will be created first. If the source /// directory contains sub directories, those and their content will also be copied. If the /// copy fails at any point in the process, the user is notified of the problem and /// an attempt is made to remove the destination directory if the failure happened part /// way through the process. /// </summary> /// <param name="sourcePath">Directory whose contents will be copied</param> /// <param name="destinationPath">Destination directory receiving the content of the source directory</param> /// <returns>true if successful, otherwise, false.</returns> public static bool CopyDirectoryContents(string sourcePath, string destinationPath) { try { DirectoryHelper.Copy(sourcePath,destinationPath); } catch (Exception e) { //Review: generally, it's better if SIL.Core doesn't undertake to make these kind of UI decisions. //I've extracted CopyDirectoryWithException, so as not to mess up whatever client is using this version ReportFailedCopyAndCleanUp(e, sourcePath, destinationPath); return false; } return true; } private static void ReportFailedCopyAndCleanUp(Exception error, string srcDirectory, string dstDirectory) { ErrorReport.NotifyUserOfProblem(error, "{0} was unable to copy the directory {1} to {2}", EntryAssembly.ProductName, srcDirectory, dstDirectory); try { if (!Directory.Exists(dstDirectory)) return; // Clean up by removing the partially copied directory. Directory.Delete(dstDirectory, true); } catch { } } /// <summary> /// Sets the permissions for this directory so that everyone has full control /// </summary> /// <param name="fullDirectoryPath"></param> /// <param name="showErrorMessage"></param> /// <returns>True if able to set access, False otherwise</returns> public static bool SetFullControl(string fullDirectoryPath, bool showErrorMessage = true) { if (!Platform.IsWindows) return false; // get current settings var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var security = Directory.GetAccessControl(fullDirectoryPath, AccessControlSections.Access); var currentRules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); // if everyone already has full control, return now if (currentRules.Cast<FileSystemAccessRule>() .Where(rule => rule.IdentityReference.Value == everyone.Value) .Any(rule => rule.FileSystemRights == FileSystemRights.FullControl)) { return true; } // initialize var returnVal = false; try { // set the permissions so everyone can read and write to this directory var fullControl = new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); security.AddAccessRule(fullControl); Directory.SetAccessControl(fullDirectoryPath, security); returnVal = true; } catch (Exception ex) { if (showErrorMessage) { ErrorReport.NotifyUserOfProblem(ex, "{0} was not able to set directory security for '{1}' to 'full control' for everyone.", EntryAssembly.ProductName, fullDirectoryPath); } } return returnVal; } [Obsolete("Use DirectoryHelper.Copy()")] public static void CopyDirectoryWithException(string sourcePath, string destinationPath, bool overwrite = false) { DirectoryHelper.Copy(sourcePath, destinationPath, overwrite); } [Obsolete("Use DirectoryHelper.AreEquivalent()")] public static bool AreDirectoriesEquivalent(string dir1, string dir2) { return DirectoryHelper.AreEquivalent(dir1, dir2); } [Obsolete("Use DirectoryHelper.AreEquivalent()")] public static bool AreDirectoriesEquivalent(DirectoryInfo dirInfo1, DirectoryInfo dirInfo2) { return DirectoryHelper.AreEquivalent(dirInfo1, dirInfo2); } /// <summary> /// Move <paramref name="sourcePath"/> to <paramref name="destinationPath"/>. If src /// and dest are on different partitions (e.g., temp and documents are on different /// drives) then this method will do a copy followed by a delete. This is in contrast /// to Directory.Move which fails if src and dest are on different partitions. /// </summary> /// <param name="sourcePath">The source directory or file, similar to Directory.Move</param> /// <param name="destinationPath">The destination directory or file. If <paramref name="sourcePath"/> /// is a file then <paramref name="destinationPath"/> also needs to be a file.</param> [Obsolete("Use DirectoryHelper.Move()")] public static void MoveDirectorySafely(string sourcePath, string destinationPath) { DirectoryHelper.Move(sourcePath, destinationPath); } /// <summary> /// Return subdirectories of <paramref name="path"/> that are not system or hidden. /// There are some cases where our call to Directory.GetDirectories() throws. /// For example, when the access permissions on a folder are set so that it can't be read. /// Another possible example may be Windows Backup files, which apparently look like directories. /// </summary> /// <param name="path">Directory path to look in.</param> /// <returns>Zero or more directory names that are not system or hidden.</returns> /// <exception cref="System.UnauthorizedAccessException">E.g. when the user does not have /// read permission.</exception> [Obsolete("Use DirectoryHelper.GetSafeDirectories()")] public static string[] GetSafeDirectories(string path) { return DirectoryHelper.GetSafeDirectories(path); } /// <summary> /// There are various things which can prevent a simple directory deletion, mostly timing related things which are hard to debug. /// This method uses all the tricks to do its best. /// </summary> /// <returns>returns true if the directory is fully deleted</returns> [Obsolete("Use RobustIO.DeleteDirectoryAndContents()")] public static bool DeleteDirectoryRobust(string path, bool overrideReadOnly = true) { return RobustIO.DeleteDirectoryAndContents(path, overrideReadOnly); } /// <summary> /// If necessary, append a number to make the folder path unique. /// </summary> /// <param name="folderPath">Source folder pathname.</param> /// <returns>A unique folder pathname at the same level as <paramref name="folderPath"/>. It may have a number apended to <paramref name="folderPath"/>, or it may be <paramref name="folderPath"/>.</returns> [Obsolete("Use PathHelper.GetUniqueFolderPath()")] public static string GetUniqueFolderPath(string folderPath) { return PathHelper.GetUniqueFolderPath(folderPath); } /// <summary> /// Checks if there are any entries in a directory /// </summary> /// <param name="path">Path to the directory to check</param> /// <param name="onlyCheckForFiles">if this is TRUE, a directory that contains subdirectories but no files will be considered empty. /// Subdirectories are not checked, so if onlyCheckForFiles is TRUE and there is a subdirectory that contains a file, the directory /// will still be considered empty.</param> /// <returns></returns> [Obsolete("Use DirectoryHelper.IsEmpty()")] public static bool DirectoryIsEmpty(string path, bool onlyCheckForFiles = false) { return DirectoryHelper.IsEmpty(path, onlyCheckForFiles); } public static bool IsDirectoryWritable(string folderPath) { /* * Using DirectoryInfo.Exists instead of Directory.Exists() because * Directory.Exists() ignores all IO and Security exceptions. */ var parent = new DirectoryInfo(folderPath); if (!parent.Exists) return false; // get a random name for a temporary directory in folderPath var tempPath = Path.Combine(folderPath, Path.GetRandomFileName()); // if the random directory already exists, pick another while (Directory.Exists(tempPath)) tempPath = Path.Combine(folderPath, Path.GetRandomFileName()); try { Directory.CreateDirectory(tempPath); if (!Directory.Exists(tempPath)) return false; Directory.Delete(tempPath, true); return true; } catch(IOException) { return false; } catch(UnauthorizedAccessException) { return false; } } } }
// 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { /// <summary> /// Base class for all delegate invocation thunks. /// </summary> public abstract partial class DelegateThunk : ILStubMethod { private DelegateInfo _delegateInfo; public DelegateThunk(DelegateInfo delegateInfo) { _delegateInfo = delegateInfo; } public sealed override TypeSystemContext Context { get { return _delegateInfo.Type.Context; } } public sealed override TypeDesc OwningType { get { return _delegateInfo.Type; } } public sealed override MethodSignature Signature { get { return _delegateInfo.Signature; } } public sealed override Instantiation Instantiation { get { return Instantiation.Empty; } } protected TypeDesc SystemDelegateType { get { return Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; } } protected FieldDesc ExtraFunctionPointerOrDataField { get { return SystemDelegateType.GetKnownField("m_extraFunctionPointerOrData"); } } protected FieldDesc HelperObjectField { get { return SystemDelegateType.GetKnownField("m_helperObject"); } } protected FieldDesc FirstParameterField { get { return SystemDelegateType.GetKnownField("m_firstParameter"); } } protected FieldDesc FunctionPointerField { get { return SystemDelegateType.GetKnownField("m_functionPointer"); } } } /// <summary> /// Invoke thunk for open delegates to static methods. Loads all arguments except /// the 'this' pointer and performs an indirect call to the delegate target. /// This method is injected into delegate types. /// </summary> public sealed partial class DelegateInvokeOpenStaticThunk : DelegateThunk { internal DelegateInvokeOpenStaticThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { // Target has the same signature as the Invoke method, except it's static. MethodSignatureBuilder builder = new MethodSignatureBuilder(Signature); builder.Flags = Signature.Flags | MethodSignatureFlags.Static; var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load all arguments except 'this' for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } // Indirectly call the delegate target static method. codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(builder.ToSignature())); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeOpenStaticThunk"; } } } /// <summary> /// Invoke thunk for open delegates to instance methods. This kind of thunk /// uses the first parameter as `this` that gets passed to the target instance method. /// The thunk also performs virtual resolution if necessary. /// This kind of delegates is typically created with Delegate.CreateDelegate /// and MethodInfo.CreateDelegate at runtime. /// </summary> public sealed partial class DelegateInvokeOpenInstanceThunk : DelegateThunk { internal DelegateInvokeOpenInstanceThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { Debug.Assert(Signature.Length > 0); var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load all arguments except delegate's 'this' TypeDesc boxThisType = null; TypeDesc[] parameters = new TypeDesc[Signature.Length - 1]; for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); if (i == 0) { // Ensure that we're working with an object type by boxing it here. // This is to allow delegates which are generic over thier first parameter // to have valid code in their thunk. if (Signature[i].IsSignatureVariable) { boxThisType = Signature[i]; codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); } } else { parameters[i - 1] = Signature[i]; } } // Call a helper to get the actual method target codeStream.EmitLdArg(0); if (Signature[0].IsByRef) { codeStream.Emit(ILOpcode.ldnull); } else { codeStream.EmitLdArg(1); if (boxThisType != null) { codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); } } codeStream.Emit(ILOpcode.call, emitter.NewToken(SystemDelegateType.GetKnownMethod("GetActualTargetFunctionPointer", null))); MethodSignature targetSignature = new MethodSignature(0, 0, Signature.ReturnType, parameters); codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetSignature)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeOpenInstanceThunk"; } } } /// <summary> /// Invoke thunk for closed delegates to static methods. The target /// is a static method, but the first argument is captured by the delegate. /// The signature of the target has an extra object-typed argument, followed /// by the arguments that are delegate-compatible with the thunk signature. /// This method is injected into delegate types. /// </summary> public sealed partial class DelegateInvokeClosedStaticThunk : DelegateThunk { internal DelegateInvokeClosedStaticThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { TypeDesc[] targetMethodParameters = new TypeDesc[Signature.Length + 1]; targetMethodParameters[0] = Context.GetWellKnownType(WellKnownType.Object); for (int i = 0; i < Signature.Length; i++) { targetMethodParameters[i + 1] = Signature[i]; } var targetMethodSignature = new MethodSignature( Signature.Flags | MethodSignatureFlags.Static, 0, Signature.ReturnType, targetMethodParameters); var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load the stored 'this' codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); // Load all arguments except 'this' for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } // Indirectly call the delegate target static method. codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSignature)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeClosedStaticThunk"; } } } /// <summary> /// Multicast invoke thunk for delegates that are a result of Delegate.Combine. /// Passes it's arguments to each of the delegates that got combined and calls them /// one by one. Returns the value of the last delegate executed. /// This method is injected into delegate types. /// </summary> public sealed partial class DelegateInvokeMulticastThunk : DelegateThunk { internal DelegateInvokeMulticastThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); ArrayType invocationListArrayType = SystemDelegateType.MakeArrayType(); ILLocalVariable delegateArrayLocal = emitter.NewLocal(invocationListArrayType); ILLocalVariable invocationCountLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable iteratorLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable delegateToCallLocal = emitter.NewLocal(SystemDelegateType); ILLocalVariable returnValueLocal = 0; if (!Signature.ReturnType.IsVoid) { returnValueLocal = emitter.NewLocal(Signature.ReturnType); } // Fill in delegateArrayLocal // Delegate[] delegateArrayLocal = (Delegate[])this.m_helperObject // ldarg.0 (this pointer) // ldfld Delegate.HelperObjectField // castclass Delegate[] // stloc delegateArrayLocal codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); codeStream.Emit(ILOpcode.castclass, emitter.NewToken(invocationListArrayType)); codeStream.EmitStLoc(delegateArrayLocal); // Fill in invocationCountLocal // int invocationCountLocal = this.m_extraFunctionPointerOrData // ldarg.0 (this pointer) // ldfld Delegate.m_extraFunctionPointerOrData // stloc invocationCountLocal codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.EmitStLoc(invocationCountLocal); // Fill in iteratorLocal // int iteratorLocal = 0; // ldc.0 // stloc iteratorLocal codeStream.EmitLdc(0); codeStream.EmitStLoc(iteratorLocal); // Loop across every element of the array. ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel(); codeStream.EmitLabel(startOfLoopLabel); // Implement as do/while loop. We only have this stub in play if we're in the multicast situation // Find the delegate to call // Delegate = delegateToCallLocal = delegateArrayLocal[iteratorLocal]; // ldloc delegateArrayLocal // ldloc iteratorLocal // ldelem System.Delegate // stloc delegateToCallLocal codeStream.EmitLdLoc(delegateArrayLocal); codeStream.EmitLdLoc(iteratorLocal); codeStream.Emit(ILOpcode.ldelem, emitter.NewToken(SystemDelegateType)); codeStream.EmitStLoc(delegateToCallLocal); // Call the delegate // returnValueLocal = delegateToCallLocal(...); // ldloc delegateToCallLocal // ldfld System.Delegate.m_firstParameter // ldarg 1, n // ldloc delegateToCallLocal // ldfld System.Delegate.m_functionPointer // calli returnValueType thiscall (all the params) // IF there is a return value // stloc returnValueLocal codeStream.EmitLdLoc(delegateToCallLocal); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FirstParameterField)); for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } codeStream.EmitLdLoc(delegateToCallLocal); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FunctionPointerField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature)); if (returnValueLocal != 0) codeStream.EmitStLoc(returnValueLocal); // Increment iteratorLocal // ++iteratorLocal; // ldloc iteratorLocal // ldc.i4.1 // add // stloc iteratorLocal codeStream.EmitLdLoc(iteratorLocal); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(iteratorLocal); // Check to see if the loop is done codeStream.EmitLdLoc(invocationCountLocal); codeStream.EmitLdLoc(iteratorLocal); codeStream.Emit(ILOpcode.bne_un, startOfLoopLabel); // Return to caller. If the delegate has a return value, be certain to return that. // return returnValueLocal; // ldloc returnValueLocal // ret if (returnValueLocal != 0) codeStream.EmitLdLoc(returnValueLocal); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeMulticastThunk"; } } } /// <summary> /// Invoke thunk for delegates that point to closed instance generic methods. /// These need a thunk because the function pointer to invoke might be a fat function /// pointer and we need a calli to unwrap it, inject the hidden argument, shuffle the /// rest of the arguments, and call the unwrapped function pointer. /// </summary> public sealed partial class DelegateInvokeInstanceClosedOverGenericMethodThunk : DelegateThunk { internal DelegateInvokeInstanceClosedOverGenericMethodThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load the stored 'this' codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); // Load all arguments except 'this' for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } // Indirectly call the delegate target codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeInstanceClosedOverGenericMethodThunk"; } } } public sealed partial class DelegateReversePInvokeThunk : DelegateThunk { internal DelegateReversePInvokeThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); MetadataType throwHelpersType = Context.SystemModule.GetKnownType("Internal.Runtime.CompilerHelpers", "ThrowHelpers"); MethodDesc throwHelper = throwHelpersType.GetKnownMethod("ThrowNotSupportedException", null); codeStream.EmitCallThrowHelper(emitter, throwHelper); return emitter.Link(this); } public override string Name { get { return "InvokeReversePInvokeThunk"; } } } /// <summary> /// Reverse invocation stub which goes from the strongly typed parameters the delegate /// accepts, converts them into an object array, and invokes a delegate with the /// object array, and then casts and returns the result back. /// This is used to support delegates pointing to the LINQ expression interpreter. /// </summary> public sealed partial class DelegateInvokeObjectArrayThunk : DelegateThunk { internal DelegateInvokeObjectArrayThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { // We will generate the following code: // // object ret; // object[] args = new object[parameterCount]; // args[0] = param0; // args[1] = param1; // ... // try { // ret = ((Func<object[], object>)dlg.m_helperObject)(args); // } finally { // param0 = (T0)args[0]; // only generated for each byref argument // } // return (TRet)ret; ILEmitter emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object); TypeDesc objectArrayType = objectType.MakeArrayType(); ILLocalVariable argsLocal = emitter.NewLocal(objectArrayType); bool hasReturnValue = !Signature.ReturnType.IsVoid; bool hasRefArgs = false; if (Signature.Length > 0) { codeStream.EmitLdc(Signature.Length); codeStream.Emit(ILOpcode.newarr, emitter.NewToken(objectType)); codeStream.EmitStLoc(argsLocal); for (int i = 0; i < Signature.Length; i++) { TypeDesc paramType = Signature[i]; bool paramIsByRef = false; if (paramType.IsByRef) { hasRefArgs |= paramType.IsByRef; paramIsByRef = true; paramType = ((ByRefType)paramType).ParameterType; } hasRefArgs |= paramType.IsByRef; codeStream.EmitLdLoc(argsLocal); codeStream.EmitLdc(i); codeStream.EmitLdArg(i + 1); ILToken paramToken = emitter.NewToken(paramType); if (paramIsByRef) { codeStream.Emit(ILOpcode.ldobj, paramToken); } codeStream.Emit(ILOpcode.box, paramToken); codeStream.Emit(ILOpcode.stelem_ref); } } else { MethodDesc emptyObjectArrayMethod = Context.GetHelperEntryPoint("DelegateHelpers", "GetEmptyObjectArray"); codeStream.Emit(ILOpcode.call, emitter.NewToken(emptyObjectArrayMethod)); codeStream.EmitStLoc(argsLocal); } if (hasRefArgs) { // we emit a try/finally to update the args array even if an exception is thrown // ilgen.BeginTryBody(); } codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); MetadataType funcType = Context.SystemModule.GetKnownType("System", "Func`2"); TypeDesc instantiatedFunc = funcType.MakeInstantiatedType(objectArrayType, objectType); codeStream.Emit(ILOpcode.castclass, emitter.NewToken(instantiatedFunc)); codeStream.EmitLdLoc(argsLocal); MethodDesc invokeMethod = instantiatedFunc.GetKnownMethod("Invoke", null); codeStream.Emit(ILOpcode.callvirt, emitter.NewToken(invokeMethod)); ILLocalVariable retLocal = (ILLocalVariable)(-1); if (hasReturnValue) { retLocal = emitter.NewLocal(objectType); codeStream.EmitStLoc(retLocal); } else { codeStream.Emit(ILOpcode.pop); } if (hasRefArgs) { // ILGeneratorLabel returnLabel = new ILGeneratorLabel(); // ilgen.Emit(OperationCode.Leave, returnLabel); // copy back ref/out args //ilgen.BeginFinallyBlock(); for (int i = 0; i < Signature.Length; i++) { TypeDesc paramType = Signature[i]; if (paramType.IsByRef) { paramType = ((ByRefType)paramType).ParameterType; ILToken paramToken = emitter.NewToken(paramType); // Update parameter codeStream.EmitLdArg(i + 1); codeStream.EmitLdLoc(argsLocal); codeStream.EmitLdc(i); codeStream.Emit(ILOpcode.ldelem_ref); codeStream.Emit(ILOpcode.unbox_any, paramToken); codeStream.Emit(ILOpcode.stobj, paramToken); } } // ilgen.Emit(OperationCode.Endfinally); // ilgen.EndTryBody(); // ilgen.MarkLabel(returnLabel); } if (hasReturnValue) { codeStream.EmitLdLoc(retLocal); codeStream.Emit(ILOpcode.unbox_any, emitter.NewToken(Signature.ReturnType)); } codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeObjectArrayThunk"; } } } /// <summary> /// Synthetic method override of "IntPtr Delegate.GetThunk(Int32)". This method is injected /// into all delegate types and provides means for System.Delegate to access the various thunks /// generated by the compiler. /// </summary> public sealed partial class DelegateGetThunkMethodOverride : ILStubMethod { private DelegateInfo _delegateInfo; private MethodSignature _signature; internal DelegateGetThunkMethodOverride(DelegateInfo delegateInfo) { _delegateInfo = delegateInfo; } public override TypeSystemContext Context { get { return _delegateInfo.Type.Context; } } public override TypeDesc OwningType { get { return _delegateInfo.Type; } } public override MethodSignature Signature { get { if (_signature == null) { TypeSystemContext context = _delegateInfo.Type.Context; TypeDesc intPtrType = context.GetWellKnownType(WellKnownType.IntPtr); TypeDesc int32Type = context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, intPtrType, new[] { int32Type }); } return _signature; } } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); var codeStream = emitter.NewCodeStream(); ILCodeLabel returnNullLabel = emitter.NewCodeLabel(); ILCodeLabel[] labels = new ILCodeLabel[(int)DelegateThunkCollection.MaxThunkKind]; for (DelegateThunkKind i = 0; i < DelegateThunkCollection.MaxThunkKind; i++) { MethodDesc thunk = _delegateInfo.Thunks[i]; if (thunk != null) labels[(int)i] = emitter.NewCodeLabel(); else labels[(int)i] = returnNullLabel; } codeStream.EmitLdArg(1); codeStream.EmitSwitch(labels); codeStream.Emit(ILOpcode.br, returnNullLabel); for (DelegateThunkKind i = 0; i < DelegateThunkCollection.MaxThunkKind; i++) { MethodDesc thunk = _delegateInfo.Thunks[i]; if (thunk != null) { codeStream.EmitLabel(labels[(int)i]); if (i == DelegateThunkKind.DelegateInvokeThunk) { // Dynamic invoke thunk is special since we're calling into a shared helper MethodDesc targetMethod; if (thunk.HasInstantiation) { TypeDesc[] inst = DynamicInvokeMethodThunk.GetThunkInstantiationForMethod(_delegateInfo.Type.InstantiateAsOpen().GetMethod("Invoke", null)); targetMethod = Context.GetInstantiatedMethod(thunk, new Instantiation(inst)); } else { targetMethod = thunk; } codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(targetMethod)); } else { codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(thunk.InstantiateAsOpen())); } codeStream.Emit(ILOpcode.ret); } } codeStream.EmitLabel(returnNullLabel); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_i); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override Instantiation Instantiation { get { return Instantiation.Empty; } } public override bool IsVirtual { get { return true; } } public override string Name { get { return "GetThunk"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Internal.TypeSystem; using Internal.TypeSystem.Interop; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { /// <summary> /// Provides method bodies for PInvoke methods /// /// This by no means intends to provide full PInvoke support. The intended use of this is to /// a) prevent calls getting generated to targets that require a full marshaller /// (this compiler doesn't provide that), and b) offer a hand in some very simple marshalling /// situations (but support for this part might go away as the product matures). /// </summary> public struct PInvokeILEmitter { private readonly PInvokeMethodData _methodData; private readonly Marshaller[] _marshallers; private PInvokeILEmitter(MethodDesc targetMethod, PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration) { Debug.Assert(targetMethod.IsPInvoke || targetMethod is DelegateMarshallingMethodThunk); _methodData = new PInvokeMethodData(targetMethod, pinvokeILEmitterConfiguration); _marshallers = InitializeMarshallers(_methodData); } private static Marshaller[] InitializeMarshallers(PInvokeMethodData pInvokeMethodData) { MethodDesc targetMethod = pInvokeMethodData.TargetMethod; bool isDelegate = targetMethod is DelegateMarshallingMethodThunk; MethodSignature methodSig = isDelegate ? ((DelegateMarshallingMethodThunk)targetMethod).DelegateSignature : targetMethod.Signature; ParameterMetadata[] parameterMetadataArray = targetMethod.GetParameterMetadata(); Marshaller[] marshallers = new Marshaller[methodSig.Length + 1]; int parameterIndex = 0; ParameterMetadata parameterMetadata = new ParameterMetadata(); for (int i = 0; i < marshallers.Length; i++) { Debug.Assert(parameterIndex == parameterMetadataArray.Length || i <= parameterMetadataArray[parameterIndex].Index); if (parameterIndex == parameterMetadataArray.Length || i < parameterMetadataArray[parameterIndex].Index) { // if we don't have metadata for the parameter, create a dummy one parameterMetadata = new ParameterMetadata(i, ParameterMetadataAttributes.None, null); } else if (i == parameterMetadataArray[parameterIndex].Index) { parameterMetadata = parameterMetadataArray[parameterIndex++]; } TypeDesc parameterType = (i == 0) ? methodSig.ReturnType : methodSig[i - 1]; //first item is the return type marshallers[i] = Marshaller.CreateMarshaller(parameterType, pInvokeMethodData, parameterMetadata, marshallers, isDelegate ? MarshalDirection.Reverse : MarshalDirection.Forward); } return marshallers; } private MethodIL EmitIL() { PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams(); ILEmitter emitter = pInvokeILCodeStreams.Emitter; ILCodeStream fnptrLoadStream = pInvokeILCodeStreams.FunctionPointerLoadStream; ILCodeStream callsiteSetupCodeStream = pInvokeILCodeStreams.CallsiteSetupCodeStream; ILCodeStream unmarshallingCodestream = pInvokeILCodeStreams.UnmarshallingCodestream; // Marshal the arguments for (int i = 0; i < _marshallers.Length; i++) { _marshallers[i].EmitMarshallingIL(pInvokeILCodeStreams); } // make the call TypeDesc nativeReturnType = _marshallers[0].NativeParameterType; TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1]; for (int i = 1; i < _marshallers.Length; i++) { nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType; } MethodDesc targetMethod = _methodData.TargetMethod; PInvokeMetadata importMetadata = _methodData.ImportMetadata; PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration = _methodData.PInvokeILEmitterConfiguration; MethodSignature nativeSig; // if the SetLastError flag is set in DllImport, clear the error code before doing P/Invoke if ((importMetadata.Attributes & PInvokeAttributes.SetLastError) == PInvokeAttributes.SetLastError) { callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken( _methodData.PInvokeMarshal.GetKnownMethod("ClearLastWin32Error", null))); } if (targetMethod is DelegateMarshallingMethodThunk) { nativeSig = new MethodSignature(MethodSignatureFlags.Static, 0, nativeReturnType, nativeParameterTypes); TypeDesc[] parameters = new TypeDesc[_marshallers.Length - 1]; for (int i = 1; i < _marshallers.Length; i++) { parameters[i - 1] = _marshallers[i].ManagedParameterType; } MethodSignature managedSignature = new MethodSignature(MethodSignatureFlags.Static, 0, _marshallers[0].ManagedParameterType, parameters); fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(targetMethod.Context.GetHelperType("InteropHelpers").GetKnownMethod("GetDelegateFunctionPointer", null))); ILLocalVariable vDelegateStub = emitter.NewLocal(targetMethod.Context.GetWellKnownType(WellKnownType.IntPtr)); fnptrLoadStream.EmitStLoc(vDelegateStub); callsiteSetupCodeStream.EmitLdLoc(vDelegateStub); callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(managedSignature)); } else if (MarshalHelpers.UseLazyResolution(targetMethod, importMetadata.Module, pinvokeILEmitterConfiguration)) { MetadataType lazyHelperType = targetMethod.Context.GetHelperType("InteropHelpers"); FieldDesc lazyDispatchCell = new PInvokeLazyFixupField((DefType)targetMethod.OwningType, importMetadata); fnptrLoadStream.Emit(ILOpcode.ldsflda, emitter.NewToken(lazyDispatchCell)); fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(lazyHelperType.GetKnownMethod("ResolvePInvoke", null))); MethodSignatureFlags unmanagedCallConv = PInvokeMetadata.GetUnmanagedCallingConvention(importMetadata.Attributes); nativeSig = new MethodSignature( targetMethod.Signature.Flags | unmanagedCallConv, 0, nativeReturnType, nativeParameterTypes); ILLocalVariable vNativeFunctionPointer = emitter.NewLocal(targetMethod.Context.GetWellKnownType(WellKnownType.IntPtr)); fnptrLoadStream.EmitStLoc(vNativeFunctionPointer); callsiteSetupCodeStream.EmitLdLoc(vNativeFunctionPointer); callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig)); } else { // Eager call PInvokeMetadata nativeImportMetadata = new PInvokeMetadata(importMetadata.Module, importMetadata.Name ?? targetMethod.Name, importMetadata.Attributes); nativeSig = new MethodSignature( targetMethod.Signature.Flags, 0, nativeReturnType, nativeParameterTypes); MethodDesc nativeMethod = new PInvokeTargetNativeMethod(targetMethod.OwningType, nativeSig, nativeImportMetadata, pinvokeILEmitterConfiguration.GetNextNativeMethodId()); callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(nativeMethod)); } // if the SetLastError flag is set in DllImport, call the PInvokeMarshal.SaveLastWin32Error so that last error can be used later // by calling PInvokeMarshal.GetLastWin32Error if ((importMetadata.Attributes & PInvokeAttributes.SetLastError) == PInvokeAttributes.SetLastError) { callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken( _methodData.PInvokeMarshal.GetKnownMethod("SaveLastWin32Error", null))); } unmarshallingCodestream.Emit(ILOpcode.ret); return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(targetMethod), IsStubRequired(), nativeSig); } //TODO: https://github.com/dotnet/corert/issues/2675 // This exception messages need to localized // TODO: Log as warning public static MethodIL EmitExceptionBody(string message, MethodDesc method) { ILEmitter emitter = new ILEmitter(); TypeSystemContext context = method.Context; MethodSignature ctorSignature = new MethodSignature(0, 0, context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { context.GetWellKnownType(WellKnownType.String) }); MethodDesc exceptionCtor = method.Context.GetWellKnownType(WellKnownType.Exception).GetKnownMethod(".ctor", ctorSignature); ILCodeStream codeStream = emitter.NewCodeStream(); codeStream.Emit(ILOpcode.ldstr, emitter.NewToken(message)); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(exceptionCtor)); codeStream.Emit(ILOpcode.throw_); codeStream.Emit(ILOpcode.ret); return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(method), true, null); } public static MethodIL EmitIL(MethodDesc method, PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration) { try { return new PInvokeILEmitter(method, pinvokeILEmitterConfiguration).EmitIL(); } catch (NotSupportedException) { string message = "Method '" + method.ToString() + "' requires non-trivial marshalling that is not yet supported by this compiler."; return EmitExceptionBody(message, method); } catch (InvalidProgramException ex) { Debug.Assert(!String.IsNullOrEmpty(ex.Message)); return EmitExceptionBody(ex.Message, method); } } private bool IsStubRequired() { MethodDesc method = _methodData.TargetMethod; Debug.Assert(method.IsPInvoke || method is DelegateMarshallingMethodThunk); if (method is DelegateMarshallingMethodThunk) { return true; } if (MarshalHelpers.UseLazyResolution(method, _methodData.ImportMetadata.Module, _methodData.PInvokeILEmitterConfiguration)) { return true; } if ((_methodData.ImportMetadata.Attributes & PInvokeAttributes.SetLastError) == PInvokeAttributes.SetLastError) { return true; } for (int i = 0; i < _marshallers.Length; i++) { if (_marshallers[i].IsMarshallingRequired()) return true; } return false; } } internal sealed class PInvokeILCodeStreams { public ILEmitter Emitter { get; } public ILCodeStream FunctionPointerLoadStream { get; } public ILCodeStream MarshallingCodeStream { get; } public ILCodeStream CallsiteSetupCodeStream { get; } public ILCodeStream ReturnValueMarshallingCodeStream { get; } public ILCodeStream UnmarshallingCodestream { get; } public PInvokeILCodeStreams() { Emitter = new ILEmitter(); // We have 4 code streams: // - _marshallingCodeStream is used to convert each argument into a native type and // store that into the local // - callsiteSetupCodeStream is used to used to load each previously generated local // and call the actual target native method. // - _returnValueMarshallingCodeStream is used to convert the native return value // to managed one. // - _unmarshallingCodestream is used to propagate [out] native arguments values to // managed ones. FunctionPointerLoadStream = Emitter.NewCodeStream(); MarshallingCodeStream = Emitter.NewCodeStream(); CallsiteSetupCodeStream = Emitter.NewCodeStream(); ReturnValueMarshallingCodeStream = Emitter.NewCodeStream(); UnmarshallingCodestream = Emitter.NewCodeStream(); } } /// <summary> /// Synthetic method that represents the actual PInvoke target method. /// All parameters are simple types. There will be no code /// generated for this method. Instead, a static reference to a symbol will be emitted. /// </summary> internal sealed class PInvokeTargetNativeMethod : MethodDesc { private TypeDesc _owningType; private MethodSignature _signature; private PInvokeMetadata _methodMetadata; private int _sequenceNumber; public PInvokeTargetNativeMethod(TypeDesc owningType, MethodSignature signature, PInvokeMetadata methodMetadata, int sequenceNumber) { _owningType = owningType; _signature = signature; _methodMetadata = methodMetadata; _sequenceNumber = sequenceNumber; } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc OwningType { get { return _owningType; } } public override MethodSignature Signature { get { return _signature; } } public override string Name { get { return "__pInvokeImpl" + _methodMetadata.Name + _sequenceNumber; } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } public override bool IsPInvoke { get { return true; } } public override PInvokeMetadata GetPInvokeMethodMetadata() { return _methodMetadata; } public override string ToString() { return "[EXTERNAL]" + Name; } } /// <summary> /// Synthetic RVA static field that represents PInvoke fixup cell. The RVA data is /// backed by a small data structure generated on the fly from the <see cref="PInvokeMetadata"/> /// carried by the instance of this class. /// </summary> internal sealed class PInvokeLazyFixupField : FieldDesc { private DefType _owningType; private PInvokeMetadata _pInvokeMetadata; public PInvokeLazyFixupField(DefType owningType, PInvokeMetadata pInvokeMetadata) { _owningType = owningType; _pInvokeMetadata = pInvokeMetadata; } public PInvokeMetadata PInvokeMetadata { get { return _pInvokeMetadata; } } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc FieldType { get { return Context.GetHelperType("InteropHelpers").GetNestedType("MethodFixupCell"); } } public override bool HasRva { get { return true; } } public override bool IsInitOnly { get { return false; } } public override bool IsLiteral { get { return false; } } public override bool IsStatic { get { return true; } } public override bool IsThreadStatic { get { return false; } } public override DefType OwningType { get { return _owningType; } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } } internal sealed class PInvokeILStubMethodIL : ILStubMethodIL { public bool IsStubRequired { get; } public MethodSignature NativeCallableSignature { get; } public PInvokeILStubMethodIL(ILStubMethodIL methodIL, bool isStubRequired, MethodSignature signature) : base(methodIL) { IsStubRequired = isStubRequired; NativeCallableSignature = signature; } } }
#nullable disable //#define HTML_XPATH_TRACE using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.XPath; namespace Meziantou.Framework.Html; public sealed class HtmlNodeNavigator : XPathNavigator { private readonly NameTable _nameTable = new(); private HtmlNode _currentNode; private readonly HtmlNode _rootNode; [Conditional("HTML_XPATH_TRACE")] private static void Trace(object value, [CallerMemberName] string methodName = null) { #if HTML_XPATH_TRACE if (!EnableTrace) return; #endif Debug.WriteLine(methodName + ":" + value); } #if HTML_XPATH_TRACE internal static bool EnableTrace { get; set; } #endif public HtmlNodeNavigator(HtmlDocument document, HtmlNode currentNode!!, HtmlNodeNavigatorOptions options) { Document = document; CurrentNode = currentNode; BaseNode = currentNode; Options = options; if ((options & HtmlNodeNavigatorOptions.RootNode) == HtmlNodeNavigatorOptions.RootNode) { _rootNode = CurrentNode; } } private HtmlNodeNavigator(HtmlNodeNavigator other!!) { CurrentNode = other.CurrentNode; BaseNode = other.BaseNode; Document = other.Document; Options = other.Options; _rootNode = other._rootNode; } public override object UnderlyingObject => CurrentNode; public HtmlNode CurrentNode { get => _currentNode; set { if (_currentNode != value) { Trace("old: " + _currentNode + " new: " + value); _currentNode = value; } } } public HtmlNodeNavigatorOptions Options { get; } public HtmlDocument Document { get; } public HtmlNode BaseNode { get; } private string GetOrAdd(string array) { return _nameTable.Get(array) ?? _nameTable.Add(array); } public override string BaseURI => GetOrAdd(string.Empty); public override XPathNavigator Clone() => new HtmlNodeNavigator(this); public override string OuterXml { get { if (CurrentNode == null) return null; return CurrentNode.OuterXml; } set => base.OuterXml = value; } public override bool IsEmptyElement { get { var element = CurrentNode as HtmlElement; Trace("=" + (element?.IsEmpty == true)); return element?.IsEmpty == true; } } public override bool IsSamePosition(XPathNavigator other) { if (other is not HtmlNodeNavigator nav) return false; if (Document != null) return Document == nav.Document && CurrentNode == nav.CurrentNode; return BaseNode == nav.BaseNode && CurrentNode == nav.CurrentNode; } public override bool MoveTo(XPathNavigator other) { var nav = other as HtmlNodeNavigator; Trace("nav:" + nav); if (nav == null || (Document != null && nav.Document != Document) || (BaseNode != nav.BaseNode)) return false; CurrentNode = nav.CurrentNode; return true; } public override bool MoveToFirstAttribute() { var element = CurrentNode as HtmlElement; Trace("element:" + element); if (element == null) return false; Trace("element.HasAttributes:" + element.HasAttributes); if (!element.HasAttributes) return false; CurrentNode = element.Attributes[0]; return true; } public override bool MoveToFirstChild() { Trace("ChildNodes.HasChildNodes:" + CurrentNode.HasChildNodes); if (!CurrentNode.HasChildNodes) return false; CurrentNode = CurrentNode.ChildNodes[0]; return true; } private static HtmlAttribute MoveToFirstNamespaceLocal(HtmlAttributeList attributes) { if (attributes == null) return null; foreach (var att in attributes) { if (att.IsNamespace) return att; } return null; } private static HtmlAttribute MoveToFirstNamespaceGlobal(HtmlNode rootNode, ref HtmlAttributeList attributes) { var att = MoveToFirstNamespaceLocal(attributes); if (att != null) return att; if (rootNode != null && attributes != null && attributes.Parent == rootNode) return null; var element = attributes != null ? attributes.Parent.ParentNode as HtmlElement : null; while (element != null) { if (rootNode != null && element.Equals(rootNode)) return null; if (element.HasAttributes) { attributes = element.Attributes; att = MoveToFirstNamespaceLocal(attributes); } if (att != null) return att; element = element.ParentNode as HtmlElement; } return null; } public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { if (CurrentNode is not HtmlElement element) return false; HtmlAttribute att = null; HtmlAttributeList attributes = null; switch (namespaceScope) { case XPathNamespaceScope.Local: if (element.HasAttributes) { att = MoveToFirstNamespaceLocal(element.Attributes); } if (att == null) return false; CurrentNode = att; break; case XPathNamespaceScope.ExcludeXml: if (element.HasAttributes) { attributes = element.Attributes; att = MoveToFirstNamespaceGlobal(_rootNode, ref attributes); } if (att == null) return false; while (string.Equals(att.LocalName, HtmlNode.XmlPrefix, StringComparison.Ordinal)) { att = MoveToNextNamespaceGlobal(_rootNode, ref attributes, att); if (att == null) return false; } CurrentNode = att; break; case XPathNamespaceScope.All: default: if (element.HasAttributes) { attributes = element.Attributes; att = MoveToFirstNamespaceGlobal(_rootNode, ref attributes); } if (att == null) { if (Document == null) return false; CurrentNode = Document.NamespaceXml; } else { CurrentNode = att; } break; } return true; } private static HtmlAttribute MoveToNextNamespaceLocal(HtmlAttribute att) { att = att.NextSibling; while (att != null) { if (att.IsNamespace) return att; att = att.NextSibling; } return null; } private static HtmlAttribute MoveToNextNamespaceGlobal(HtmlNode rootNode, ref HtmlAttributeList attributes, HtmlAttribute att) { var next = MoveToNextNamespaceLocal(att); if (next != null) return next; if (rootNode != null && attributes != null && attributes.Parent == rootNode) return null; var element = attributes != null ? attributes.Parent.ParentNode as HtmlElement : null; while (element != null) { if (rootNode != null && element.Equals(rootNode)) return null; if (element.HasAttributes) { attributes = element.Attributes; next = MoveToFirstNamespaceLocal(attributes); if (next != null) return next; } element = element.ParentNode as HtmlElement; } return null; } public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { if (CurrentNode is not HtmlAttribute attribute || !attribute.IsNamespace) return false; HtmlAttribute att; var attributes = attribute.ParentNode.HasAttributes ? attribute.ParentNode.Attributes : null; switch (namespaceScope) { case XPathNamespaceScope.Local: att = MoveToNextNamespaceLocal(attribute); if (att == null) return false; CurrentNode = att; break; case XPathNamespaceScope.ExcludeXml: att = attribute; do { att = MoveToNextNamespaceGlobal(_rootNode, ref attributes, att); if (att == null) return false; } while (string.Equals(att.LocalName, HtmlNode.XmlPrefix, StringComparison.Ordinal)); CurrentNode = att; break; case XPathNamespaceScope.All: default: att = attribute; do { att = MoveToNextNamespaceGlobal(_rootNode, ref attributes, att); if (att == null) { if (Document == null) return false; CurrentNode = Document.NamespaceXml; return true; } } while (string.Equals(att.LocalName, HtmlNode.XmlPrefix, StringComparison.Ordinal)); CurrentNode = att; break; } return true; } public override bool MoveToNext() { var node = CurrentNode.NextSibling; Trace("node:" + node); if (node == null) return false; CurrentNode = node; return true; } public override bool MoveToNextAttribute() { var att = CurrentNode as HtmlAttribute; Trace("att:" + att); if (att == null) return false; HtmlNode node = att.NextSibling; Trace("next att:" + node); if (node == null) return false; CurrentNode = node; return true; } public override bool MoveToParent() { Trace("ParentNode:" + CurrentNode.ParentNode); if (CurrentNode.ParentNode == null) return false; if (_rootNode != null && CurrentNode.ParentNode == _rootNode) { Trace("ParentNode reached root"); return false; } CurrentNode = CurrentNode.ParentNode; return true; } public override bool MoveToPrevious() { var node = CurrentNode.PreviousSibling; Trace("PreviousSibling:" + node); if (node == null) return false; CurrentNode = node; return true; } public override void MoveToRoot() { Trace(value: null); CurrentNode = Document ?? BaseNode; } public override bool MoveToId(string id) { throw new NotSupportedException(); } [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "By design")] public override string LocalName { get { var name = CurrentNode.LocalName; Trace("=" + name); if (name != null) { if ((Options & HtmlNodeNavigatorOptions.UppercasedNames) == HtmlNodeNavigatorOptions.UppercasedNames) return name.ToUpperInvariant(); if ((Options & HtmlNodeNavigatorOptions.LowercasedNames) == HtmlNodeNavigatorOptions.LowercasedNames) return name.ToLowerInvariant(); } return name ?? string.Empty; } } [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "By design")] public override string Name { get { var name = CurrentNode.Name; Trace("=" + name); if (name != null) { if ((Options & HtmlNodeNavigatorOptions.UppercasedNames) == HtmlNodeNavigatorOptions.UppercasedNames) return name.ToUpperInvariant(); if ((Options & HtmlNodeNavigatorOptions.LowercasedNames) == HtmlNodeNavigatorOptions.LowercasedNames) return name.ToLowerInvariant(); } return name ?? string.Empty; } } public override XmlNameTable NameTable => _nameTable; [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "By design")] public override string NamespaceURI { get { var ns = CurrentNode.NamespaceURI; if (Document?.Options.EmptyNamespacesForXPath.Contains(ns) == true) return string.Empty; Debug.Assert(ns != null); if ((Options & HtmlNodeNavigatorOptions.UppercasedNamespaceURIs) == HtmlNodeNavigatorOptions.UppercasedNamespaceURIs) return ns.ToUpperInvariant(); if ((Options & HtmlNodeNavigatorOptions.LowercasedNamespaceURIs) == HtmlNodeNavigatorOptions.LowercasedNamespaceURIs) return ns.ToLowerInvariant(); Trace("=" + ns); return ns; } } public override XPathNodeType NodeType { get { var nt = CurrentNode.NodeType switch { HtmlNodeType.Attribute => XPathNodeType.Attribute, HtmlNodeType.Comment => XPathNodeType.Comment, HtmlNodeType.Document => XPathNodeType.Root, HtmlNodeType.DocumentType or HtmlNodeType.Element => XPathNodeType.Element, HtmlNodeType.ProcessingInstruction => XPathNodeType.ProcessingInstruction, _ => XPathNodeType.Text, }; Trace("=" + nt); return nt; } } [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "By design")] public override string Prefix { get { Debug.Assert(CurrentNode.Prefix != null); var prefix = CurrentNode.Prefix; Trace("=" + prefix); if ((Options & HtmlNodeNavigatorOptions.UppercasedPrefixes) == HtmlNodeNavigatorOptions.UppercasedPrefixes) return prefix.ToUpperInvariant(); if ((Options & HtmlNodeNavigatorOptions.LowercasedPrefixes) == HtmlNodeNavigatorOptions.LowercasedPrefixes) return prefix.ToLowerInvariant(); return prefix ?? string.Empty; } } [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "By design")] public override string Value { get { Trace("=" + CurrentNode.Value); if (CurrentNode is HtmlElement element) { if ((Options & HtmlNodeNavigatorOptions.UppercasedValues) == HtmlNodeNavigatorOptions.UppercasedValues) return element.InnerText.ToUpperInvariant(); if ((Options & HtmlNodeNavigatorOptions.LowercasedValues) == HtmlNodeNavigatorOptions.LowercasedValues) return element.InnerText.ToLowerInvariant(); return element.InnerText; } var value = CurrentNode.Value; if (value != null) { if ((Options & HtmlNodeNavigatorOptions.UppercasedValues) == HtmlNodeNavigatorOptions.UppercasedValues) return value.ToUpperInvariant(); if ((Options & HtmlNodeNavigatorOptions.LowercasedValues) == HtmlNodeNavigatorOptions.LowercasedValues) return value.ToLowerInvariant(); } return value; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Xml; using System.IO; public class DialogueScript : MonoBehaviour { public TextAsset dialogue; private XmlNode texttoshow; public Text dialogs; public Image characterpic; public Sprite[] chara1; public Sprite[] chara2; public Sprite chara3; public Sprite chara4; public Sprite chara5; public Sprite[] chara6; public Image textbox; private string charaname; private RaycastHit hit; private RaycastHit hit2; private bool textcomplete = false; private bool istalking = false; public AudioSource beepsound; public AudioClip beep; public static string NPCname; public static bool cantalk; private Vector3 center; private Vector3 side1; private Vector3 side2; public MovementController _mScript; public static int _seqNum; //private bool faceme = false; public Text showname; public Animator charanim; public Animator serikAnim; public virtual void Start() { textbox.enabled = false; dialogs.enabled = false; characterpic.enabled = false; showname.enabled = false; _mScript = GameObject.FindGameObjectWithTag("Player").GetComponent<MovementController>(); charanim = GameObject.Find("Character").GetComponent<Animator>(); serikAnim = GameObject.FindGameObjectWithTag("SerikGhost").GetComponent<Animator>(); } public virtual void Update() { center = transform.position + new Vector3(0, 0.5f, 0); side1 = center + new Vector3(0.2f, 0, 0); side2 = center + new Vector3(-0.2f, 0, 0); Debug.DrawRay(center, transform.forward * 5); Debug.DrawRay(side1, transform.forward * 5); Debug.DrawRay(side2, transform.forward * 5); if (Physics.Raycast(center, transform.forward, out hit, 1) && !istalking || Physics.Raycast(side1, transform.forward, out hit, 1) && !istalking || Physics.Raycast(side2, transform.forward, out hit, 1) && !istalking) { if (Input.GetButtonDown("Action") && hit.collider.tag == "talking") { NPCname = hit.collider.name; string textData = dialogue.text; ParseDialogue(textData); } } else if (Input.GetButtonDown("Action") && textcomplete && istalking) { textcomplete = false; if(texttoshow.NextSibling != null) { //beepsound.PlayOneShot(beep); string tempstr = Nextnode(texttoshow); StartCoroutine(Printletters(tempstr)); Debug.Log(_seqNum + "if"); _seqNum++; } else { CheckNames(); //faceme = false; textbox.enabled = false; dialogs.enabled = false; characterpic.enabled = false; showname.enabled = false; istalking = false; _mScript.bForcedMove = false; _seqNum = 0; Debug.Log(_seqNum + "else"); charanim.SetBool("isTalking", false); charanim.SetBool("bVictory", false); } } else if (Input.GetButtonDown("Action") && !textcomplete && istalking) { textcomplete = true; } } public void ParseDialogue(string xmlData) { _mScript.bForcedMove = true; textbox.enabled = true; dialogs.enabled = true; characterpic.enabled = true; showname.enabled = true; istalking = true; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(new StringReader(xmlData)); string xmlPathPattern = "//Dialogue"; XmlNodeList myNodeList = xmlDoc.SelectNodes(xmlPathPattern); foreach (XmlNode node in myNodeList) { string tempstr = FirstDialogue(node); StartCoroutine(Printletters(tempstr)); } } private string FirstDialogue(XmlNode node) { XmlNode thenode = node[NPCname]; XmlNode newtext = thenode.FirstChild; Checkchara(newtext); texttoshow = newtext; return newtext.InnerXml; } private string Nextnode(XmlNode node) { XmlNode newtextnext = node.NextSibling; Checkchara(newtextnext); texttoshow = newtextnext; return newtextnext.InnerXml; } private void Checkchara(XmlNode node) { string character = node.Attributes["character"].Value; int expression = 0; if(node.Attributes["expression"] != null) { int.TryParse(node.Attributes["expression"].Value, out expression); } switch(character) { case "Gulnaz": characterpic.sprite = chara1[expression]; showname.text = character; charanim.SetBool("isTalking", true); Invoke("StopAnim", 0.2f); break; case "Serik": characterpic.sprite = chara2[expression]; showname.text = character; break; case "Temir": characterpic.sprite = chara4; showname.text = character; break; case "Ruslan": characterpic.sprite = chara3; showname.text = character; break; case "Inzhu": characterpic.sprite = chara5; showname.text = character; break; case "GhostSerik": characterpic.sprite = chara6[expression]; showname.text = "Serik"; serikAnim.SetBool("bSerikTalk", true); Invoke("StopAnim", 0.2f); break; default: characterpic.sprite = null; break; } } IEnumerator Printletters(string sentence) { string str = ""; for (int i = 0; i < sentence.Length; i++) { str += sentence[i]; if (i == sentence.Length - 1) { print("truuuuuueeeee"); textcomplete = true; } if(textcomplete == true) { str = sentence; i = sentence.Length; } dialogs.text = str; yield return new WaitForSeconds(0.04f); } } public virtual void CheckNames() { Debug.Log("checking and changing names"); } void StopAnim() { charanim.SetBool("isTalking", false); charanim.SetBool("bVictory", false); serikAnim.SetBool("bSerikTalk", false); } }
using System; using System.Collections.Generic; using System.Linq; namespace UnityEngine.TestTools.Logging { internal class LogScope : IDisposable { private bool m_Disposed; private readonly object _lock = new object(); public Queue<LogMatch> ExpectedLogs { get; set; } public List<LogEvent> AllLogs { get; } public List<LogEvent> FailingLogs { get; } public bool IgnoreFailingMessages { get; set; } public bool IsNUnitException { get; private set; } public bool IsNUnitSuccessException { get; private set; } public bool IsNUnitInconclusiveException { get; private set; } public bool IsNUnitIgnoreException { get; private set; } public string NUnitExceptionMessage { get; private set; } private bool m_NeedToProcessLogs; private static List<LogScope> s_ActiveScopes = new List<LogScope>(); internal static LogScope Current { get { if (s_ActiveScopes.Count == 0) throw new InvalidOperationException("No log scope is available"); return s_ActiveScopes[0]; } } internal static bool HasCurrentLogScope() { return s_ActiveScopes.Count > 0; } public LogScope() { AllLogs = new List<LogEvent>(); FailingLogs = new List<LogEvent>(); ExpectedLogs = new Queue<LogMatch>(); IgnoreFailingMessages = false; Activate(); } private void Activate() { s_ActiveScopes.Insert(0, this); RegisterScope(this); Application.logMessageReceivedThreaded -= AddLog; Application.logMessageReceivedThreaded += AddLog; } private void Deactivate() { Application.logMessageReceivedThreaded -= AddLog; s_ActiveScopes.Remove(this); UnregisterScope(this); } private static void RegisterScope(LogScope logScope) { Application.logMessageReceivedThreaded += logScope.AddLog; } private static void UnregisterScope(LogScope logScope) { Application.logMessageReceivedThreaded -= logScope.AddLog; } public void AddLog(string message, string stacktrace, LogType type) { lock (_lock) { m_NeedToProcessLogs = true; var log = new LogEvent { LogType = type, Message = message, StackTrace = stacktrace, }; AllLogs.Add(log); if (IsNUnitResultStateException(stacktrace, type)) { if (message.StartsWith("SuccessException")) { IsNUnitException = true; IsNUnitSuccessException = true; if (message.StartsWith("SuccessException: ")) { NUnitExceptionMessage = message.Substring("SuccessException: ".Length); return; } } else if (message.StartsWith("InconclusiveException")) { IsNUnitException = true; IsNUnitInconclusiveException = true; if (message.StartsWith("InconclusiveException: ")) { NUnitExceptionMessage = message.Substring("InconclusiveException: ".Length); return; } } else if (message.StartsWith("IgnoreException")) { IsNUnitException = true; IsNUnitIgnoreException = true; if (message.StartsWith("IgnoreException: ")) { NUnitExceptionMessage = message.Substring("IgnoreException: ".Length); return; } } } if (IsFailingLog(type) && !IgnoreFailingMessages) { FailingLogs.Add(log); } } } public bool IsAllLogsHandled() { lock (_lock) { return AllLogs.All(x => x.IsHandled); } } public LogEvent GetUnhandledLog() { lock (_lock) { return AllLogs.First(x => !x.IsHandled); } } private static bool IsNUnitResultStateException(string stacktrace, LogType logType) { if (logType != LogType.Exception) return false; return string.IsNullOrEmpty(stacktrace) || stacktrace.StartsWith("NUnit.Framework.Assert."); } private static bool IsFailingLog(LogType type) { switch (type) { case LogType.Assert: case LogType.Error: case LogType.Exception: return true; default: return false; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (m_Disposed) { return; } m_Disposed = true; if (disposing) { Deactivate(); } } internal bool AnyFailingLogs() { ProcessExpectedLogs(); return FailingLogs.Any(); } internal void ProcessExpectedLogs() { lock (_lock) { if (!m_NeedToProcessLogs || !ExpectedLogs.Any()) return; LogMatch expectedLog = null; foreach (var logEvent in AllLogs) { if (!ExpectedLogs.Any()) break; if (expectedLog == null && ExpectedLogs.Any()) expectedLog = ExpectedLogs.Peek(); if (expectedLog != null && expectedLog.Matches(logEvent)) { ExpectedLogs.Dequeue(); logEvent.IsHandled = true; if (FailingLogs.Any(expectedLog.Matches)) { var failingLog = FailingLogs.First(expectedLog.Matches); FailingLogs.Remove(failingLog); } expectedLog = null; } } m_NeedToProcessLogs = false; } } } }
#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 System.Diagnostics; using Ctrip.Log4.Util; namespace Ctrip.Log4.Core { /// <summary> /// The internal representation of caller location information. /// </summary> /// <remarks> /// <para> /// This class uses the <c>System.Diagnostics.StackTrace</c> class to generate /// a call stack. The caller's information is then extracted from this stack. /// </para> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class is not supported on the /// .NET Compact Framework 1.0 therefore caller location information is not /// available on that framework. /// </para> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds: /// </para> /// <para> /// "StackTrace information will be most informative with Debug build configurations. /// By default, Debug builds include debug symbols, while Release builds do not. The /// debug symbols contain most of the file, method name, line number, and column /// information used in constructing StackFrame and StackTrace objects. StackTrace /// might not report as many method calls as expected, due to code transformations /// that occur during optimization." /// </para> /// <para> /// This means that in a Release build the caller information may be incomplete or may /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if !NETCF [Serializable] #endif public class LocationInfo { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is /// the stack boundary into the logging system for this call.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LocationInfo" /> /// class based on the current thread. /// </para> /// </remarks> public LocationInfo(Type callerStackBoundaryDeclaringType) { // Initialize all fields m_className = NA; m_fileName = NA; m_lineNumber = NA; m_methodName = NA; m_fullInfo = NA; #if !NETCF if (callerStackBoundaryDeclaringType != null) { try { StackTrace st = new StackTrace(true); int frameIndex = 0; // skip frames not from fqnOfCallingClass while (frameIndex < st.FrameCount) { StackFrame frame = st.GetFrame(frameIndex); if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType) { break; } frameIndex++; } // skip frames from fqnOfCallingClass while (frameIndex < st.FrameCount) { StackFrame frame = st.GetFrame(frameIndex); if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType) { break; } frameIndex++; } if (frameIndex < st.FrameCount) { // take into account the frames we skip above int adjustedFrameCount = st.FrameCount - frameIndex; ArrayList stackFramesList = new ArrayList(adjustedFrameCount); m_stackFrames = new StackFrame[adjustedFrameCount]; for (int i=frameIndex; i < st.FrameCount; i++) { stackFramesList.Add(st.GetFrame(i)); } stackFramesList.CopyTo(m_stackFrames, 0); // now frameIndex is the first 'user' caller frame StackFrame locationFrame = st.GetFrame(frameIndex); if (locationFrame != null) { System.Reflection.MethodBase method = locationFrame.GetMethod(); if (method != null) { m_methodName = method.Name; if (method.DeclaringType != null) { m_className = method.DeclaringType.FullName; } } m_fileName = locationFrame.GetFileName(); m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); // Combine all location info m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')'; } } } catch(System.Security.SecurityException) { // This security exception will occur if the caller does not have // some undefined set of SecurityPermission flags. LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available."); } } #endif } /// <summary> /// Constructor /// </summary> /// <param name="className">The fully qualified class name.</param> /// <param name="methodName">The method name.</param> /// <param name="fileName">The file name.</param> /// <param name="lineNumber">The line number of the method within the file.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LocationInfo" /> /// class with the specified data. /// </para> /// </remarks> public LocationInfo(string className, string methodName, string fileName, string lineNumber) { m_className = className; m_fileName = fileName; m_lineNumber = lineNumber; m_methodName = methodName; m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')'; } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets the fully qualified class name of the caller making the logging /// request. /// </summary> /// <value> /// The fully qualified class name of the caller making the logging /// request. /// </value> /// <remarks> /// <para> /// Gets the fully qualified class name of the caller making the logging /// request. /// </para> /// </remarks> public string ClassName { get { return m_className; } } /// <summary> /// Gets the file name of the caller. /// </summary> /// <value> /// The file name of the caller. /// </value> /// <remarks> /// <para> /// Gets the file name of the caller. /// </para> /// </remarks> public string FileName { get { return m_fileName; } } /// <summary> /// Gets the line number of the caller. /// </summary> /// <value> /// The line number of the caller. /// </value> /// <remarks> /// <para> /// Gets the line number of the caller. /// </para> /// </remarks> public string LineNumber { get { return m_lineNumber; } } /// <summary> /// Gets the method name of the caller. /// </summary> /// <value> /// The method name of the caller. /// </value> /// <remarks> /// <para> /// Gets the method name of the caller. /// </para> /// </remarks> public string MethodName { get { return m_methodName; } } /// <summary> /// Gets all available caller information /// </summary> /// <value> /// All available caller information, in the format /// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c> /// </value> /// <remarks> /// <para> /// Gets all available caller information, in the format /// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c> /// </para> /// </remarks> public string FullInfo { get { return m_fullInfo; } } #if !NETCF /// <summary> /// Gets the stack frames from the stack trace of the caller making the log request /// </summary> public StackFrame[] StackFrames { get { return m_stackFrames; } } #endif #endregion Public Instance Properties #region Private Instance Fields private readonly string m_className; private readonly string m_fileName; private readonly string m_lineNumber; private readonly string m_methodName; private readonly string m_fullInfo; #if !NETCF private readonly StackFrame[] m_stackFrames; #endif #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the LocationInfo class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LocationInfo); /// <summary> /// When location information is not available the constant /// <c>NA</c> is returned. Current value of this string /// constant is <b>?</b>. /// </summary> private const string NA = "?"; #endregion Private Static Fields } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // OrderPreservingPipeliningMergeHelper.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace System.Linq.Parallel { /// <summary> /// A merge helper that yields results in a streaming fashion, while still ensuring correct output /// ordering. This merge only works if each producer task generates outputs in the correct order, /// i.e. with an Increasing (or Correct) order index. /// /// The merge creates DOP producer tasks, each of which will be writing results into a separate /// buffer. /// /// The consumer always waits until each producer buffer contains at least one element. If we don't /// have one element from each producer, we cannot yield the next element. (If the order index is /// Correct, or in some special cases with the Increasing order, we could yield sooner. The /// current algorithm does not take advantage of this.) /// /// The consumer maintains a producer heap, and uses it to decide which producer should yield the next output /// result. After yielding an element from a particular producer, the consumer will take another element /// from the same producer. However, if the producer buffer exceeded a particular threshold, the consumer /// will take the entire buffer, and give the producer an empty buffer to fill. /// /// Finally, if the producer notices that its buffer has exceeded an even greater threshold, it will /// go to sleep and wait until the consumer takes the entire buffer. /// </summary> internal class OrderPreservingPipeliningMergeHelper<TOutput, TKey> : IMergeHelper<TOutput> { private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks. private readonly PartitionedStream<TOutput, TKey> _partitions; // Source partitions. private readonly TaskScheduler _taskScheduler; // The task manager to execute the query. /// <summary> /// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer. /// If false, the producer will make each result available to the consumer immediately after it is /// produced. /// </summary> private readonly bool _autoBuffered; /// <summary> /// Buffers for the results. Each buffer has elements added by one producer, and removed /// by the consumer. /// </summary> private readonly Queue<Pair<TKey, TOutput>>[] _buffers; /// <summary> /// Whether each producer is done producing. Set to true by individual producers, read by consumer. /// </summary> private readonly bool[] _producerDone; /// <summary> /// Whether a particular producer is waiting on the consumer. Read by the consumer, set to true /// by producers, set to false by the consumer. /// </summary> private readonly bool[] _producerWaiting; /// <summary> /// Whether the consumer is waiting on a particular producer. Read by producers, set to true /// by consumer, set to false by producer. /// </summary> private readonly bool[] _consumerWaiting; /// <summary> /// Each object is a lock protecting the corresponding elements in _buffers, _producerDone, /// _producerWaiting and _consumerWaiting. /// </summary> private readonly object[] _bufferLocks; /// <summary> /// A comparer used by the producer heap. /// </summary> private readonly IComparer<Producer<TKey>> _producerComparer; /// <summary> /// The initial capacity of the buffer queue. The value was chosen experimentally. /// </summary> internal const int INITIAL_BUFFER_SIZE = 128; /// <summary> /// If the consumer notices that the queue reached this limit, it will take the entire buffer from /// the producer, instead of just popping off one result. The value was chosen experimentally. /// </summary> internal const int STEAL_BUFFER_SIZE = 1024; /// <summary> /// If the producer notices that the queue reached this limit, it will go to sleep until woken up /// by the consumer. Chosen experimentally. /// </summary> internal const int MAX_BUFFER_SIZE = 8192; //----------------------------------------------------------------------------------- // Instantiates a new merge helper. // // Arguments: // partitions - the source partitions from which to consume data. // ignoreOutput - whether we're enumerating "for effect" or for output. // internal OrderPreservingPipeliningMergeHelper( PartitionedStream<TOutput, TKey> partitions, TaskScheduler taskScheduler, CancellationState cancellationState, bool autoBuffered, int queryId, IComparer<TKey> keyComparer) { Debug.Assert(partitions != null); TraceHelpers.TraceInfo("KeyOrderPreservingMergeHelper::.ctor(..): creating an order preserving merge helper"); _taskGroupState = new QueryTaskGroupState(cancellationState, queryId); _partitions = partitions; _taskScheduler = taskScheduler; _autoBuffered = autoBuffered; int partitionCount = _partitions.PartitionCount; _buffers = new Queue<Pair<TKey, TOutput>>[partitionCount]; _producerDone = new bool[partitionCount]; _consumerWaiting = new bool[partitionCount]; _producerWaiting = new bool[partitionCount]; _bufferLocks = new object[partitionCount]; if (keyComparer == Util.GetDefaultComparer<int>()) { Debug.Assert(typeof(TKey) == typeof(int)); _producerComparer = (IComparer<Producer<TKey>>)new ProducerComparerInt(); } else { _producerComparer = new ProducerComparer(keyComparer); } } //----------------------------------------------------------------------------------- // Schedules execution of the merge itself. // void IMergeHelper<TOutput>.Execute() { OrderPreservingPipeliningSpoolingTask<TOutput, TKey>.Spool( _taskGroupState, _partitions, _consumerWaiting, _producerWaiting, _producerDone, _buffers, _bufferLocks, _taskScheduler, _autoBuffered); } //----------------------------------------------------------------------------------- // Gets the enumerator from which to enumerate output results. // IEnumerator<TOutput> IMergeHelper<TOutput>.GetEnumerator() { return new OrderedPipeliningMergeEnumerator(this, _producerComparer); } //----------------------------------------------------------------------------------- // Returns the results as an array. // [ExcludeFromCodeCoverage] public TOutput[] GetResultsAsArray() { Debug.Fail("An ordered pipelining merge is not intended to be used this way."); throw new InvalidOperationException(); } /// <summary> /// A comparer used by FixedMaxHeap(Of Producer) /// /// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to /// end up in the root of the heap. /// /// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return - /// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0 /// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return + /// </summary> private class ProducerComparer : IComparer<Producer<TKey>> { private readonly IComparer<TKey> _keyComparer; internal ProducerComparer(IComparer<TKey> keyComparer) { _keyComparer = keyComparer; } public int Compare(Producer<TKey> x, Producer<TKey> y) { return _keyComparer.Compare(y.MaxKey, x.MaxKey); } } /// <summary> /// Enumerator over the results of an order-preserving pipelining merge. /// </summary> private class OrderedPipeliningMergeEnumerator : MergeEnumerator<TOutput> { /// <summary> /// Merge helper associated with this enumerator /// </summary> private readonly OrderPreservingPipeliningMergeHelper<TOutput, TKey> _mergeHelper; /// <summary> /// Heap used to efficiently locate the producer whose result should be consumed next. /// For each producer, stores the order index for the next element to be yielded. /// /// Read and written by the consumer only. /// </summary> private readonly FixedMaxHeap<Producer<TKey>> _producerHeap; /// <summary> /// Stores the next element to be yielded from each producer. We use a separate array /// rather than storing this information in the producer heap to keep the Producer struct /// small. /// /// Read and written by the consumer only. /// </summary> private readonly TOutput[] _producerNextElement; /// <summary> /// A private buffer for the consumer. When the size of a producer buffer exceeds a threshold /// (STEAL_BUFFER_SIZE), the consumer will take ownership of the entire buffer, and give the /// producer a new empty buffer to place results into. /// /// Read and written by the consumer only. /// </summary> private readonly Queue<Pair<TKey, TOutput>>?[] _privateBuffer; /// <summary> /// Tracks whether MoveNext() has already been called previously. /// </summary> private bool _initialized = false; /// <summary> /// Constructor /// </summary> internal OrderedPipeliningMergeEnumerator(OrderPreservingPipeliningMergeHelper<TOutput, TKey> mergeHelper, IComparer<Producer<TKey>> producerComparer) : base(mergeHelper._taskGroupState) { int partitionCount = mergeHelper._partitions.PartitionCount; _mergeHelper = mergeHelper; _producerHeap = new FixedMaxHeap<Producer<TKey>>(partitionCount, producerComparer); _privateBuffer = new Queue<Pair<TKey, TOutput>>[partitionCount]; _producerNextElement = new TOutput[partitionCount]; } /// <summary> /// Returns the current result /// </summary> public override TOutput Current { get { int producerToYield = _producerHeap.MaxValue.ProducerIndex; return _producerNextElement[producerToYield]; } } /// <summary> /// Moves the enumerator to the next result, or returns false if there are no more results to yield. /// </summary> public override bool MoveNext() { if (!_initialized) { // // Initialization: wait until each producer has produced at least one element. Since the order indices // are increasing, we cannot start yielding until we have at least one element from each producer. // _initialized = true; for (int producer = 0; producer < _mergeHelper._partitions.PartitionCount; producer++) { Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>); // Get the first element from this producer if (TryWaitForElement(producer, ref element)) { // Update the producer heap and its helper array with the received element _producerHeap.Insert(new Producer<TKey>(element.First, producer)); _producerNextElement[producer] = element.Second; } else { // If this producer didn't produce any results because it encountered an exception, // cancellation would have been initiated by now. If cancellation has started, we will // propagate the exception now. ThrowIfInTearDown(); } } } else { // If the producer heap is empty, we are done. In fact, we know that a previous MoveNext() call // already returned false. if (_producerHeap.Count == 0) { return false; } // // Get the next element from the producer that yielded a value last. Update the producer heap. // The next producer to yield will be in the front of the producer heap. // // The last producer whose result the merge yielded int lastProducer = _producerHeap.MaxValue.ProducerIndex; // Get the next element from the same producer Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>); if (TryGetPrivateElement(lastProducer, ref element) || TryWaitForElement(lastProducer, ref element)) { // Update the producer heap and its helper array with the received element _producerHeap.ReplaceMax(new Producer<TKey>(element.First, lastProducer)); _producerNextElement[lastProducer] = element.Second; } else { // If this producer is done because it encountered an exception, cancellation // would have been initiated by now. If cancellation has started, we will propagate // the exception now. ThrowIfInTearDown(); // This producer is done. Remove it from the producer heap. _producerHeap.RemoveMax(); } } return _producerHeap.Count > 0; } /// <summary> /// If the cancellation of the query has been initiated (because one or more producers /// encountered exceptions, or because external cancellation token has been set), the method /// will tear down the query and rethrow the exception. /// </summary> private void ThrowIfInTearDown() { if (_mergeHelper._taskGroupState.CancellationState.MergedCancellationToken.IsCancellationRequested) { try { // Wake up all producers. Since the cancellation token has already been // set, the producers will eventually stop after waking up. object[] locks = _mergeHelper._bufferLocks; for (int i = 0; i < locks.Length; i++) { lock (locks[i]) { Monitor.Pulse(locks[i]); } } // Now, we wait for all producers to wake up, notice the cancellation and stop executing. // QueryEnd will wait on all tasks to complete and then propagate all exceptions. _taskGroupState.QueryEnd(false); Debug.Fail("QueryEnd() should have thrown an exception."); } finally { // Clear the producer heap so that future calls to MoveNext simply return false. _producerHeap.Clear(); } } } /// <summary> /// Wait until a producer's buffer is non-empty, or until that producer is done. /// </summary> /// <returns>false if there is no element to yield because the producer is done, true otherwise</returns> private bool TryWaitForElement(int producer, ref Pair<TKey, TOutput> element) { Queue<Pair<TKey, TOutput>> buffer = _mergeHelper._buffers[producer]; object bufferLock = _mergeHelper._bufferLocks[producer]; lock (bufferLock) { // If the buffer is empty, we need to wait on the producer if (buffer.Count == 0) { // If the producer is already done, return false if (_mergeHelper._producerDone[producer]) { element = default(Pair<TKey, TOutput>); return false; } _mergeHelper._consumerWaiting[producer] = true; Monitor.Wait(bufferLock); // If the buffer is still empty, the producer is done if (buffer.Count == 0) { Debug.Assert(_mergeHelper._producerDone[producer]); element = default(Pair<TKey, TOutput>); return false; } } Debug.Assert(buffer.Count > 0, "Producer's buffer should not be empty here."); // If the producer is waiting, wake it up if (_mergeHelper._producerWaiting[producer]) { Monitor.Pulse(bufferLock); _mergeHelper._producerWaiting[producer] = false; } if (buffer.Count < STEAL_BUFFER_SIZE) { element = buffer.Dequeue(); return true; } else { // Privatize the entire buffer _privateBuffer[producer] = _mergeHelper._buffers[producer]; // Give an empty buffer to the producer _mergeHelper._buffers[producer] = new Queue<Pair<TKey, TOutput>>(INITIAL_BUFFER_SIZE); // No return statement. // This is the only branch that continues below of the lock region. } } // Get an element out of the private buffer. bool gotElement = TryGetPrivateElement(producer, ref element); Debug.Assert(gotElement); return true; } /// <summary> /// Looks for an element from a particular producer in the consumer's private buffer. /// </summary> private bool TryGetPrivateElement(int producer, ref Pair<TKey, TOutput> element) { var privateChunk = _privateBuffer[producer]; if (privateChunk != null) { if (privateChunk.Count > 0) { element = privateChunk.Dequeue(); return true; } Debug.Assert(_privateBuffer[producer]!.Count == 0); _privateBuffer[producer] = null; } return false; } public override void Dispose() { // Wake up any waiting producers int partitionCount = _mergeHelper._buffers.Length; for (int producer = 0; producer < partitionCount; producer++) { object bufferLock = _mergeHelper._bufferLocks[producer]; lock (bufferLock) { if (_mergeHelper._producerWaiting[producer]) { Monitor.Pulse(bufferLock); } } } base.Dispose(); } } } /// <summary> /// A structure to represent a producer in the producer heap. /// </summary> internal readonly struct Producer<TKey> { internal readonly TKey MaxKey; // Order index of the next element from this producer internal readonly int ProducerIndex; // Index of the producer, [0..DOP) internal Producer(TKey maxKey, int producerIndex) { MaxKey = maxKey; ProducerIndex = producerIndex; } } /// <summary> /// A comparer used by FixedMaxHeap(Of Producer) /// /// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to /// end up in the root of the heap. /// /// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return - /// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0 /// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return + /// </summary> internal class ProducerComparerInt : IComparer<Producer<int>> { public int Compare(Producer<int> x, Producer<int> y) { Debug.Assert(x.MaxKey >= 0 && y.MaxKey >= 0); // Guarantees no overflow on next line return y.MaxKey - x.MaxKey; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Roslyn.Test.PdbUtilities { // TODO: remove, use SymReaderFactory instead public sealed class SymReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3, IDisposable { /// <summary> /// Mock implementation: instead of a single reader with multiple versions, we'll use an array /// of readers - each with a single version. We do this so that we can implement /// <see cref="ISymUnmanagedReader3.GetSymAttributeByVersion"/> on top of /// <see cref="ISymUnmanagedReader.GetSymAttribute"/>. /// </summary> private readonly ISymUnmanagedReader[] _readerVersions; private readonly DummyMetadataImport _metadataImport; private readonly PEReader _peReaderOpt; private bool _isDisposed; public SymReader(Stream pdbStream) : this(new[] { pdbStream }, null, null) { } public SymReader(byte[] pdbImage) : this(new[] { new MemoryStream(pdbImage) }, null, null) { } public SymReader(byte[] pdbImage, byte[] peImage) : this(new[] { new MemoryStream(pdbImage) }, new MemoryStream(peImage), null) { } public SymReader(Stream pdbStream, Stream peStream) : this(new[] { pdbStream }, peStream, null) { } public SymReader(Stream pdbStream, MetadataReader metadataReader) : this(new[] { pdbStream }, null, metadataReader) { } public SymReader(Stream[] pdbStreamsByVersion, Stream peStreamOpt, MetadataReader metadataReaderOpt) { if (peStreamOpt != null) { _peReaderOpt = new PEReader(peStreamOpt); _metadataImport = new DummyMetadataImport(_peReaderOpt.GetMetadataReader()); } else { _metadataImport = new DummyMetadataImport(metadataReaderOpt); } _readerVersions = pdbStreamsByVersion.Select( pdbStream => CreateReader(pdbStream, _metadataImport)).ToArray(); // If ISymUnmanagedReader3 is available, then we shouldn't be passing in multiple byte streams - one should suffice. Debug.Assert(!(UnversionedReader is ISymUnmanagedReader3) || _readerVersions.Length == 1); } private static ISymUnmanagedReader CreateReader(Stream pdbStream, object metadataImporter) { // NOTE: The product uses a different GUID (Microsoft.CodeAnalysis.ExpressionEvaluator.DkmUtilities.s_symUnmanagedReaderClassId). Guid corSymReaderSxS = new Guid("0A3976C5-4529-4ef8-B0B0-42EED37082CD"); var reader = (ISymUnmanagedReader)Activator.CreateInstance(Marshal.GetTypeFromCLSID(corSymReaderSxS)); int hr = reader.Initialize(metadataImporter, null, null, new ComStreamWrapper(pdbStream)); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr); return reader; } private ISymUnmanagedReader UnversionedReader => _readerVersions[0]; public int GetDocuments(int cDocs, out int pcDocs, ISymUnmanagedDocument[] pDocs) { return UnversionedReader.GetDocuments(cDocs, out pcDocs, pDocs); } public int GetMethod(int methodToken, out ISymUnmanagedMethod retVal) { // The EE should never be calling ISymUnmanagedReader.GetMethod. In order to account // for EnC updates, it should always be calling GetMethodByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { // Versions are 1-based. Debug.Assert(version >= 1); var reader = _readerVersions[version - 1]; version = _readerVersions.Length > 1 ? 1 : version; return reader.GetMethodByVersion(methodToken, version, out retVal); } public int GetSymAttribute(int token, string name, int sizeBuffer, out int lengthBuffer, byte[] buffer) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { // Versions are 1-based. Debug.Assert(version >= 1); return _readerVersions[version - 1].GetSymAttribute(methodToken, name, bufferLength, out count, customDebugInformation); } public int GetUserEntryPoint(out int entryPoint) { return UnversionedReader.GetUserEntryPoint(out entryPoint); } void IDisposable.Dispose() { if (!_isDisposed) { for (int i = 0; i < _readerVersions.Length; i++) { int hr = (_readerVersions[i] as ISymUnmanagedDispose).Destroy(); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr); _readerVersions[i] = null; } _peReaderOpt?.Dispose(); _metadataImport.Dispose(); _isDisposed = true; } } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { return UnversionedReader.GetDocument(url, language, languageVendor, documentType, out document); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { return UnversionedReader.GetVariables(methodToken, bufferLength, out count, variables); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { return UnversionedReader.GetGlobalVariables(bufferLength, out count, variables); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { return UnversionedReader.GetMethodFromDocumentPosition(document, line, column, out method); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { return UnversionedReader.GetNamespaces(bufferLength, out count, namespaces); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { return UnversionedReader.Initialize(metadataImporter, fileName, searchPath, stream); } public int UpdateSymbolStore(string fileName, IStream stream) { return UnversionedReader.UpdateSymbolStore(fileName, stream); } public int ReplaceSymbolStore(string fileName, IStream stream) { return UnversionedReader.ReplaceSymbolStore(fileName, stream); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { return UnversionedReader.GetSymbolStoreFileName(bufferLength, out count, name); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { return UnversionedReader.GetMethodsFromDocumentPosition(document, line, column, bufferLength, out count, methods); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { return UnversionedReader.GetDocumentVersion(document, out version, out isCurrent); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { return UnversionedReader.GetMethodVersion(method, out version); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } } }
S/W Version Information Model: SM-R770 Tizen-Version: 2.3.2.1 Build-Number: R770XXU1APK6 Build-Date: 2016.11.25 15:41:21 Crash Information Process Name: devapp PID: 5195 Date: 2017-09-13 22:03:18-0400 Executable File Path: /opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp Signal: 6 (SIGABRT) si_code: 0 signal sent by kill (sent by pid 2582, uid 0) Register Information r0 = 0xff934a7c, r1 = 0xaabe03f8 r2 = 0x00000000, r3 = 0x00000000 r4 = 0xaac1a830, r5 = 0xaabe03f8 r6 = 0xaab501a8, r7 = 0xff9347a0 r8 = 0x00000000, r9 = 0xaac14848 r10 = 0xaac142f8, fp = 0x00000001 ip = 0xaabe03f8, sp = 0xff934768 lr = 0xff934a7c, pc = 0xaaaabbd2 cpsr = 0x60000030 Memory Information MemTotal: 714608 KB MemFree: 5800 KB Buffers: 41216 KB Cached: 199760 KB VmPeak: 83424 KB VmSize: 83420 KB VmLck: 0 KB VmPin: 0 KB VmHWM: 32056 KB VmRSS: 32052 KB VmData: 13504 KB VmStk: 6964 KB VmExe: 16 KB VmLib: 25288 KB VmPTE: 116 KB VmSwap: 0 KB Threads Information Threads: 2 PID = 5195 TID = 5195 5195 5202 Maps Information aaaaa000 aaaae000 r-xp /opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp aaabe000 aac57000 rw-p [heap] f3199000 f3998000 rw-p [stack:5202] f3998000 f399a000 r-xp /usr/lib/libcapi-media-wav-player.so.0.1.11 f39a2000 f39a3000 r-xp /usr/lib/libmmfkeysound.so.0.0.0 f39ab000 f39b3000 r-xp /usr/lib/libfeedback.so.0.1.4 f39cc000 f39cd000 r-xp /usr/lib/edje/modules/feedback/linux-gnueabi-armv7l-1.0.0/module.so f3b98000 f3baf000 r-xp /usr/lib/edje/modules/elm/linux-gnueabi-armv7l-1.0.0/module.so f3d52000 f3d57000 r-xp /usr/lib/bufmgr/libtbm_exynos.so.0.0.0 f3d5f000 f3d6a000 r-xp /usr/lib/evas/modules/engines/software_generic/linux-gnueabi-armv7l-1.7.99/module.so f4092000 f409c000 r-xp /lib/libnss_files-2.13.so f40a5000 f4174000 r-xp /usr/lib/libscim-1.0.so.8.2.3 f418a000 f41ae000 r-xp /usr/lib/ecore/immodules/libisf-imf-module.so f41b7000 f42a9000 r-xp /usr/lib/libCOREGL.so.4.0 f42c9000 f42ce000 r-xp /usr/lib/libsystem.so.0.0.0 f42d8000 f42d9000 r-xp /usr/lib/libresponse.so.0.2.96 f42e1000 f42e6000 r-xp /usr/lib/libproc-stat.so.0.2.96 f42ef000 f42f1000 r-xp /usr/lib/libpkgmgr_installer_status_broadcast_server.so.0.1.0 f42fa000 f4301000 r-xp /usr/lib/libpkgmgr_installer_client.so.0.1.0 f430a000 f432c000 r-xp /usr/lib/libpkgmgr-client.so.0.1.68 f4335000 f4338000 r-xp /lib/libattr.so.1.1.0 f4340000 f4348000 r-xp /usr/lib/libcapi-appfw-package-manager.so.0.0.59 f4350000 f4356000 r-xp /usr/lib/libcapi-appfw-app-manager.so.0.2.8 f4360000 f4365000 r-xp /usr/lib/libcapi-media-tool.so.0.1.5 f436d000 f438e000 r-xp /usr/lib/libexif.so.12.3.3 f43a1000 f43a8000 r-xp /lib/libcrypt-2.13.so f43d8000 f43db000 r-xp /lib/libcap.so.2.21 f43e3000 f43e5000 r-xp /usr/lib/libiri.so f43ee000 f4407000 r-xp /usr/lib/libprivacy-manager-client.so.0.0.8 f440f000 f4414000 r-xp /usr/lib/libmmutil_imgp.so.0.0.0 f441c000 f4422000 r-xp /usr/lib/libmmutil_jpeg.so.0.0.0 f442a000 f4447000 r-xp /usr/lib/libsecurity-server-commons.so.1.0.0 f4451000 f4455000 r-xp /usr/lib/libogg.so.0.7.1 f445d000 f447f000 r-xp /usr/lib/libvorbis.so.0.4.3 f4487000 f4489000 r-xp /usr/lib/libgmodule-2.0.so.0.3200.3 f4491000 f44bf000 r-xp /usr/lib/libidn.so.11.5.44 f44c7000 f44d0000 r-xp /usr/lib/libcares.so.2.1.0 f44da000 f44dc000 r-xp /usr/lib/libXau.so.6.0.0 f44e4000 f44e6000 r-xp /usr/lib/libttrace.so.1.1 f44ee000 f44f0000 r-xp /usr/lib/libdri2.so.0.0.0 f44f8000 f4500000 r-xp /usr/lib/libdrm.so.2.4.0 f4509000 f450a000 r-xp /usr/lib/libsecurity-privilege-checker.so.1.0.1 f4513000 f4516000 r-xp /usr/lib/libcapi-media-image-util.so.0.3.5 f451e000 f452d000 r-xp /usr/lib/libmdm-common.so.1.1.22 f4536000 f45ca000 r-xp /usr/lib/libstdc++.so.6.0.16 f45de000 f45e2000 r-xp /usr/lib/libsmack.so.1.0.0 f45eb000 f4794000 r-xp /usr/lib/libcrypto.so.1.0.0 f47b4000 f47fb000 r-xp /usr/lib/libssl.so.1.0.0 f4807000 f4836000 r-xp /usr/lib/libsecurity-server-client.so.1.0.1 f483e000 f4885000 r-xp /usr/lib/libsndfile.so.1.0.26 f4892000 f48db000 r-xp /usr/lib/pulseaudio/libpulsecommon-4.0.so f48e4000 f48e9000 r-xp /usr/lib/libjson.so.0.0.1 f48f1000 f48f4000 r-xp /usr/lib/libtinycompress.so.0.0.0 f48fc000 f48fe000 r-xp /usr/lib/journal/libjournal.so.0.1.0 f4907000 f4917000 r-xp /lib/libresolv-2.13.so f491b000 f4933000 r-xp /usr/lib/liblzma.so.5.0.3 f493b000 f493d000 r-xp /usr/lib/libsecurity-extension-common.so.1.0.1 f4945000 f4a18000 r-xp /usr/lib/libgio-2.0.so.0.3200.3 f4a23000 f4a28000 r-xp /usr/lib/libffi.so.5.0.10 f4a31000 f4a75000 r-xp /usr/lib/libcurl.so.4.3.0 f4a7e000 f4aa1000 r-xp /usr/lib/libjpeg.so.8.0.2 f4ab9000 f4acc000 r-xp /usr/lib/libxcb.so.1.1.0 f4ad5000 f4adb000 r-xp /usr/lib/libxcb-render.so.0.0.0 f4ae4000 f4ae5000 r-xp /usr/lib/libxcb-shm.so.0.0.0 f4aee000 f4b06000 r-xp /usr/lib/libpng12.so.0.50.0 f4b0e000 f4b12000 r-xp /usr/lib/libEGL.so.1.4 f4b22000 f4b33000 r-xp /usr/lib/libGLESv2.so.2.0 f4b43000 f4b44000 r-xp /usr/lib/libecore_imf_evas.so.1.7.99 f4b4d000 f4b64000 r-xp /usr/lib/liblua-5.1.so f4b6d000 f4b74000 r-xp /usr/lib/libembryo.so.1.7.99 f4b7c000 f4b87000 r-xp /usr/lib/libtbm.so.1.0.0 f4b8f000 f4bb2000 r-xp /usr/lib/libui-extension.so.0.1.0 f4bbb000 f4bd1000 r-xp /usr/lib/libtts.so f4bdb000 f4bf1000 r-xp /lib/libz.so.1.2.5 f4bf9000 f4c0f000 r-xp /lib/libexpat.so.1.6.0 f4c19000 f4c1c000 r-xp /usr/lib/libecore_input_evas.so.1.7.99 f4c24000 f4c28000 r-xp /usr/lib/libecore_ipc.so.1.7.99 f4c31000 f4c36000 r-xp /usr/lib/libecore_fb.so.1.7.99 f4c40000 f4c4a000 r-xp /usr/lib/libXext.so.6.4.0 f4c53000 f4c57000 r-xp /usr/lib/libXtst.so.6.1.0 f4c5f000 f4c65000 r-xp /usr/lib/libXrender.so.1.3.0 f4c6d000 f4c73000 r-xp /usr/lib/libXrandr.so.2.2.0 f4c7b000 f4c7c000 r-xp /usr/lib/libXinerama.so.1.0.0 f4c85000 f4c88000 r-xp /usr/lib/libXfixes.so.3.1.0 f4c91000 f4c93000 r-xp /usr/lib/libXgesture.so.7.0.0 f4c9b000 f4c9d000 r-xp /usr/lib/libXcomposite.so.1.0.0 f4ca5000 f4ca7000 r-xp /usr/lib/libXdamage.so.1.1.0 f4caf000 f4cb6000 r-xp /usr/lib/libXcursor.so.1.0.2 f4cbe000 f4d06000 r-xp /usr/lib/libmdm.so.1.2.62 f6599000 f669f000 r-xp /usr/lib/libicuuc.so.57.1 f66b5000 f683d000 r-xp /usr/lib/libicui18n.so.57.1 f684d000 f684f000 r-xp /usr/lib/libSLP-db-util.so.0.1.0 f6858000 f6865000 r-xp /usr/lib/libail.so.0.1.0 f686e000 f6871000 r-xp /usr/lib/libsyspopup_caller.so.0.1.0 f687a000 f68b2000 r-xp /usr/lib/libpulse.so.0.16.2 f68b3000 f68b6000 r-xp /usr/lib/libpulse-simple.so.0.0.4 f68be000 f691f000 r-xp /usr/lib/libasound.so.2.0.0 f6929000 f693f000 r-xp /usr/lib/libavsysaudio.so.0.0.1 f6947000 f694e000 r-xp /usr/lib/libmmfcommon.so.0.0.0 f6957000 f695b000 r-xp /usr/lib/libmmfsoundcommon.so.0.0.0 f6963000 f6964000 r-xp /usr/lib/libgthread-2.0.so.0.3200.3 f696c000 f6977000 r-xp /usr/lib/libaudio-session-mgr.so.0.0.0 f6984000 f698a000 r-xp /lib/librt-2.13.so f6993000 f6a08000 r-xp /usr/lib/libsqlite3.so.0.8.6 f6a13000 f6a2d000 r-xp /usr/lib/libpkgmgr_parser.so.0.1.0 f6a35000 f6a53000 r-xp /usr/lib/libsystemd.so.0.4.0 f6a5d000 f6a5e000 r-xp /usr/lib/libsecurity-extension-interface.so.1.0.1 f6a66000 f6a6b000 r-xp /usr/lib/libxdgmime.so.1.1.0 f6a73000 f6a8a000 r-xp /usr/lib/libdbus-glib-1.so.2.2.2 f6a93000 f6a95000 r-xp /usr/lib/libiniparser.so.0 f6a9e000 f6ad2000 r-xp /usr/lib/libgobject-2.0.so.0.3200.3 f6adb000 f6ae1000 r-xp /usr/lib/libecore_imf.so.1.7.99 f6ae9000 f6aec000 r-xp /usr/lib/libbundle.so.0.1.22 f6af4000 f6afa000 r-xp /usr/lib/libappsvc.so.0.1.0 f6b03000 f6b0a000 r-xp /usr/lib/libminizip.so.1.0.0 f6b12000 f6b68000 r-xp /usr/lib/libpixman-1.so.0.28.2 f6b75000 f6bcb000 r-xp /usr/lib/libfreetype.so.6.11.3 f6bd7000 f6c1c000 r-xp /usr/lib/libharfbuzz.so.0.10200.4 f6c25000 f6c38000 r-xp /usr/lib/libfribidi.so.0.3.1 f6c41000 f6c5b000 r-xp /usr/lib/libecore_con.so.1.7.99 f6c64000 f6c8e000 r-xp /usr/lib/libdbus-1.so.3.8.12 f6c97000 f6ca0000 r-xp /usr/lib/libedbus.so.1.7.99 f6ca8000 f6cb9000 r-xp /usr/lib/libecore_input.so.1.7.99 f6cc1000 f6cc6000 r-xp /usr/lib/libecore_file.so.1.7.99 f6cce000 f6ce7000 r-xp /usr/lib/libeet.so.1.7.99 f6cf9000 f6d02000 r-xp /usr/lib/libXi.so.6.1.0 f6d0a000 f6deb000 r-xp /usr/lib/libX11.so.6.3.0 f6df6000 f6eae000 r-xp /usr/lib/libcairo.so.2.11200.14 f6eb9000 f6f17000 r-xp /usr/lib/libedje.so.1.7.99 f6f21000 f6f38000 r-xp /usr/lib/libecore.so.1.7.99 f6f50000 f6fb9000 r-xp /lib/libm-2.13.so f6fc2000 f6fd4000 r-xp /usr/lib/libefl-assist.so.0.1.0 f6fdc000 f70ac000 r-xp /usr/lib/libglib-2.0.so.0.3200.3 f70ad000 f7179000 r-xp /usr/lib/libxml2.so.2.7.8 f7186000 f71ae000 r-xp /usr/lib/libfontconfig.so.1.8.0 f71af000 f71d1000 r-xp /usr/lib/libecore_evas.so.1.7.99 f71da000 f722a000 r-xp /usr/lib/libecore_x.so.1.7.99 f722c000 f7235000 r-xp /usr/lib/libvconf.so.0.2.45 f723d000 f7241000 r-xp /usr/lib/libmmfsession.so.0.0.0 f724a000 f724f000 r-xp /usr/lib/libcapi-system-info.so.0.2.0 f7257000 f726e000 r-xp /usr/lib/libmmfsound.so.0.1.0 f7280000 f7294000 r-xp /lib/libpthread-2.13.so f729f000 f72e0000 r-xp /usr/lib/libeina.so.1.7.99 f72e9000 f730c000 r-xp /usr/lib/libpkgmgr-info.so.0.0.17 f7314000 f7321000 r-xp /usr/lib/libaul.so.0.1.0 f732b000 f7330000 r-xp /usr/lib/libappcore-common.so.1.1 f7338000 f733e000 r-xp /usr/lib/libappcore-efl.so.1.1 f7346000 f7348000 r-xp /usr/lib/libcapi-appfw-app-common.so.0.3.2.5 f7351000 f7355000 r-xp /usr/lib/libcapi-appfw-app-control.so.0.3.2.5 f735e000 f7360000 r-xp /lib/libdl-2.13.so f7369000 f7374000 r-xp /lib/libunwind.so.8.0.1 f73a1000 f73a9000 r-xp /lib/libgcc_s-4.6.so.1 f73aa000 f74ce000 r-xp /lib/libc-2.13.so f74dc000 f74e1000 r-xp /usr/lib/libstorage.so.0.1 f74e9000 f75b7000 r-xp /usr/lib/libevas.so.1.7.99 f75dc000 f7718000 r-xp /usr/lib/libelementary.so.1.7.99 f772f000 f7750000 r-xp /usr/lib/libefl-extension.so.0.1.0 f7758000 f775a000 r-xp /usr/lib/libdlog.so.0.0.0 f7762000 f776a000 r-xp /usr/lib/libcapi-system-system-settings.so.0.0.2 f776b000 f7776000 r-xp /usr/lib/libcapi-media-sound-manager.so.0.1.54 f777e000 f7785000 r-xp /usr/lib/libcapi-media-audio-io.so.0.2.23 f778d000 f7793000 r-xp /usr/lib/libcapi-base-common.so.0.1.8 f779c000 f77a0000 r-xp /usr/lib/libcapi-appfw-application.so.0.3.2.5 f77aa000 f77b5000 r-xp /usr/lib/evas/modules/engines/software_x11/linux-gnueabi-armv7l-1.7.99/module.so f77be000 f77c2000 r-xp /usr/lib/libsys-assert.so f77cb000 f77e8000 r-xp /lib/ld-2.13.so ff928000 ffff0000 rw-p [stack] End of Maps Information Callstack Information (PID:5195) Call Stack Count: 16 0: button_clicked_test_cb + 0x11 (0xaaaabbd2) [/opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp] + 0x1bd2 1: evas_object_smart_callback_call + 0x88 (0xf751e5cd) [/usr/lib/libevas.so.1] + 0x355cd 2: (0xf6efef0d) [/usr/lib/libedje.so.1] + 0x45f0d 3: (0xf6f02efd) [/usr/lib/libedje.so.1] + 0x49efd 4: (0xf6eff869) [/usr/lib/libedje.so.1] + 0x46869 5: (0xf6effc1b) [/usr/lib/libedje.so.1] + 0x46c1b 6: (0xf6effd55) [/usr/lib/libedje.so.1] + 0x46d55 7: (0xf6f2c3f5) [/usr/lib/libecore.so.1] + 0xb3f5 8: (0xf6f29e53) [/usr/lib/libecore.so.1] + 0x8e53 9: (0xf6f2d46b) [/usr/lib/libecore.so.1] + 0xc46b 10: ecore_main_loop_begin + 0x30 (0xf6f2d879) [/usr/lib/libecore.so.1] + 0xc879 11: appcore_efl_main + 0x332 (0xf733bb47) [/usr/lib/libappcore-efl.so.1] + 0x3b47 12: ui_app_main + 0xb0 (0xf779e421) [/usr/lib/libcapi-appfw-application.so.0] + 0x2421 13: main + 0x124 (0xaaaab865) [/opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp] + 0x1865 14: __libc_start_main + 0x114 (0xf73c185c) [/lib/libc.so.6] + 0x1785c 15: (0xaaaab360) [/opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp] + 0x1360 End of Call Stack Package Information Package Name: edu.umich.edu.yctung.devapp Package ID : edu.umich.edu.yctung.devapp Version: 1.0.0 Package Type: rpm App Name: DevApp App ID: edu.umich.edu.yctung.devapp Type: capp Categories: Latest Debug Message Information --------- beginning of /dev/log_main watch_core_time_tick 09-13 22:02:14.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:15.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:15.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:15.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:15.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:15.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:16.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:16.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:16.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:16.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:16.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:17.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:17.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:17.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:17.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:17.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:18.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:18.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:18.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:18.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:18.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:19.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:19.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:19.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:19.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:19.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:20.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:20.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:20.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:20.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:20.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:21.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:21.301-0400 E/CAPI_SYSTEM_INFO( 3821): system_info_parse.c: system_info_get_value_from_config_xml(279) > cannot find tizen.org/feature/container field from /etc/config/model-config.xml file!!! 09-13 22:02:21.301-0400 E/CAPI_SYSTEM_INFO( 3821): system_info.c: system_info_get_platform_bool(293) > cannot get tizen.org/feature/container 09-13 22:02:21.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:21.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:21.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:21.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:22.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:22.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:22.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:22.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:22.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:23.151-0400 E/PKGMGR_SERVER( 5141): pkgmgr-server.c: main(2227) > package manager server start 09-13 22:02:23.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:23.271-0400 E/PKGMGR_SERVER( 5141): pkgmgr-server.c: req_cb(1134) > KILL_APP start 09-13 22:02:23.291-0400 W/AUL_AMD ( 2474): amd_request.c: __request_handler(669) > __request_handler: 14 09-13 22:02:23.301-0400 W/AUL_AMD ( 2474): amd_request.c: __send_result_to_client(91) > __send_result_to_client, pid: -1 09-13 22:02:23.301-0400 E/PKGMGR_SERVER( 5141): pkgmgr-server.c: req_cb(1153) > CHECK_KILL_APP done[return = 0] 09-13 22:02:23.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:23.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:23.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:23.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:24.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:24.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:24.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:24.721-0400 W/AUL ( 5193): launch.c: app_request_to_launchpad(284) > request cmd(0) to(edu.umich.edu.yctung.devapp) 09-13 22:02:24.721-0400 W/AUL_AMD ( 2474): amd_request.c: __request_handler(669) > __request_handler: 0 09-13 22:02:24.741-0400 I/AUL_AMD ( 2474): menu_db_util.h: _get_app_info_from_db_by_apppath(239) > path : /usr/bin/launch_app, ret : 0 09-13 22:02:24.761-0400 I/AUL_AMD ( 2474): menu_db_util.h: _get_app_info_from_db_by_apppath(239) > path : /bin/bash, ret : 0 09-13 22:02:24.761-0400 E/AUL_AMD ( 2474): amd_launch.c: _start_app(1772) > no caller appid info, ret: -1 09-13 22:02:24.761-0400 W/AUL_AMD ( 2474): amd_launch.c: _start_app(1782) > caller pid : 5193 09-13 22:02:24.781-0400 W/AUL_AMD ( 2474): amd_launch.c: _start_app(2218) > pad pid(-4) 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: main(1382) > revents : 0x0, 0x1 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: main(1400) > pfds[LAUNCHPAD_FD].revents & POLLIN 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_SDK__, value: DEBUG 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: DEBUG, value: __DLP_DEBUG_ARG__ 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __DLP_DEBUG_ARG__, value: :26109 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_STARTTIME__, value: 1505354544/733813 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_PKG_NAME__, value: edu.umich.edu.yctung.devapp 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_CALLER_PID__, value: 5193 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_HWACC__, value: SYS 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_TASKMANAGE__, value: true 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_EXEC__, value: /opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_PACKAGETYPE__, value: rpm 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_INTERNAL_POOL__, value: false 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_PKGID_, value: edu.umich.edu.yctung.devapp 09-13 22:02:24.781-0400 E/DBG_PAD ( 3809): launchpad.c: prt_recvd_bundle(1134) > recvd - key: __AUL_HIGHPRIORITY__, value: false 09-13 22:02:24.781-0400 E/RESOURCED( 2582): block.c: block_prelaunch_state(138) > insert data edu.umich.edu.yctung.devapp, table num : 4 09-13 22:02:24.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:24.791-0400 E/DBG_PAD ( 3809): launchpad.c: __prepare_fork(1013) > set DBG_LAUNCH_FLAG access label failed due to "Is a directory" 09-13 22:02:24.911-0400 W/AUL ( 2474): app_signal.c: aul_send_app_launch_request_signal(521) > aul_send_app_launch_request_signal app(edu.umich.edu.yctung.devapp) pid(5195) type(uiapp) bg(0) 09-13 22:02:24.911-0400 W/AUL ( 5193): launch.c: app_request_to_launchpad(298) > request cmd(0) result(5195) 09-13 22:02:24.931-0400 W/STARTER ( 2659): pkg-monitor.c: _app_mgr_status_cb(394) > [_app_mgr_status_cb:394] Launch request [5195] 09-13 22:02:24.941-0400 W/AUL_AMD ( 2474): amd_request.c: __request_handler(669) > __request_handler: 14 09-13 22:02:24.961-0400 W/AUL_AMD ( 2474): amd_request.c: __send_result_to_client(91) > __send_result_to_client, pid: 5195 09-13 22:02:24.961-0400 W/AUL_AMD ( 2474): amd_request.c: __request_handler(669) > __request_handler: 12 09-13 22:02:24.971-0400 W/AUL_AMD ( 2474): amd_request.c: __request_handler(669) > __request_handler: 14 09-13 22:02:24.991-0400 W/AUL_AMD ( 2474): amd_request.c: __send_result_to_client(91) > __send_result_to_client, pid: 5195 09-13 22:02:24.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:24.991-0400 W/AUL_AMD ( 2474): amd_request.c: __request_handler(669) > __request_handler: 12 09-13 22:02:25.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:25.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:25.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:25.741-0400 E/PKGMGR_SERVER( 5141): pkgmgr-server.c: exit_server(1619) > exit_server Start [backend_status=1, queue_status=1] 09-13 22:02:25.741-0400 E/PKGMGR_SERVER( 5141): pkgmgr-server.c: main(2281) > package manager server terminated. 09-13 22:02:25.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:25.921-0400 W/AUL_AMD ( 2474): amd_key.c: _key_ungrab(254) > fail(-1) to ungrab key(XF86Stop) 09-13 22:02:25.921-0400 W/AUL_AMD ( 2474): amd_launch.c: __grab_timeout_handler(1453) > back key ungrab error 09-13 22:02:25.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:26.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:26.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:26.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:26.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:26.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:27.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:27.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:27.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:27.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:27.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:28.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:28.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:28.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:28.591-0400 I/efl-extension( 5195): efl_extension.c: eext_mod_init(40) > Init 09-13 22:02:28.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:28.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:29.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:29.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:29.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:29.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:29.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:30.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:30.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:30.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:30.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:30.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:31.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:31.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:31.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:31.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:31.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:32.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:32.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:32.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:32.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:32.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:33.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:33.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:33.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:33.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:33.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:34.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:34.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:34.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:34.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:34.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:35.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:35.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:35.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:35.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:35.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:36.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:36.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:36.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:36.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:36.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:37.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:37.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:37.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:37.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:37.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:38.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:38.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:38.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:38.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:38.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:39.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:39.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:39.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:39.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:39.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:40.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:40.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:40.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:40.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:40.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:41.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:41.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:41.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:41.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:41.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:42.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:42.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:42.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:42.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:42.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:43.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:43.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:43.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:43.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:43.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:44.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:44.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:44.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:44.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:44.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:45.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:45.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:45.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:45.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:45.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:46.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:46.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:46.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:46.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:46.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:47.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:47.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:47.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:47.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:47.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:48.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:48.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:48.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:48.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:48.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:49.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:49.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:49.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:49.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:49.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:50.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:50.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:50.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:50.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:50.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:51.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:51.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:51.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:51.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:51.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:52.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:52.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:52.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:52.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:52.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:53.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:53.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:53.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:53.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:53.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:54.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:54.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:54.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:54.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:54.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:55.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:55.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:55.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:55.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:55.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:56.021-0400 W/SHealthCommon( 3180): TimelineSessionStorage.cpp: OnTriggered(1268) > localStartTime: 1505260800000.000000 09-13 22:02:56.041-0400 W/SHealthCommon( 3180): SHealthMessagePortConnection.cpp: SendServiceMessageImpl(640) > SEND SERVICE MESSAGE [name: timeline_summary_updated client list: [2:com.samsung.shealth.widget.hrlog (253052)]] 09-13 22:02:56.081-0400 W/SHealthCommon( 3180): SHealthMessagePortConnection.cpp: SendServiceMessageImpl(705) > Current shealth version [3.1.30] 09-13 22:02:56.091-0400 W/SHealthWidget( 3402): WidgetMain.cpp: widget_update(147) > ipcClientInfo: 2, com.samsung.shealth.widget.hrlog (253052), msgName: timeline_summary_updated 09-13 22:02:56.091-0400 W/SHealthCommon( 3402): IpcProxy.cpp: OnServiceMessageReceived(186) > msgName: timeline_summary_updated 09-13 22:02:56.091-0400 W/SHealthWidget( 3402): HrLogWidgetViewController.cpp: OnIpcProxyMessageReceived(71) > ##24Hour Widget Service SummaryUpdate Called 09-13 22:02:56.091-0400 W/WSLib ( 3402): ICUStringUtil.cpp: GetStrFromIcu(147) > ts:1505340176099.000000, pattern:[HH:mm] 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_value_string(522) > Enter [system_settings_get_value_string] 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_value(386) > Enter [system_settings_get_value] 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_item(361) > Enter [system_settings_get_item], key=13 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_item(374) > Enter [system_settings_get_item], index = 13, key = 13, type = 0 09-13 22:02:56.091-0400 E/WSLib ( 3402): ICUStringUtil.cpp: GetStrFromIcu(170) > locale en_US 09-13 22:02:56.091-0400 W/WSLib ( 3402): ICUStringUtil.cpp: GetStrFromIcu(195) > formattedString:[22:02] 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_value_string(522) > Enter [system_settings_get_value_string] 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_value(386) > Enter [system_settings_get_value] 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_item(361) > Enter [system_settings_get_item], key=13 09-13 22:02:56.091-0400 E/TIZEN_N_SYSTEM_SETTINGS( 3402): system_settings.c: system_settings_get_item(374) > Enter [system_settings_get_item], index = 13, key = 13, type = 0 09-13 22:02:56.091-0400 I/CAPI_WIDGET_APPLICATION( 3402): widget_app.c: __provider_update_cb(281) > received updating signal 09-13 22:02:56.101-0400 I/HealthDataService( 3005): RequestHandler.cpp: OnHealthIpcMessageSync2ndParty(147) > Server Received: SHARE_ADD 09-13 22:02:56.121-0400 I/healthData( 3180): client_dbus_connection.c: client_dbus_sendto_server_sync_with_2nd_party(370) > Server said: OK {} 09-13 22:02:56.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:56.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:56.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:56.791-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:56.991-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:57.041-0400 I/CAPI_APPFW_APPLICATION( 5195): app_main.c: ui_app_main(704) > app_efl_main 09-13 22:02:57.101-0400 I/UXT ( 5195): Uxt_ObjectManager.cpp: OnInitialized(753) > Initialized. 09-13 22:02:57.191-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:57.331-0400 W/AUL_AMD ( 2474): amd_status.c: __socket_monitor_cb(1277) > (5195) was created 09-13 22:02:57.331-0400 I/CAPI_APPFW_APPLICATION( 5195): app_main.c: _ui_app_appcore_create(563) > app_appcore_create 09-13 22:02:57.391-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:57.531-0400 E/EFL ( 5195): ecore_evas<5195> ecore_evas_extn.c:2204 ecore_evas_extn_plug_connect() Extn plug failed to connect:ipctype=0, svcname=elm_indicator_portrait, svcnum=0, svcsys=0 09-13 22:02:57.581-0400 D/devapp ( 5195): label is added 09-13 22:02:57.591-0400 I/CAPI_WATCH_APPLICATION( 3088): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 09-13 22:02:57.601-0400 D/devapp ( 5195): button is added 09-13 22:02:57.601-0400 I/APP_CORE( 5195): appcore-efl.c: __do_app(453) > [APP 5195] Event: RESET State: CREATED 09-13 22:02:57.601-0400 I/CAPI_APPFW_APPLICATION( 5195): app_main.c: _ui_app_appcore_reset(645) > app_appcore_reset 09-13 22:02:57.621-0400 D/chronograph( 3088): ChronographSweepSecond.cpp: _onSweep60sAnimationFinished(124) > BEGIN >>>> 09-13 22:02:57.621-0400 D/chronograph( 3088): ChronographSweepSecond.cpp: _onSweep60sAnimationFinished(137) > mSweep60SStartValue[57.566002] mCurrentValue[57.626999] 09-13 22:02:57.621-0400 D/chronograph( 3088): ChronographSweepSecond.cpp: _onSweep60sAnimationFinished(178) > speed up/down by 0.365982 degree in 60 seconds 09-13 22:02:57.631-0400 I/APP_CORE( 5195): appcore-efl.c: __do_app(522) > Legacy lifecycle: 0 09-13 22:02:57.631-0400 I/APP_CORE( 5195): appcore-efl.c: __do_app(524) > [APP 5195] Initial Launching, call the resume_cb 09-13 22:02:57.631-0400 I/CAPI_APPFW_APPLICATION( 5195): app_main.c: _ui_app_appcore_resume(628) > app_appcore_resume 09-13 22:02:57.641-0400 W/W_HOME ( 2933): event_manager.c: _ecore_x_message_cb(428) > state: 0 -> 1 09-13 22:02:57.641-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:4, app_state:1 win_state:1(1) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.641-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:2, app_state:1 win_state:1(1) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.641-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:1, app_state:1 win_state:1(1) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.641-0400 W/W_HOME ( 2933): main.c: _ecore_x_message_cb(997) > main_info.is_win_on_top: 0 09-13 22:02:57.641-0400 W/W_INDICATOR( 2660): windicator.c: _home_screen_clock_visibility_changed_cb(988) > [_home_screen_clock_visibility_changed_cb:988] Clock visibility : 0 09-13 22:02:57.641-0400 W/W_INDICATOR( 2660): windicator_battery.c: windicator_battery_vconfkey_unregister(426) > [windicator_battery_vconfkey_unregister:426] Unset battery cb 09-13 22:02:57.651-0400 W/APP_CORE( 5195): appcore-efl.c: __show_cb(860) > [EVENT_TEST][EVENT] GET SHOW EVENT!!!. WIN:2600002 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _window_visibility_cb(473) > Window [0x1200003] is now visible(1) 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _window_visibility_cb(483) > state: 1 -> 0 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:4, app_state:1 win_state:1(0) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:6, app_state:1 win_state:1(0) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.701-0400 I/APP_CORE( 5195): appcore-efl.c: __do_app(453) > [APP 5195] Event: RESUME State: RUNNING 09-13 22:02:57.701-0400 W/W_HOME ( 2933): main.c: _window_visibility_cb(964) > Window [0x1200003] is now visible(1) 09-13 22:02:57.701-0400 I/APP_CORE( 2933): appcore-efl.c: __do_app(453) > [APP 2933] Event: PAUSE State: RUNNING 09-13 22:02:57.701-0400 I/CAPI_APPFW_APPLICATION( 2933): app_main.c: app_appcore_pause(202) > app_appcore_pause 09-13 22:02:57.701-0400 W/W_HOME ( 2933): main.c: _appcore_pause_cb(488) > appcore pause 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _app_pause_cb(397) > state: 1 -> 2 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:2, app_state:2 win_state:1(0) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:0, app_state:2 win_state:1(0) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.701-0400 W/W_HOME ( 2933): main.c: home_pause(547) > clock/widget paused 09-13 22:02:57.701-0400 W/W_HOME ( 2933): event_manager.c: _state_control(176) > control:1, app_state:2 win_state:1(0) pm_state:1 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 09-13 22:02:57.701-0400 W/W_INDICATOR( 2660): windicator.c: _home_screen_clock_visibility_changed_cb(988) > [_home_screen_clock_visibility_changed_cb:988] Clock visibility : 0 09-13 22:02:57.701-0400 W/W_INDICATOR( 2660): windicator_battery.c: windicator_battery_vconfkey_unregister(426) > [windicator_battery_vconfkey_unregister:426] Unset battery cb 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: OnReadMessage(739) > _MessagePortIpcServer::OnReadMessage 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: HandleReceivedMessage(578) > _MessagePortIpcServer::HandleReceivedMessage 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortStub.cpp: OnIpcRequestReceived(147) > MessagePort message received 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortStub.cpp: OnCheckRemotePort(115) > _MessagePortStub::OnCheckRemotePort. 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortService.cpp: CheckRemotePort(200) > _MessagePortService::CheckRemotePort 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortService.cpp: GetKey(358) > _MessagePortService::GetKey 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortService.cpp: CheckRemotePort(213) > Check a remote message port: [com.samsung.w-music-player.music-control-service:music-control-service-request-message-port] 09-13 22:02:57.701-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: Send(847) > _MessagePortIpcServer::Stop 09-13 22:02:57.701-0400 W/AUL ( 2474): app_signal.c: aul_send_app_status_change_signal(686) > aul_send_app_status_change_signal app(com.samsung.w-home) pid(2933) status(bg) type(uiapp) 09-13 22:02:57.711-0400 W/STARTER ( 2659): pkg-monitor.c: _proc_mgr_status_cb(449) > [_proc_mgr_status_cb:449] >> P[2933] goes to (4) 09-13 22:02:57.711-0400 E/STARTER ( 2659): pkg-monitor.c: _proc_mgr_status_cb(451) > [_proc_mgr_status_cb:451] >>>>H(pid 2933)'s state(4) 09-13 22:02:57.711-0400 I/TDM ( 1956): tdm_display.c: tdm_layer_unset_buffer(1602) > [1247.971365] layer(0x410f48) now usable 09-13 22:02:57.711-0400 I/TDM ( 1956): tdm_exynos_display.c: exynos_layer_unset_buffer(1678) > [1247.971387] layer[0x4109e8]zpos[0] 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: OnReadMessage(739) > _MessagePortIpcServer::OnReadMessage 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: HandleReceivedMessage(578) > _MessagePortIpcServer::HandleReceivedMessage 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortStub.cpp: OnIpcRequestReceived(147) > MessagePort message received 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortStub.cpp: OnSendMessage(126) > MessagePort OnSendMessage 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortService.cpp: SendMessage(284) > _MessagePortService::SendMessage 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortService.cpp: GetKey(358) > _MessagePortService::GetKey 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortService.cpp: SendMessage(292) > Sends a message to a remote message port [com.samsung.w-music-player.music-control-service:music-control-service-request-message-port] 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortStub.cpp: SendMessage(138) > MessagePort SendMessage 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: SendResponse(884) > _MessagePortIpcServer::SendResponse 09-13 22:02:57.711-0400 I/MESSAGE_PORT( 2464): MessagePortIpcServer.cpp: Send(847) > _MessagePortIpcServer::Stop 09-13 22:02:57.711-0400 I/wnotib ( 2933): w-notification-board-broker-main.c: _wnotib_ecore_x_event_visibility_changed_cb(755) > fully_obscured: 1 09-13 22:02:57.711-0400 E/wnotib ( 2933): w-notification-board-action.c: wnb_action_is_drawer_hidden(4793) > [NULL==g_wnb_action_data] msg Drawer not initialized. 09-13 22:02:57.711-0400 W/wnotib ( 2933): w-notification-board-noti-manager.c: wnb_nm_postpone_updating_job(985) > Set is_notiboard_update_postponed to true with is_for_VI 0, notiboard panel creation count [1], notiboard card appending count [1]. 09-13 22:02:57.711-0400 W/STARTER ( 2659): pkg-monitor.c: _proc_mgr_status_cb(449) > [_proc_mgr_status_cb:449] >> P[5195] goes to (3) 09-13 22:02:57.711-0400 W/AUL_AMD ( 2474): amd_key.c: _key_ungrab(254) > fail(-1) to ungrab key(XF86Stop) 09-13 22:02:57.711-0400 W/AUL_AMD ( 2474): amd_launch.c: __e17_status_handler(2391) > back key ungrab error 09-13 22:02:57.711-0400 W/AUL ( 2474): app_signal.c: aul_send_app_status_change_signal(686) > aul_send_app_status_change_signal app(edu.umich.edu.yctung.devapp) pid(5195) status(fg) type(uiapp) 09-13 22:02:57.721-0400 W/WATCH_CORE( 3088): appcore-watch.c: __widget_pause(1113) > widget_pause 09-13 22:02:57.721-0400 W/AUL ( 3088): app_signal.c: aul_send_app_status_change_signal(686) > aul_send_app_status_change_signal app(com.samsung.chronograph16) pid(3088) status(bg) type(watchapp) 09-13 22:02:57.721-0400 D/chronograph( 3088): ChronographApp.cpp: _appPause(150) > >>>HIT<<< 09-13 22:02:57.721-0400 W/chronograph( 3088): ChronographViewController.cpp: onPause(183) > State is Pause[isPaused=1], StopwatchState=0 09-13 22:02:57.721-0400 W/chronograph( 3088): ChronographSweepSecond.cpp: resetSweepSecond(103) > resetSweepSecond >>>> 09-13 22:02:57.721-0400 D/chronograph( 3088): ChronographSweepSecond.cpp: resetSweepSecond(107) > Stop and Clear sweepAnimation !! 09-13 22:02:57.721-0400 D/chronograph-common( 3088): ChronographSensor.cpp: disableAcceleormeter(52) > BEGIN >>>> 09-13 22:02:57.721-0400 D/chronograph-common( 3088): ChronographSensor.cpp: _stopAccelerometer(129) > BEGIN >>>> 09-13 22:02:57.731-0400 E/CAPI_APPFW_APP_CONTROL( 3391): app_control.c: app_control_error(131) > [app_control_get_caller] INVALID_PARAMETER(0xffffffea) : invalid app_control handle type 09-13 22:02:57.741-0400 W/MUSIC_CONTROL_SERVICE( 3391): music-control-service.c: _music_control_service_pasre_request(464) > [TID:3391] [com.samsung.w-home]register msg port [false] 09-13 22:02:58.091-0400 E/AUL ( 2474): app_signal.c: __app_dbus_signal_filter(97) > reject by security issue - no interface 09-13 22:02:58.211-0400 I/APP_CORE( 2933): appcore-efl.c: __do_app(453) > [APP 2933] Event: MEM_FLUSH State: PAUSED 09-13 22:03:00.521-0400 E/EFL ( 5195): ecore_x<5195> ecore_x_events.c:563 _ecore_x_event_handle_button_press() ButtonEvent:press time=1250786 button=1 09-13 22:03:00.631-0400 E/EFL ( 5195): ecore_x<5195> ecore_x_events.c:722 _ecore_x_event_handle_button_release() ButtonEvent:release time=1250891 button=1 09-13 22:03:01.631-0400 E/EFL ( 2312): ecore_x<2312> ecore_x_netwm.c:1520 ecore_x_netwm_ping_send() Send ECORE_X_ATOM_NET_WM_PING to client win:0x2600002 time=1250891 09-13 22:03:02.711-0400 I/APP_CORE( 2933): appcore-efl.c: __do_app(453) > [APP 2933] Event: MEM_FLUSH State: PAUSED 09-13 22:03:11.641-0400 E/PROCESSMGR( 2312): e_mod_processmgr.c: _e_mod_processmgr_dbus_msg_send(315) > [PROCESSMGR] pointed_win=0x2600002 Send kill command to the ResourceD! PID=5195 Name=edu.umich.edu.yctung.devapp 09-13 22:03:11.641-0400 E/RESOURCED( 2582): proc-monitor.c: proc_dbus_watchdog_handler(838) > Receive watchdog signal to pid: 5195(devapp) 09-13 22:03:11.641-0400 E/RESOURCED( 2582): proc-monitor.c: proc_dbus_watchdog_handler(854) > just kill watchdog process when debug enabled pid: 5195(devapp) 09-13 22:03:18.761-0400 W/CRASH_MANAGER( 5206): worker.c: worker_job(1199) > 0605195646576150535459
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Searchservice { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for DataSources. /// </summary> public static partial class DataSourcesExtensions { /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSourceName'> /// The name of the datasource to create or update. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static DataSource CreateOrUpdate(this IDataSources operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateOrUpdateAsync(dataSourceName, dataSource, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSourceName'> /// The name of the datasource to create or update. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataSource> CreateOrUpdateAsync(this IDataSources operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(dataSourceName, dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Azure Search datasource. /// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSourceName'> /// The name of the datasource to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Delete(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.DeleteAsync(dataSourceName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search datasource. /// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSourceName'> /// The name of the datasource to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieves a datasource definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSourceName'> /// The name of the datasource to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static DataSource Get(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetAsync(dataSourceName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Retrieves a datasource definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSourceName'> /// The name of the datasource to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataSource> GetAsync(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all datasources available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static DataSourceListResult List(this IDataSources operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.ListAsync(searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Lists all datasources available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataSourceListResult> ListAsync(this IDataSources operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Azure Search datasource. /// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static DataSource Create(this IDataSources operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateAsync(dataSource, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search datasource. /// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataSource> CreateAsync(this IDataSources operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Data; namespace SubSonic { /// <summary> /// Summary for the ActiveRecord&lt;T&gt; class /// </summary> /// <typeparam name="T"></typeparam> [Serializable] public abstract class ActiveRecord<T> : ReadOnlyRecord<T> where T : ReadOnlyRecord<T>, new() { /// <summary> /// Initializes a new instance of the <see cref="ActiveRecord&lt;T&gt;"/> class. /// </summary> protected ActiveRecord() { MarkNew(); } #region CommandMethods /// <summary> /// Gets the provider specific (SQL Server, Oracle, etc.) SQL parameter prefix. /// </summary> /// <value>The parameter prefix.</value> protected static string ParameterPrefix { get { return BaseSchema.Provider.GetParameterPrefix(); } } /// <summary> /// Returns a INSERT QueryCommand object used to generate SQL. /// </summary> /// <param name="userName">An optional username to be used if audit fields are present</param> /// <returns></returns> public QueryCommand GetInsertCommand(string userName) { return ActiveHelper<T>.GetInsertCommand(this, userName); } /// <summary> /// Returns a UPDATE QueryCommand object used to generate SQL. /// </summary> /// <param name="userName">An optional username to be used if audit fields are present</param> /// <returns></returns> public QueryCommand GetUpdateCommand(string userName) { return ActiveHelper<T>.GetUpdateCommand(this, userName); } /// <summary> /// Returns a DELETE QueryCommand object to delete the record with /// the primary key value matching the passed value /// </summary> /// <param name="keyID">The primary key record value to match for the delete</param> /// <returns></returns> public static QueryCommand GetDeleteCommand(object keyID) { return ActiveHelper<T>.GetDeleteCommand(keyID); } /// <summary> /// Returns a DELETE QueryCommand object to delete the records with /// matching passed column/value criteria /// </summary> /// <param name="columnName">Name of the column to match</param> /// <param name="oValue">Value of column to match</param> /// <returns></returns> public static QueryCommand GetDeleteCommand(string columnName, object oValue) { return ActiveHelper<T>.GetDeleteCommand(columnName, oValue); } #endregion #region Persistence /// <summary> /// Executes before any operations occur within ActiveRecord Save() /// </summary> protected virtual void BeforeValidate() {} /// <summary> /// Executes on existing records after validation and before the update command has been generated. /// </summary> protected virtual void BeforeUpdate() {} /// <summary> /// Executes on existing records after validation and before the insert command has been generated. /// </summary> protected virtual void BeforeInsert() {} /// <summary> /// Executes after all steps have been performed for a successful ActiveRecord Save() /// </summary> protected virtual void AfterCommit() {} [Obsolete("Deprecated: Use BeforeInsert() and/or BeforeUpdate() instead.")] protected virtual void PreUpdate() {} [Obsolete("Deprecated: Use AfterCommit() instead.")] protected virtual void PostUpdate() {} /// <summary> /// Saves this object's state to the selected Database. /// </summary> public void Save() { Save(String.Empty); } /// <summary> /// Saves this object's state to the selected Database. /// </summary> /// <param name="userID">The user ID.</param> public void Save(int userID) { Save(userID.ToString()); } /// <summary> /// Saves this object's state to the selected Database. /// </summary> /// <param name="userID">The user ID.</param> public void Save(Guid userID) { string sUserID = userID.ToString(); Save(sUserID); } /// <summary> /// Validates this instance. /// </summary> /// <returns></returns> public virtual bool Validate() { ValidateColumnSettings(); return Errors.Count == 0; } /// <summary> /// Saves this object's state to the selected Database. /// </summary> /// <param name="userName">Name of the user.</param> public void Save(string userName) { bool isValid = true; if(ValidateWhenSaving) { BeforeValidate(); isValid = Validate(); } if(isValid) { if(IsNew) BeforeInsert(); else if(IsDirty) BeforeUpdate(); QueryCommand cmd = GetSaveCommand(userName); if(cmd == null) return; // reset the Primary Key with the id passed back by the operation object pkVal = DataService.ExecuteScalar(cmd); // clear out the DirtyColumns DirtyColumns.Clear(); if(pkVal != null) { if(pkVal.GetType() == typeof(decimal)) pkVal = Convert.ToInt64(pkVal); // set the primaryKey, only if an auto-increment if(BaseSchema.PrimaryKey.AutoIncrement || BaseSchema.PrimaryKey.DataType == DbType.Guid) { try { pkVal = Convert.ChangeType(pkVal, BaseSchema.PrimaryKey.GetPropertyType()); SetPrimaryKey(pkVal); } catch { // this will happen if there is no PK defined on a table. Catch this and notify throw new Exception("No Primary Key is defined for this table. A primary key is required to use SubSonic"); } } } // set this object as old MarkOld(); MarkClean(); AfterCommit(); } else { // throw an Exception string notification = String.Empty; foreach(string message in Errors) notification += message + Environment.NewLine; throw new Exception("Can't save: " + notification); } } /// <summary> /// Returns a QueryCommand object used to persist the instance to the underlying database. /// </summary> /// <returns></returns> public QueryCommand GetSaveCommand() { return GetSaveCommand(String.Empty); } /// <summary> /// Returns a QueryCommand object used to persist the instance to the underlying database. /// </summary> /// <param name="userName">An optional username to be used if audit fields are present</param> /// <returns></returns> public QueryCommand GetSaveCommand(string userName) { if(IsNew) return GetInsertCommand(userName); if(IsDirty) return GetUpdateCommand(userName); return null; } /// <summary> /// If the record contains Deleted or IsDeleted flag columns, sets them to true. If not, invokes Destroy() /// </summary> /// <param name="keyID">The key ID.</param> /// <returns>Number of rows affected by the operation</returns> public static int Delete(object keyID) { return DeleteByParameter(BaseSchema.PrimaryKey.ColumnName, keyID, null); } /// <summary> /// If the record contains Deleted or IsDeleted flag columns, sets them to true. If not, invokes Destroy() /// </summary> /// <param name="columnName">The name of the column that whose value will be evaluated for deletion</param> /// <param name="oValue">The value that will be compared against columnName to determine deletion</param> /// <returns>Number of rows affected by the operation</returns> public static int Delete(string columnName, object oValue) { return DeleteByParameter(columnName, oValue, null); } /// <summary> /// If the record contains Deleted or IsDeleted flag columns, sets them to true. If not, invokes Destroy() /// </summary> /// <param name="columnName">The name of the column that whose value will be evaluated for deletion</param> /// <param name="oValue">The value that will be compared against columnName to determine deletion</param> /// <param name="userName">The userName that the record will be updated with. Only relevant if the record contains Deleted or IsDeleted properties</param> /// <returns>Number of rows affected by the operation</returns> public static int Delete(string columnName, object oValue, string userName) { return DeleteByParameter(columnName, oValue, userName); } /// <summary> /// If the record contains Deleted or IsDeleted flag columns, sets them to true. If not, invokes Destroy() /// </summary> /// <param name="columnName">The name of the column that whose value will be evaluated for deletion</param> /// <param name="oValue">The value that will be compared against columnName to determine deletion</param> /// <param name="userName">The userName that the record will be updated with. Only relevant if the record contains Deleted or IsDeleted properties</param> /// <returns>Number of rows affected by the operation</returns> private static int DeleteByParameter(string columnName, object oValue, string userName) { return ActiveHelper<T>.Delete(columnName, oValue, userName); } /// <summary> /// Deletes the record in the table, even if it contains Deleted or IsDeleted flag columns /// </summary> /// <param name="keyID">The key ID.</param> /// <returns>Number of rows affected by the operation</returns> public static int Destroy(object keyID) { return ActiveHelper<T>.DestroyByParameter(BaseSchema.PrimaryKey.ColumnName, keyID); } /// <summary> /// Deletes the record in the table, even if it contains Deleted or IsDeleted flag columns /// </summary> /// <param name="columnName">The name of the column that whose value will be evaluated for deletion</param> /// <param name="oValue">The value that will be compared against columnName to determine deletion</param> /// <returns>Number of rows affected by the operation</returns> public static int Destroy(string columnName, object oValue) { return ActiveHelper<T>.DestroyByParameter(columnName, oValue); } /// <summary> /// Deletes the record in the table, even if it contains Deleted or IsDeleted flag columns /// </summary> /// <param name="columnName">The name of the column that whose value will be evaluated for deletion</param> /// <param name="oValue">The value that will be compared against columnName to determine deletion</param> /// <returns>Number of rows affected by the operation</returns> private static int DestroyByParameter(string columnName, object oValue) { return ActiveHelper<T>.DestroyByParameter(columnName, oValue); } #endregion /// <summary> /// Gets the column value. /// </summary> /// <typeparam name="CT">The type of the T.</typeparam> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } /// <summary> /// Gets the column value. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public object GetColumnValue(string columnName) { return GetColumnValue<object>(columnName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Culture-specific collection of resources. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // A ResourceSet stores all the resources defined in one particular CultureInfo. // // The method used to load resources is straightforward - this class // enumerates over an IResourceReader, loading every name and value, and // stores them in a hash table. Custom IResourceReaders can be used. // [Serializable] public class ResourceSet : IDisposable, IEnumerable { [NonSerialized] protected IResourceReader Reader; internal Hashtable Table; private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. #if LOOSELY_LINKED_RESOURCE_REFERENCE [OptionalField] private Assembly _assembly; // For LooselyLinkedResourceReferences #endif // LOOSELY_LINKED_RESOURCE_REFERENCE protected ResourceSet() { // To not inconvenience people subclassing us, we should allocate a new // hashtable here just so that Table is set to something. CommonInit(); } // For RuntimeResourceSet, ignore the Table parameter - it's a wasted // allocation. internal ResourceSet(bool junk) { } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to open & read from a file // on disk. // public ResourceSet(String fileName) { Reader = new ResourceReader(fileName); CommonInit(); ReadResources(); } #if LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(String fileName, Assembly assembly) { Reader = new ResourceReader(fileName); CommonInit(); _assembly = assembly; ReadResources(); } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to read from an open stream // of data. // public ResourceSet(Stream stream) { Reader = new ResourceReader(stream); CommonInit(); ReadResources(); } #if LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(Stream stream, Assembly assembly) { Reader = new ResourceReader(stream); CommonInit(); _assembly = assembly; ReadResources(); } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(IResourceReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); ReadResources(); } #if LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(IResourceReader reader, Assembly assembly) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); _assembly = assembly; ReadResources(); } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE private void CommonInit() { Table = new Hashtable(); } // Closes and releases any resources used by this ResourceSet, if any. // All calls to methods on the ResourceSet after a call to close may // fail. Close is guaranteed to be safely callable multiple times on a // particular ResourceSet, and all subclasses must support these semantics. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { // Close the Reader in a thread-safe way. IResourceReader copyOfReader = Reader; Reader = null; if (copyOfReader != null) copyOfReader.Close(); } Reader = null; _caseInsensitiveTable = null; Table = null; } public void Dispose() { Dispose(true); } #if LOOSELY_LINKED_RESOURCE_REFERENCE // Optional - used for resolving assembly manifest resource references. // This can safely be null. public Assembly Assembly { get { return _assembly; } /*protected*/ set { _assembly = value; } } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE // Returns the preferred IResourceReader class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultReader() { return typeof(ResourceReader); } // Returns the preferred IResourceWriter class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultWriter() { return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true); } public virtual IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet")); return copyOfTable.GetEnumerator(); } // Look up a string value for a resource given its name. // public virtual String GetString(String name) { Object obj = GetObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name)); } } public virtual String GetString(String name, bool ignoreCase) { Object obj; String s; // Case-sensitive lookup obj = GetObjectInternal(name); try { s = (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name)); } // case-sensitive lookup succeeded if (s != null || !ignoreCase) { return s; } // Try doing a case-insensitive lookup obj = GetCaseInsensitiveObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name)); } } // Look up an object value for a resource given its name. // public virtual Object GetObject(String name) { return GetObjectInternal(name); } public virtual Object GetObject(String name, bool ignoreCase) { Object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; return GetCaseInsensitiveObjectInternal(name); } protected virtual void ReadResources() { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { Object value = en.Value; #if LOOSELY_LINKED_RESOURCE_REFERENCE if (Assembly != null && value is LooselyLinkedResourceReference) { LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value; value = assRef.Resolve(Assembly); } #endif //LOOSELYLINKEDRESOURCEREFERENCE Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } private Object GetObjectInternal(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet")); return copyOfTable[name]; } private Object GetCaseInsensitiveObjectInternal(String name) { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet")); Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); #if _DEBUG //Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data"); BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + name + " correctly in your source"); #endif IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) { caseTable.Add(en.Key, en.Value); } _caseInsensitiveTable = caseTable; } return caseTable[name]; } } }
// ------------------------------------- // Domain : IBT / Realtime.co // Author : Nicholas Ventimiglia // Product : Messaging and Storage // Published : 2014 // ------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace Realtime.LITJson { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection ().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection ().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection ().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary ().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary ().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary (); IList<string> keys = new List<string> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add (entry.Key); } return (ICollection) keys; } } ICollection IDictionary.Values { get { EnsureDictionary (); IList<JsonData> values = new List<JsonData> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add (entry.Value); } return (ICollection) values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList ().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList ().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary ()[key]; } set { if (! (key is String)) throw new ArgumentException ( "The key has to be a string"); JsonData data = ToJsonData (value); this[(string) key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary (); return object_list[idx].Value; } set { EnsureDictionary (); JsonData data = ToJsonData (value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList ()[index]; } set { EnsureList (); JsonData data = ToJsonData (value); this[index] = data; } } #endregion #region Public Indexers public JsonData this[string prop_name] { get { EnsureDictionary (); return inst_object[prop_name]; } set { EnsureDictionary (); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (prop_name, value); if (inst_object.ContainsKey (prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add (entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection (); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection (); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData> (entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData () { } public JsonData (bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData (double number) { type = JsonType.Double; inst_double = number; } public JsonData (int number) { type = JsonType.Int; inst_int = number; } public JsonData (long number) { type = JsonType.Long; inst_long = number; } public JsonData (object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool) obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double) obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int) obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long) obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string) obj; return; } throw new ArgumentException ( "Unable to wrap the given object with JsonData"); } public JsonData (string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData (Boolean data) { return new JsonData (data); } public static implicit operator JsonData (Double data) { return new JsonData (data); } public static implicit operator JsonData (Int32 data) { return new JsonData (data); } public static implicit operator JsonData (Int64 data) { return new JsonData (data); } public static implicit operator JsonData (String data) { return new JsonData (data); } #endregion #region Explicit Conversions public static explicit operator Boolean (JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double (JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32 (JsonData data) { if (data.type != JsonType.Int) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_int; } public static explicit operator Int64 (JsonData data) { if (data.type != JsonType.Long) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_long; } public static explicit operator String (JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException ( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo (Array array, int index) { EnsureCollection ().CopyTo (array, index); } #endregion #region IDictionary Methods void IDictionary.Add (object key, object value) { JsonData data = ToJsonData (value); EnsureDictionary ().Add (key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> ((string) key, data); object_list.Add (entry); json = null; } void IDictionary.Clear () { EnsureDictionary ().Clear (); object_list.Clear (); json = null; } bool IDictionary.Contains (object key) { return EnsureDictionary ().Contains (key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return ((IOrderedDictionary) this).GetEnumerator (); } void IDictionary.Remove (object key) { EnsureDictionary ().Remove (key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string) key) { object_list.RemoveAt (i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator () { return EnsureCollection ().GetEnumerator (); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean () { if (type != JsonType.Boolean) throw new InvalidOperationException ( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble () { if (type != JsonType.Double) throw new InvalidOperationException ( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt () { if (type != JsonType.Int) throw new InvalidOperationException ( "JsonData instance doesn't hold an int"); return inst_int; } long IJsonWrapper.GetLong () { if (type != JsonType.Long) throw new InvalidOperationException ( "JsonData instance doesn't hold a long"); return inst_long; } string IJsonWrapper.GetString () { if (type != JsonType.String) throw new InvalidOperationException ( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean (bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble (double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt (int val) { type = JsonType.Int; inst_int = val; json = null; } void IJsonWrapper.SetLong (long val) { type = JsonType.Long; inst_long = val; json = null; } void IJsonWrapper.SetString (string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson () { return ToJson (); } void IJsonWrapper.ToJson (JsonWriter writer) { ToJson (writer); } #endregion #region IList Methods int IList.Add (object value) { return Add (value); } void IList.Clear () { EnsureList ().Clear (); json = null; } bool IList.Contains (object value) { return EnsureList ().Contains (value); } int IList.IndexOf (object value) { return EnsureList ().IndexOf (value); } void IList.Insert (int index, object value) { EnsureList ().Insert (index, value); json = null; } void IList.Remove (object value) { EnsureList ().Remove (value); json = null; } void IList.RemoveAt (int index) { EnsureList ().RemoveAt (index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { EnsureDictionary (); return new OrderedDictionaryEnumerator ( object_list.GetEnumerator ()); } void IOrderedDictionary.Insert (int idx, object key, object value) { string property = (string) key; JsonData data = ToJsonData (value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (property, data); object_list.Insert (idx, entry); } void IOrderedDictionary.RemoveAt (int idx) { EnsureDictionary (); inst_object.Remove (object_list[idx].Key); object_list.RemoveAt (idx); } #endregion #region Private Methods private ICollection EnsureCollection () { if (type == JsonType.Array) return (ICollection) inst_array; if (type == JsonType.Object) return (ICollection) inst_object; throw new InvalidOperationException ( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary () { if (type == JsonType.Object) return (IDictionary) inst_object; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); return (IDictionary) inst_object; } private IList EnsureList () { if (type == JsonType.Array) return (IList) inst_array; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData> (); return (IList) inst_array; } private JsonData ToJsonData (object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData) obj; return new JsonData (obj); } private static void WriteJson (IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write (null); return; } if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in ((IDictionary) obj)) { writer.WritePropertyName ((string) entry.Key); WriteJson ((JsonData) entry.Value, writer); } writer.WriteObjectEnd (); return; } } #endregion public int Add (object value) { JsonData data = ToJsonData (value); json = null; return EnsureList ().Add (data); } public bool Remove(string key) { EnsureDictionary(); return inst_object.Remove(key); } public void Clear () { if (IsObject) { ((IDictionary) this).Clear (); return; } if (IsArray) { ((IList) this).Clear (); return; } } public bool Equals (JsonData x) { if (x == null) return false; if (x.type != this.type) return false; switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals (x.inst_object); case JsonType.Array: return this.inst_array.Equals (x.inst_array); case JsonType.String: return this.inst_string.Equals (x.inst_string); case JsonType.Int: return this.inst_int.Equals (x.inst_int); case JsonType.Long: return this.inst_long.Equals (x.inst_long); case JsonType.Double: return this.inst_double.Equals (x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals (x.inst_boolean); } return false; } public JsonType GetJsonType () { return type; } public void SetJsonType (JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); break; case JsonType.Array: inst_array = new List<JsonData> (); break; case JsonType.String: inst_string = default (String); break; case JsonType.Int: inst_int = default (Int32); break; case JsonType.Long: inst_long = default (Int64); break; case JsonType.Double: inst_double = default (Double); break; case JsonType.Boolean: inst_boolean = default (Boolean); break; } this.type = type; } public string ToJson () { if (json != null) return json; StringWriter sw = new StringWriter (); JsonWriter writer = new JsonWriter (sw); writer.Validate = false; WriteJson (this, writer); json = sw.ToString (); return json; } public void ToJson (JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson (this, writer); writer.Validate = old_validate; } public override string ToString () { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString (); case JsonType.Double: return inst_double.ToString (); case JsonType.Int: return inst_int.ToString (); case JsonType.Long: return inst_long.ToString (); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry (curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator ( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext () { return list_enumerator.MoveNext (); } public void Reset () { list_enumerator.Reset (); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Threading.Tasks; using System.Web; using ASC.Common.Data; using ASC.Common.DependencyInjection; using ASC.Common.Logging; using ASC.Common.Web; using ASC.Projects.Core.DataInterfaces; using ASC.Projects.Core.Domain; using ASC.Projects.Engine; using ASC.Web.Projects.Classes; using ASC.Web.Studio.Utility; using Autofac; using Autofac.Core; using Autofac.Core.Lifetime; using Autofac.Core.Resolving; namespace ASC.Web.Projects.Core { public static class DIHelper { internal static IContainer Builder; private static bool isRegistered; private static readonly object Locker = new object(); public static void Register() { if (isRegistered) return; lock (Locker) { if (isRegistered) return; var container = AutofacConfigLoader.Load("projects"); container.Register(c => DbManager.FromHttpContext(Global.DbID)) .AsSelf() .As<IDbManager>() .InstancePerRequest(); container.Register(c => new ProjectSecurityCommon()) .AsSelf() .InstancePerRequest() .PropertiesAutowired(); container.Register(c => new ProjectSecurityProject()) .AsSelf() .As<ProjectSecurityTemplate<Project>>() .InstancePerRequest() .PropertiesAutowired(); container.Register(c => new ProjectSecurityTask()) .AsSelf() .As<ProjectSecurityTemplate<ASC.Projects.Core.Domain.Task>>() .InstancePerRequest() .PropertiesAutowired(); container.Register(c => new ProjectSecurityMilestone()) .AsSelf() .As<ProjectSecurityTemplate<Milestone>>() .InstancePerRequest() .PropertiesAutowired(); container.Register(c => new ProjectSecurityMessage()) .AsSelf() .As<ProjectSecurityTemplate<Message>>() .InstancePerRequest() .PropertiesAutowired(); container.Register(c => new ProjectSecurityTimeTracking()) .AsSelf() .As<ProjectSecurityTemplate<TimeSpend>>() .InstancePerRequest() .PropertiesAutowired(); Builder = container.Build(); isRegistered = true; } } public static ILifetimeScope Resolve(bool disableNotification = false) { return Resolve(TenantProvider.CurrentTenantID, disableNotification); } public static ILifetimeScope Resolve(int tenantID, bool disableNotification = false) { Register(); var scope = FromHttpContext(); scope.Resolve<IDbManager>(); var tenantParameter = new TypedParameter(typeof(int), tenantID); var disableNotificationParameter = new TypedParameter(typeof(bool), disableNotification); scope.Resolve<IDaoFactory>(tenantParameter); scope.Resolve<EngineFactory>(disableNotificationParameter); return scope; } private static ILifetimeScope FromHttpContext() { if (HttpContext.Current != null) { var scope = DisposableHttpContext.Current["scope"] as ILifetimeScope; if (scope == null) { scope = ToHttpContext(); } else { scope = new LifeTimeScopeProxy(scope); try { scope.Resolve<IDbManager>(); } catch (ObjectDisposedException e) { LogManager.GetLogger("ASC").Error("FromHttpContext ObjectDisposedException", e); scope = ToHttpContext(); } } return scope; } return Builder.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); } private static ILifetimeScope ToHttpContext() { var scope = Builder.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); var proxy = new LifeTimeScopeProxy(scope); DisposableHttpContext.Current["scope"] = scope; return proxy; } public static TypedParameter GetParameter<T>(T data) { return new TypedParameter(typeof(T), data); } } internal class LifeTimeScopeProxy : ILifetimeScope { private ILifetimeScope LifetimeScope { get; set; } public LifeTimeScopeProxy(ILifetimeScope lifetimeScope) { LifetimeScope = lifetimeScope; LifetimeScope.ChildLifetimeScopeBeginning += ChildLifetimeScopeBeginning; LifetimeScope.CurrentScopeEnding += CurrentScopeEnding; LifetimeScope.ResolveOperationBeginning += ResolveOperationBeginning; } public object ResolveComponent(ResolveRequest request) { return LifetimeScope.ResolveComponent(request); } public IComponentRegistry ComponentRegistry { get { return LifetimeScope.ComponentRegistry; } } public ValueTask DisposeAsync() { if (HttpContext.Current == null) { return LifetimeScope.DisposeAsync(); } return default(ValueTask); } public void Dispose() { if (HttpContext.Current == null) { LifetimeScope.Dispose(); } } public ILifetimeScope BeginLifetimeScope() { return LifetimeScope.BeginLifetimeScope(); } public ILifetimeScope BeginLifetimeScope(object tag) { return LifetimeScope.BeginLifetimeScope(tag); } public ILifetimeScope BeginLifetimeScope(Action<ContainerBuilder> configurationAction) { return LifetimeScope.BeginLifetimeScope(configurationAction); } public ILifetimeScope BeginLifetimeScope(object tag, Action<ContainerBuilder> configurationAction) { return LifetimeScope.BeginLifetimeScope(tag, configurationAction); } public IDisposer Disposer { get { return LifetimeScope.Disposer; } } public object Tag { get { return LifetimeScope.Tag; } } public event EventHandler<LifetimeScopeBeginningEventArgs> ChildLifetimeScopeBeginning; public event EventHandler<LifetimeScopeEndingEventArgs> CurrentScopeEnding; public event EventHandler<ResolveOperationBeginningEventArgs> ResolveOperationBeginning; } }
// 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.Runtime.InteropServices; using Xunit; namespace System.IO.Tests { public class Directory_GetFileSystemEntries_str_str : Directory_GetFileSystemEntries_str { #region Utilities public override string[] GetEntries(string dirName) { return Directory.GetFileSystemEntries(dirName, "*"); } public virtual string[] GetEntries(string dirName, string searchPattern) { return Directory.GetFileSystemEntries(dirName, searchPattern); } #endregion #region UniversalTests [Fact] public void SearchPatternNull() { Assert.Throws<ArgumentNullException>(() => GetEntries(TestDirectory, null)); } [Fact] public void SearchPatternEmpty() { // To avoid OS differences we have decided not to throw an argument exception when empty // string passed. But we should return 0 items. Assert.Empty(GetEntries(TestDirectory, string.Empty)); } [Fact] public void SearchPatternValid() { Assert.Empty(GetEntries(TestDirectory, "a..b abc..d")); //Should not throw } [Fact] public void SearchPatternDotIsStar() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory("TestDir1"); testDir.CreateSubdirectory("TestDir2"); using (File.Create(Path.Combine(testDir.FullName, "TestFile1"))) using (File.Create(Path.Combine(testDir.FullName, "TestFile2"))) { string[] strArr = GetEntries(testDir.FullName, "."); if (TestFiles) { Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr); } if (TestDirectories) { Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr); } } } [Fact] public void SearchPatternWithTrailingStar() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory("TestDir1"); testDir.CreateSubdirectory("TestDir2"); testDir.CreateSubdirectory("TestDir3"); using (File.Create(Path.Combine(testDir.FullName, "TestFile1"))) using (File.Create(Path.Combine(testDir.FullName, "TestFile2"))) using (File.Create(Path.Combine(testDir.FullName, "Test1File2"))) using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2"))) { string[] strArr = GetEntries(testDir.FullName, "Test1*"); if (TestFiles) { Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr); } strArr = GetEntries(testDir.FullName, "*"); if (TestFiles) { Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr); } if (TestDirectories) { Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr); } } } [Fact] public void SearchPatternWithLeadingStar() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory("TestDir1"); testDir.CreateSubdirectory("TestDir2"); testDir.CreateSubdirectory("TestDir3"); using (File.Create(Path.Combine(testDir.FullName, "TestFile1"))) using (File.Create(Path.Combine(testDir.FullName, "TestFile2"))) using (File.Create(Path.Combine(testDir.FullName, "Test1File2"))) using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2"))) { string[] strArr = GetEntries(testDir.FullName, "*2"); if (TestFiles) { Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr); } if (TestDirectories) { Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr); } strArr = GetEntries(testDir.FullName, "*Dir*"); if (TestFiles) { Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr); } if (TestDirectories) { Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr); Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr); } } } [Fact] public void SearchPatternExactMatch() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAA")); Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAAB")); Directory.CreateDirectory(Path.Combine(testDir.FullName, "CAAA")); using (File.Create(Path.Combine(testDir.FullName, "AAABB"))) using (File.Create(Path.Combine(testDir.FullName, "AAABBC"))) using (File.Create(Path.Combine(testDir.FullName, "CAAABB"))) { if (TestFiles) { string[] results = GetEntries(testDir.FullName, "AAABB"); Assert.Equal(1, results.Length); Assert.Contains(Path.Combine(testDir.FullName, "AAABB"), results); } if (TestDirectories) { string[] results = GetEntries(testDir.FullName, "AAA"); Assert.Equal(1, results.Length); Assert.Contains(Path.Combine(testDir.FullName, "AAA"), results); } } } [Fact] public void SearchPatternIgnoreSubDirectories() { //Shouldn't get files on full path by default DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName())); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) using (File.Create(Path.Combine(TestDirectory, GetTestFileName()))) { string[] results = GetEntries(TestDirectory, Path.Combine(testDir.Name, "*")); if (TestDirectories && TestFiles) Assert.Equal(2, results.Length); else Assert.Equal(1, results.Length); } } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsSearchPatternLongSegment() { // Create a path segment longer than the normal max of 255 DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string longName = new string('k', 257); Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName)); } [Fact] public void SearchPatternLongPath() { // Create a destination path longer than the traditional Windows limit of 256 characters DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string longName = new string('k', 254); string longFullname = Path.Combine(testDir.FullName, longName); if (TestFiles) { using (File.Create(longFullname)) { } } else { Directory.CreateDirectory(longFullname); } string[] results = GetEntries(testDir.FullName, longName); Assert.Contains(longFullname, results); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsSearchPatternWithDoubleDots() { Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc.."))); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "..")); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar)); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsSearchPatternInvalid() { Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0")); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ">")); Char[] invalidFileNames = Path.GetInvalidFileNameChars(); for (int i = 0; i < invalidFileNames.Length; i++) { switch (invalidFileNames[i]) { case '\\': case '/': Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()))); break; //We don't throw in V1 too case ':': //History: // 1) we assumed that this will work in all non-9x machine // 2) Then only in XP // 3) NTFS? if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && FileSystemDebugInfo.IsCurrentDriveNTFS()) // testing NTFS { Assert.Throws<IOException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()))); } else { GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())); } break; case '*': case '?': GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())); break; default: Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()))); break; } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixSearchPatternInvalid() { Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0")); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, string.Format("te{0}st", "\0".ToString()))); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsSearchPatternQuestionMarks() { string testDir1Str = GetTestFileName(); DirectoryInfo testDir = new DirectoryInfo(TestDirectory); DirectoryInfo testDir1 = testDir.CreateSubdirectory(testDir1Str); using (File.Create(Path.Combine(TestDirectory, testDir1Str, GetTestFileName()))) using (File.Create(Path.Combine(TestDirectory, GetTestFileName()))) { string[] results = GetEntries(TestDirectory, string.Format("{0}.???", new string('?', GetTestFileName().Length))); if (TestFiles && TestDirectories) Assert.Equal(2, results.Length); else Assert.Equal(1, results.Length); } } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsSearchPatternWhitespace() { Assert.Empty(GetEntries(TestDirectory, " ")); Assert.Empty(GetEntries(TestDirectory, "\n")); Assert.Empty(GetEntries(TestDirectory, " ")); Assert.Empty(GetEntries(TestDirectory, "\t")); } [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void SearchPatternCaseSensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testBase = GetTestFileName(); testDir.CreateSubdirectory(testBase + "aBBb"); testDir.CreateSubdirectory(testBase + "aBBB"); File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose(); File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose(); if (TestDirectories) { Assert.Equal(2, GetEntries(testDir.FullName, "*BB*").Length); } if (TestFiles) { Assert.Equal(2, GetEntries(testDir.FullName, "*AA*").Length); } } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void SearchPatternCaseInsensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testBase = GetTestFileName(); testDir.CreateSubdirectory(testBase + "aBBb"); testDir.CreateSubdirectory(testBase + "aBBB"); File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose(); File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose(); if (TestDirectories) { Assert.Equal(1, GetEntries(testDir.FullName, "*BB*").Length); } if (TestFiles) { Assert.Equal(1, GetEntries(testDir.FullName, "*AA*").Length); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixSearchPatternFileValidChar() { if (TestFiles) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) File.Create(Path.Combine(testDir.FullName, valid)).Dispose(); foreach (string valid in WindowsInvalidUnixValid) Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixSearchPatternDirectoryValidChar() { if (TestDirectories) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) testDir.CreateSubdirectory(valid); foreach (string valid in WindowsInvalidUnixValid) Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixSearchPatternWithDoubleDots() { // search pattern is valid but directory doesn't exist Assert.Throws<DirectoryNotFoundException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc.."))); // invalid search pattern trying to go up a directory with .. Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "..")); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar)); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc", ".."))); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "..", "abc"))); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc"))); Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc") + Path.DirectorySeparatorChar)); } #endregion } }
/* * 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.Reflection; using System.Threading; using log4net.Config; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.Assets; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Land; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using ArchiveConstants = OpenSim.Framework.Serialization.ArchiveConstants; using TarArchiveReader = OpenSim.Framework.Serialization.TarArchiveReader; using TarArchiveWriter = OpenSim.Framework.Serialization.TarArchiveWriter; using RegionSettings = OpenSim.Framework.RegionSettings; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.CoreModules.World.Archiver.Tests { [TestFixture] public class ArchiverTests : OpenSimTestCase { private Guid m_lastRequestId; private string m_lastErrorMessage; protected SceneHelpers m_sceneHelpers; protected TestScene m_scene; protected ArchiverModule m_archiverModule; protected SerialiserModule m_serialiserModule; protected TaskInventoryItem m_soundItem; [SetUp] public override void SetUp() { base.SetUp(); m_archiverModule = new ArchiverModule(); m_serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); m_sceneHelpers = new SceneHelpers(); m_scene = m_sceneHelpers.SetupScene(); SceneHelpers.SetupSceneModules(m_scene, m_archiverModule, m_serialiserModule, terrainModule); } private void LoadCompleted(Guid requestId, List<UUID> loadedScenes, string errorMessage) { lock (this) { m_lastRequestId = requestId; m_lastErrorMessage = errorMessage; Console.WriteLine("About to pulse ArchiverTests on LoadCompleted"); Monitor.PulseAll(this); } } private void SaveCompleted(Guid requestId, string errorMessage) { lock (this) { m_lastRequestId = requestId; m_lastErrorMessage = errorMessage; Console.WriteLine("About to pulse ArchiverTests on SaveCompleted"); Monitor.PulseAll(this); } } protected SceneObjectPart CreateSceneObjectPart1() { string partName = "My Little Pony"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000015"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); // Vector3 offsetPosition = new Vector3(5, 10, 15); return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, Vector3.Zero) { Name = partName }; } protected SceneObjectPart CreateSceneObjectPart2() { string partName = "Action Man"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000016"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateCylinder(); Vector3 groupPosition = new Vector3(90, 80, 70); Quaternion rotationOffset = new Quaternion(60, 70, 80, 90); Vector3 offsetPosition = new Vector3(20, 25, 30); return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition) { Name = partName }; } private void CreateTestObjects(Scene scene, out SceneObjectGroup sog1, out SceneObjectGroup sog2, out UUID ncAssetUuid) { SceneObjectPart part1 = CreateSceneObjectPart1(); sog1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(sog1, false); AssetNotecard nc = new AssetNotecard(); nc.BodyText = "Hello World!"; nc.Encode(); ncAssetUuid = UUID.Random(); UUID ncItemUuid = UUID.Random(); AssetBase ncAsset = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); m_scene.AssetService.Store(ncAsset); TaskInventoryItem ncItem = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; SceneObjectPart part2 = CreateSceneObjectPart2(); sog2 = new SceneObjectGroup(part2); part2.Inventory.AddInventoryItem(ncItem, true); scene.AddNewSceneObject(sog2, false); } private static void CreateSoundAsset(TarArchiveWriter tar, Assembly assembly, string soundDataResourceName, out byte[] soundData, out UUID soundUuid) { using (Stream resource = assembly.GetManifestResourceStream(soundDataResourceName)) { using (BinaryReader br = new BinaryReader(resource)) { // FIXME: Use the inspector instead soundData = br.ReadBytes(99999999); soundUuid = UUID.Parse("00000000-0000-0000-0000-000000000001"); string soundAssetFileName = ArchiveConstants.ASSETS_PATH + soundUuid + ArchiveConstants.ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV]; tar.WriteFile(soundAssetFileName, soundData); /* AssetBase soundAsset = AssetHelpers.CreateAsset(soundUuid, soundData); scene.AssetService.Store(soundAsset); asset1FileName = ArchiveConstants.ASSETS_PATH + soundUuid + ".wav"; */ } } } /// <summary> /// Test saving an OpenSim Region Archive. /// </summary> [Test] public void TestSaveOar() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup sog1; SceneObjectGroup sog2; UUID ncAssetUuid; CreateTestObjects(m_scene, out sog1, out sog2, out ncAssetUuid); MemoryStream archiveWriteStream = new MemoryStream(); m_scene.EventManager.OnOarFileSaved += SaveCompleted; Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); lock (this) { m_archiverModule.ArchiveRegion(archiveWriteStream, requestId); //AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer; //while (assetServer.HasWaitingRequests()) // assetServer.ProcessNextRequest(); Monitor.Wait(this, 60000); } Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); bool gotNcAssetFile = false; string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt"); List<string> foundPaths = new List<string>(); List<string> expectedPaths = new List<string>(); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1)); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2)); string filePath; TarArchiveReader.TarEntryType tarEntryType; byte[] data = tar.ReadEntry(out filePath, out tarEntryType); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions); arr.LoadControlFile(filePath, data, new DearchiveScenesInfo()); Assert.That(arr.ControlFileLoaded, Is.True); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName)); gotNcAssetFile = true; } else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { foundPaths.Add(filePath); } } Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive"); Assert.That(foundPaths, Is.EquivalentTo(expectedPaths)); // TODO: Test presence of more files and contents of files. } /// <summary> /// Test saving an OpenSim Region Archive with the no assets option /// </summary> [Test] public void TestSaveOarNoAssets() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectPart part1 = CreateSceneObjectPart1(); SceneObjectGroup sog1 = new SceneObjectGroup(part1); m_scene.AddNewSceneObject(sog1, false); SceneObjectPart part2 = CreateSceneObjectPart2(); AssetNotecard nc = new AssetNotecard(); nc.BodyText = "Hello World!"; nc.Encode(); UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000"); UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000"); AssetBase ncAsset = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); m_scene.AssetService.Store(ncAsset); SceneObjectGroup sog2 = new SceneObjectGroup(part2); TaskInventoryItem ncItem = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; part2.Inventory.AddInventoryItem(ncItem, true); m_scene.AddNewSceneObject(sog2, false); MemoryStream archiveWriteStream = new MemoryStream(); Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); Dictionary<string, Object> options = new Dictionary<string, Object>(); options.Add("noassets", true); m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options); // Don't wait for completion - with --noassets save oar happens synchronously // Monitor.Wait(this, 60000); Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); List<string> foundPaths = new List<string>(); List<string> expectedPaths = new List<string>(); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1)); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2)); string filePath; TarArchiveReader.TarEntryType tarEntryType; byte[] data = tar.ReadEntry(out filePath, out tarEntryType); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions); arr.LoadControlFile(filePath, data, new DearchiveScenesInfo()); Assert.That(arr.ControlFileLoaded, Is.True); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { Assert.Fail("Asset was found in saved oar of TestSaveOarNoAssets()"); } else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { foundPaths.Add(filePath); } } Assert.That(foundPaths, Is.EquivalentTo(expectedPaths)); // TODO: Test presence of more files and contents of files. } /// <summary> /// Test loading an OpenSim Region Archive. /// </summary> [Test] public void TestLoadOar() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); // Put in a random blank directory to check that this doesn't upset the load process tar.WriteDir("ignoreme"); // Also check that direct entries which will also have a file entry containing that directory doesn't // upset load tar.WriteDir(ArchiveConstants.TERRAINS_PATH); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); SceneObjectPart part1 = CreateSceneObjectPart1(); part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f); part1.SitTargetPosition = new Vector3(1, 2, 3); SceneObjectGroup object1 = new SceneObjectGroup(part1); // Let's put some inventory items into our object string soundItemName = "sound-item1"; UUID soundItemUuid = UUID.Parse("00000000-0000-0000-0000-000000000002"); Type type = GetType(); Assembly assembly = type.Assembly; string soundDataResourceName = null; string[] names = assembly.GetManifestResourceNames(); foreach (string name in names) { if (name.EndsWith(".Resources.test-sound.wav")) soundDataResourceName = name; } Assert.That(soundDataResourceName, Is.Not.Null); byte[] soundData; UUID soundUuid; CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid); TaskInventoryItem item1 = new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName }; part1.Inventory.AddInventoryItem(item1, true); m_scene.AddNewSceneObject(object1, false); string object1FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part1.Name, Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z), part1.UUID); tar.WriteFile(ArchiveConstants.OBJECTS_PATH + object1FileName, SceneObjectSerializer.ToXml2Format(object1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); lock (this) { m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_archiverModule.DearchiveRegion(archiveReadStream); } Assert.That(m_lastErrorMessage, Is.Null); TestLoadedRegion(part1, soundItemName, soundData); } /// <summary> /// Test loading an OpenSim Region Archive where the scene object parts are not ordered by link number (e.g. /// 2 can come after 3). /// </summary> [Test] public void TestLoadOarUnorderedParts() { TestHelpers.InMethod(); UUID ownerId = TestHelpers.ParseTail(0xaaaa); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(1, ownerId, "obj1-", 0x11); SceneObjectPart sop2 = SceneHelpers.CreateSceneObjectPart("obj1-Part2", TestHelpers.ParseTail(0x12), ownerId); SceneObjectPart sop3 = SceneHelpers.CreateSceneObjectPart("obj1-Part3", TestHelpers.ParseTail(0x13), ownerId); // Add the parts so they will be written out in reverse order to the oar sog1.AddPart(sop3); sop3.LinkNum = 3; sog1.AddPart(sop2); sop2.LinkNum = 2; tar.WriteFile( ArchiveConstants.CreateOarObjectPath(sog1.Name, sog1.UUID, sog1.AbsolutePosition), SceneObjectSerializer.ToXml2Format(sog1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); lock (this) { m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_archiverModule.DearchiveRegion(archiveReadStream); } Assert.That(m_lastErrorMessage, Is.Null); SceneObjectPart part2 = m_scene.GetSceneObjectPart("obj1-Part2"); Assert.That(part2.LinkNum, Is.EqualTo(2)); SceneObjectPart part3 = m_scene.GetSceneObjectPart("obj1-Part3"); Assert.That(part3.LinkNum, Is.EqualTo(3)); } /// <summary> /// Test loading an OpenSim Region Archive saved with the --publish option. /// </summary> [Test] public void TestLoadPublishedOar() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectPart part1 = CreateSceneObjectPart1(); SceneObjectGroup sog1 = new SceneObjectGroup(part1); m_scene.AddNewSceneObject(sog1, false); SceneObjectPart part2 = CreateSceneObjectPart2(); AssetNotecard nc = new AssetNotecard(); nc.BodyText = "Hello World!"; nc.Encode(); UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000"); UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000"); AssetBase ncAsset = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); m_scene.AssetService.Store(ncAsset); SceneObjectGroup sog2 = new SceneObjectGroup(part2); TaskInventoryItem ncItem = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; part2.Inventory.AddInventoryItem(ncItem, true); m_scene.AddNewSceneObject(sog2, false); MemoryStream archiveWriteStream = new MemoryStream(); m_scene.EventManager.OnOarFileSaved += SaveCompleted; Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); lock (this) { m_archiverModule.ArchiveRegion( archiveWriteStream, requestId, new Dictionary<string, Object>() { { "wipe-owners", Boolean.TrueString } }); Monitor.Wait(this, 60000); } Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); { UUID estateOwner = TestHelpers.ParseTail(0x4747); UUID objectOwner = TestHelpers.ParseTail(0x15); // Reload to new scene ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); SceneHelpers m_sceneHelpers2 = new SceneHelpers(); TestScene scene2 = m_sceneHelpers2.SetupScene(); SceneHelpers.SetupSceneModules(scene2, archiverModule, serialiserModule, terrainModule); // Make sure there's a valid owner for the owner we saved (this should have been wiped if the code is // behaving correctly UserAccountHelpers.CreateUserWithInventory(scene2, objectOwner); scene2.RegionInfo.EstateSettings.EstateOwner = estateOwner; lock (this) { scene2.EventManager.OnOarFileLoaded += LoadCompleted; archiverModule.DearchiveRegion(archiveReadStream); } Assert.That(m_lastErrorMessage, Is.Null); SceneObjectGroup loadedSog = scene2.GetSceneObjectGroup(part1.Name); Assert.That(loadedSog.OwnerID, Is.EqualTo(estateOwner)); Assert.That(loadedSog.LastOwnerID, Is.EqualTo(estateOwner)); } } /// <summary> /// Test OAR loading where the land parcel is group deeded. /// </summary> /// <remarks> /// In this situation, the owner ID is set to the group ID. /// </remarks> [Test] public void TestLoadOarDeededLand() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID landID = TestHelpers.ParseTail(0x10); MockGroupsServicesConnector groupsService = new MockGroupsServicesConnector(); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); config.Set("Module", "GroupsModule"); config.Set("DebugEnabled", true); SceneHelpers.SetupSceneModules( m_scene, configSource, new object[] { new GroupsModule(), groupsService, new LandManagementModule() }); // Create group in scene for loading // FIXME: For now we'll put up with the issue that we'll get a group ID that varies across tests. UUID groupID = groupsService.CreateGroup(UUID.Zero, "group1", "", true, UUID.Zero, 3, true, true, true, UUID.Zero); // Construct OAR MemoryStream oarStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(oarStream); tar.WriteDir(ArchiveConstants.LANDDATA_PATH); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); LandObject lo = new LandObject(groupID, true, m_scene); lo.SetLandBitmap(lo.BasicFullRegionLandBitmap()); LandData ld = lo.LandData; ld.GlobalID = landID; string ldPath = ArchiveConstants.CreateOarLandDataPath(ld); Dictionary<string, object> options = new Dictionary<string, object>(); tar.WriteFile(ldPath, LandDataSerializer.Serialize(ld, options)); tar.Close(); oarStream = new MemoryStream(oarStream.ToArray()); // Load OAR lock (this) { m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_archiverModule.DearchiveRegion(oarStream); } ILandObject rLo = m_scene.LandChannel.GetLandObject(16, 16); LandData rLd = rLo.LandData; Assert.That(rLd.GlobalID, Is.EqualTo(landID)); Assert.That(rLd.OwnerID, Is.EqualTo(groupID)); Assert.That(rLd.GroupID, Is.EqualTo(groupID)); Assert.That(rLd.IsGroupOwned, Is.EqualTo(true)); } /// <summary> /// Test loading the region settings of an OpenSim Region Archive. /// </summary> [Test] public void TestLoadOarRegionSettings() { TestHelpers.InMethod(); //log4net.Config.XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); tar.WriteDir(ArchiveConstants.TERRAINS_PATH); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); RegionSettings rs = new RegionSettings(); rs.AgentLimit = 17; rs.AllowDamage = true; rs.AllowLandJoinDivide = true; rs.AllowLandResell = true; rs.BlockFly = true; rs.BlockShowInSearch = true; rs.BlockTerraform = true; rs.DisableCollisions = true; rs.DisablePhysics = true; rs.DisableScripts = true; rs.Elevation1NW = 15.9; rs.Elevation1NE = 45.3; rs.Elevation1SE = 49; rs.Elevation1SW = 1.9; rs.Elevation2NW = 4.5; rs.Elevation2NE = 19.2; rs.Elevation2SE = 9.2; rs.Elevation2SW = 2.1; rs.FixedSun = true; rs.SunPosition = 12.0; rs.ObjectBonus = 1.4; rs.RestrictPushing = true; rs.TerrainLowerLimit = 0.4; rs.TerrainRaiseLimit = 17.9; rs.TerrainTexture1 = UUID.Parse("00000000-0000-0000-0000-000000000020"); rs.TerrainTexture2 = UUID.Parse("00000000-0000-0000-0000-000000000040"); rs.TerrainTexture3 = UUID.Parse("00000000-0000-0000-0000-000000000060"); rs.TerrainTexture4 = UUID.Parse("00000000-0000-0000-0000-000000000080"); rs.UseEstateSun = true; rs.WaterHeight = 23; rs.TelehubObject = UUID.Parse("00000000-0000-0000-0000-111111111111"); rs.AddSpawnPoint(SpawnPoint.Parse("1,-2,0.33")); tar.WriteFile(ArchiveConstants.SETTINGS_PATH + "region1.xml", RegionSettingsSerializer.Serialize(rs)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); lock (this) { m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_archiverModule.DearchiveRegion(archiveReadStream); } Assert.That(m_lastErrorMessage, Is.Null); RegionSettings loadedRs = m_scene.RegionInfo.RegionSettings; Assert.That(loadedRs.AgentLimit, Is.EqualTo(17)); Assert.That(loadedRs.AllowDamage, Is.True); Assert.That(loadedRs.AllowLandJoinDivide, Is.True); Assert.That(loadedRs.AllowLandResell, Is.True); Assert.That(loadedRs.BlockFly, Is.True); Assert.That(loadedRs.BlockShowInSearch, Is.True); Assert.That(loadedRs.BlockTerraform, Is.True); Assert.That(loadedRs.DisableCollisions, Is.True); Assert.That(loadedRs.DisablePhysics, Is.True); Assert.That(loadedRs.DisableScripts, Is.True); Assert.That(loadedRs.Elevation1NW, Is.EqualTo(15.9)); Assert.That(loadedRs.Elevation1NE, Is.EqualTo(45.3)); Assert.That(loadedRs.Elevation1SE, Is.EqualTo(49)); Assert.That(loadedRs.Elevation1SW, Is.EqualTo(1.9)); Assert.That(loadedRs.Elevation2NW, Is.EqualTo(4.5)); Assert.That(loadedRs.Elevation2NE, Is.EqualTo(19.2)); Assert.That(loadedRs.Elevation2SE, Is.EqualTo(9.2)); Assert.That(loadedRs.Elevation2SW, Is.EqualTo(2.1)); Assert.That(loadedRs.FixedSun, Is.True); Assert.AreEqual(12.0, loadedRs.SunPosition); Assert.That(loadedRs.ObjectBonus, Is.EqualTo(1.4)); Assert.That(loadedRs.RestrictPushing, Is.True); Assert.That(loadedRs.TerrainLowerLimit, Is.EqualTo(0.4)); Assert.That(loadedRs.TerrainRaiseLimit, Is.EqualTo(17.9)); Assert.That(loadedRs.TerrainTexture1, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000020"))); Assert.That(loadedRs.TerrainTexture2, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000040"))); Assert.That(loadedRs.TerrainTexture3, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000060"))); Assert.That(loadedRs.TerrainTexture4, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000080"))); Assert.That(loadedRs.UseEstateSun, Is.True); Assert.That(loadedRs.WaterHeight, Is.EqualTo(23)); Assert.AreEqual(UUID.Zero, loadedRs.TelehubObject); // because no object was found with the original UUID Assert.AreEqual(0, loadedRs.SpawnPoints().Count); } /// <summary> /// Test merging an OpenSim Region Archive into an existing scene /// </summary> //[Test] public void TestMergeOar() { TestHelpers.InMethod(); //XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); // string part2Name = "objectMerge"; // PrimitiveBaseShape part2Shape = PrimitiveBaseShape.CreateCylinder(); // Vector3 part2GroupPosition = new Vector3(90, 80, 70); // Quaternion part2RotationOffset = new Quaternion(60, 70, 80, 90); // Vector3 part2OffsetPosition = new Vector3(20, 25, 30); SceneObjectPart part2 = CreateSceneObjectPart2(); // Create an oar file that we can use for the merge { ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); Scene scene = m_sceneHelpers.SetupScene(); SceneHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); m_scene.AddNewSceneObject(new SceneObjectGroup(part2), false); // Write out this scene scene.EventManager.OnOarFileSaved += SaveCompleted; lock (this) { m_archiverModule.ArchiveRegion(archiveWriteStream); Monitor.Wait(this, 60000); } } { SceneObjectPart part1 = CreateSceneObjectPart1(); m_scene.AddNewSceneObject(new SceneObjectGroup(part1), false); // Merge in the archive we created earlier byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); archiveOptions.Add("merge", null); m_archiverModule.DearchiveRegion(archiveReadStream, Guid.Empty, archiveOptions); SceneObjectPart object1Existing = m_scene.GetSceneObjectPart(part1.Name); Assert.That(object1Existing, Is.Not.Null, "object1 was not present after merge"); Assert.That(object1Existing.Name, Is.EqualTo(part1.Name), "object1 names not identical after merge"); Assert.That(object1Existing.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal after merge"); SceneObjectPart object2PartMerged = m_scene.GetSceneObjectPart(part2.Name); Assert.That(object2PartMerged, Is.Not.Null, "object2 was not present after merge"); Assert.That(object2PartMerged.Name, Is.EqualTo(part2.Name), "object2 names not identical after merge"); Assert.That(object2PartMerged.GroupPosition, Is.EqualTo(part2.GroupPosition), "object2 group position not equal after merge"); } } /// <summary> /// Test saving a multi-region OAR. /// </summary> [Test] public void TestSaveMultiRegionOar() { TestHelpers.InMethod(); // Create test regions int WIDTH = 2; int HEIGHT = 2; List<Scene> scenes = new List<Scene>(); // Maps (Directory in OAR file -> scene) Dictionary<string, Scene> regionPaths = new Dictionary<string, Scene>(); // Maps (Scene -> expected object paths) Dictionary<UUID, List<string>> expectedPaths = new Dictionary<UUID, List<string>>(); // List of expected assets List<UUID> expectedAssets = new List<UUID>(); for (uint y = 0; y < HEIGHT; y++) { for (uint x = 0; x < WIDTH; x++) { Scene scene; if (x == 0 && y == 0) { scene = m_scene; // this scene was already created in SetUp() } else { scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y); SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule()); } scenes.Add(scene); string dir = String.Format("{0}_{1}_{2}", x + 1, y + 1, scene.RegionInfo.RegionName.Replace(" ", "_")); regionPaths[dir] = scene; SceneObjectGroup sog1; SceneObjectGroup sog2; UUID ncAssetUuid; CreateTestObjects(scene, out sog1, out sog2, out ncAssetUuid); expectedPaths[scene.RegionInfo.RegionID] = new List<string>(); expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog1)); expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog2)); expectedAssets.Add(ncAssetUuid); } } // Save OAR MemoryStream archiveWriteStream = new MemoryStream(); m_scene.EventManager.OnOarFileSaved += SaveCompleted; Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); Dictionary<string, Object> options = new Dictionary<string, Object>(); options.Add("all", true); lock (this) { m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options); Monitor.Wait(this, 60000); } // Check that the OAR contains the expected data Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); Dictionary<UUID, List<string>> foundPaths = new Dictionary<UUID, List<string>>(); List<UUID> foundAssets = new List<UUID>(); foreach (Scene scene in scenes) { foundPaths[scene.RegionInfo.RegionID] = new List<string>(); } string filePath; TarArchiveReader.TarEntryType tarEntryType; byte[] data = tar.ReadEntry(out filePath, out tarEntryType); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions); arr.LoadControlFile(filePath, data, new DearchiveScenesInfo()); Assert.That(arr.ControlFileLoaded, Is.True); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { // Assets are shared, so this file doesn't belong to any specific region. string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); if (fileName.EndsWith("_notecard.txt")) foundAssets.Add(UUID.Parse(fileName.Substring(0, fileName.Length - "_notecard.txt".Length))); } else { // This file belongs to one of the regions. Find out which one. Assert.IsTrue(filePath.StartsWith(ArchiveConstants.REGIONS_PATH)); string[] parts = filePath.Split(new Char[] { '/' }, 3); Assert.AreEqual(3, parts.Length); string regionDirectory = parts[1]; string relativePath = parts[2]; Scene scene = regionPaths[regionDirectory]; if (relativePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { foundPaths[scene.RegionInfo.RegionID].Add(relativePath); } } } Assert.AreEqual(scenes.Count, foundPaths.Count); foreach (Scene scene in scenes) { Assert.That(foundPaths[scene.RegionInfo.RegionID], Is.EquivalentTo(expectedPaths[scene.RegionInfo.RegionID])); } Assert.That(foundAssets, Is.EquivalentTo(expectedAssets)); } /// <summary> /// Test loading a multi-region OAR. /// </summary> [Test] public void TestLoadMultiRegionOar() { TestHelpers.InMethod(); // Create an ArchiveScenesGroup with the regions in the OAR. This is needed to generate the control file. int WIDTH = 2; int HEIGHT = 2; for (uint y = 0; y < HEIGHT; y++) { for (uint x = 0; x < WIDTH; x++) { Scene scene; if (x == 0 && y == 0) { scene = m_scene; // this scene was already created in SetUp() } else { scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y); SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule()); } } } ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup(); m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene) { scenesGroup.AddScene(scene); }); scenesGroup.CalcSceneLocations(); // Generate the OAR file MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); ArchiveWriteRequest writeRequest = new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty); writeRequest.MultiRegionFormat = true; tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, writeRequest.CreateControlFile(scenesGroup)); SceneObjectPart part1 = CreateSceneObjectPart1(); part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f); part1.SitTargetPosition = new Vector3(1, 2, 3); SceneObjectGroup object1 = new SceneObjectGroup(part1); // Let's put some inventory items into our object string soundItemName = "sound-item1"; UUID soundItemUuid = UUID.Parse("00000000-0000-0000-0000-000000000002"); Type type = GetType(); Assembly assembly = type.Assembly; string soundDataResourceName = null; string[] names = assembly.GetManifestResourceNames(); foreach (string name in names) { if (name.EndsWith(".Resources.test-sound.wav")) soundDataResourceName = name; } Assert.That(soundDataResourceName, Is.Not.Null); byte[] soundData; UUID soundUuid; CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid); TaskInventoryItem item1 = new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName }; part1.Inventory.AddInventoryItem(item1, true); m_scene.AddNewSceneObject(object1, false); string object1FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part1.Name, Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z), part1.UUID); string path = "regions/1_1_Unit_test_region/" + ArchiveConstants.OBJECTS_PATH + object1FileName; tar.WriteFile(path, SceneObjectSerializer.ToXml2Format(object1)); tar.Close(); // Delete the current objects, to test that they're loaded from the OAR and didn't // just remain in the scene. m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene) { scene.DeleteAllSceneObjects(); }); // Create a "hole", to test that that the corresponding region isn't loaded from the OAR m_sceneHelpers.SceneManager.CloseScene(SceneManager.Instance.Scenes[1]); // Check thay the OAR file contains the expected data MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); lock (this) { m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_archiverModule.DearchiveRegion(archiveReadStream); } Assert.That(m_lastErrorMessage, Is.Null); Assert.AreEqual(3, m_sceneHelpers.SceneManager.Scenes.Count); TestLoadedRegion(part1, soundItemName, soundData); } private void TestLoadedRegion(SceneObjectPart part1, string soundItemName, byte[] soundData) { SceneObjectPart object1PartLoaded = m_scene.GetSceneObjectPart(part1.Name); Assert.That(object1PartLoaded, Is.Not.Null, "object1 was not loaded"); Assert.That(object1PartLoaded.Name, Is.EqualTo(part1.Name), "object1 names not identical"); Assert.That(object1PartLoaded.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal"); Assert.That( object1PartLoaded.RotationOffset, Is.EqualTo(part1.RotationOffset), "object1 rotation offset not equal"); Assert.That( object1PartLoaded.OffsetPosition, Is.EqualTo(part1.OffsetPosition), "object1 offset position not equal"); Assert.That(object1PartLoaded.SitTargetOrientation, Is.EqualTo(part1.SitTargetOrientation)); Assert.That(object1PartLoaded.SitTargetPosition, Is.EqualTo(part1.SitTargetPosition)); TaskInventoryItem loadedSoundItem = object1PartLoaded.Inventory.GetInventoryItems(soundItemName)[0]; Assert.That(loadedSoundItem, Is.Not.Null, "loaded sound item was null"); AssetBase loadedSoundAsset = m_scene.AssetService.Get(loadedSoundItem.AssetID.ToString()); Assert.That(loadedSoundAsset, Is.Not.Null, "loaded sound asset was null"); Assert.That(loadedSoundAsset.Data, Is.EqualTo(soundData), "saved and loaded sound data do not match"); Assert.Greater(m_scene.LandChannel.AllParcels().Count, 0, "incorrect number of parcels"); } } }
// Copyright (c) 2007-2014 Joe White // // 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; using DGrok.DelphiNodes; namespace DGrok.Framework { public partial class Parser { private ListNode<AstNode> _emptyList; private IFrame _nextFrame; private Rule[] _rules; public Parser(IFrame frame) { RuleType maxRuleType = 0; foreach (RuleType ruleType in Enum.GetValues(typeof(RuleType))) { if (ruleType > maxRuleType) maxRuleType = ruleType; } _rules = new Rule[((int) maxRuleType) + 1]; _nextFrame = frame; _emptyList = CreateEmptyListNode<AstNode>(); #region AddOp AddTokenRule(RuleType.AddOp, TokenSets.AddOp); #endregion #region ArrayType AddRule(RuleType.ArrayType, LookAhead(TokenType.ArrayKeyword), delegate { Token array = ParseToken(TokenType.ArrayKeyword); Token openBracket = null; ListNode<DelimitedItemNode<AstNode>> indexList; Token closeBracket = null; if (CanParseToken(TokenType.OpenBracket)) { openBracket = ParseToken(TokenType.OpenBracket); indexList = ParseDelimitedList<AstNode>(RuleType.Type, TokenType.Comma); closeBracket = ParseToken(TokenType.CloseBracket); } else indexList = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); Token of = ParseToken(TokenType.OfKeyword); AstNode type = ParseRuleInternal(RuleType.Type); return new ArrayTypeNode(array, openBracket, indexList, closeBracket, of, type); }); #endregion #region AssemblerStatement AddRule(RuleType.AssemblerStatement, LookAhead(TokenType.AsmKeyword), delegate { Token asm = ParseToken(TokenType.AsmKeyword); while (!CanParseToken(TokenType.EndKeyword)) MoveNext(); Token end = ParseToken(TokenType.EndKeyword); return new AssemblerStatementNode(asm, end); }); #endregion #region AssemblyAttribute AddRule(RuleType.AssemblyAttribute, LookAhead(TokenType.OpenBracket), delegate { Token openBracket = ParseToken(TokenType.OpenBracket); Token scope = ParseToken(TokenType.AssemblySemikeyword); Token colon = ParseToken(TokenType.Colon); AstNode value = ParseRuleInternal(RuleType.Expression); Token closeBracket = ParseToken(TokenType.CloseBracket); return new AttributeNode(openBracket, scope, colon, value, closeBracket); }); #endregion #region Atom AddRule(RuleType.Atom, delegate { return CanParseRule(RuleType.Particle); }, delegate { AstNode node = ParseRuleInternal(RuleType.Particle); while (true) { if (CanParseToken(TokenType.Dot)) { Token dot = ParseToken(TokenType.Dot); AstNode right = ParseRuleInternal(RuleType.ExtendedIdent); node = new BinaryOperationNode(node, dot, right); } else if (CanParseToken(TokenType.Caret)) { Token caret = ParseToken(TokenType.Caret); node = new PointerDereferenceNode(node, caret); } else if (CanParseToken(TokenType.OpenBracket)) { Token openDelimiter = ParseToken(TokenType.OpenBracket); ListNode<DelimitedItemNode<AstNode>> parameterList = (ListNode<DelimitedItemNode<AstNode>>) ParseRuleInternal(RuleType.ExpressionList); Token closeDelimiter = ParseToken(TokenType.CloseBracket); node = new ParameterizedNode(node, openDelimiter, parameterList, closeDelimiter); } else if (CanParseToken(TokenType.OpenParenthesis)) { Token openDelimiter = ParseToken(TokenType.OpenParenthesis); ListNode<DelimitedItemNode<AstNode>> parameterList; if (CanParseRule(RuleType.ExpressionList)) { parameterList = ParseDelimitedList<AstNode>(RuleType.ParameterExpression, TokenType.Comma); } else parameterList = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); Token closeDelimiter = ParseToken(TokenType.CloseParenthesis); node = new ParameterizedNode(node, openDelimiter, parameterList, closeDelimiter); } else break; } return node; }); #endregion #region BareInherited AddRule(RuleType.BareInherited, delegate { return Peek(0) == TokenType.InheritedKeyword && !TokenSets.Expression.Contains(Peek(1)); }, delegate { return ParseToken(TokenType.InheritedKeyword); }); #endregion #region Block AddRule(RuleType.Block, TokenSets.Block.LookAhead, delegate { if (CanParseRule(RuleType.AssemblerStatement)) return ParseRuleInternal(RuleType.AssemblerStatement); else { Token begin = ParseToken(TokenType.BeginKeyword); ListNode<DelimitedItemNode<AstNode>> statementList = ParseOptionalStatementList(); Token end = ParseToken(TokenType.EndKeyword); return new BlockNode(begin, statementList, end); } }); #endregion #region CaseSelector AddRule(RuleType.CaseSelector, delegate { return CanParseRule(RuleType.ExpressionOrRangeList); }, delegate { ListNode<DelimitedItemNode<AstNode>> values = ParseDelimitedList<AstNode>(RuleType.ExpressionOrRange, TokenType.Comma); Token colon = ParseToken(TokenType.Colon); AstNode statement = null; if (CanParseRule(RuleType.Statement)) statement = ParseRuleInternal(RuleType.Statement); Token semicolon = null; if (CanParseToken(TokenType.Semicolon)) semicolon = ParseToken(TokenType.Semicolon); return new CaseSelectorNode(values, colon, statement, semicolon); }); #endregion #region CaseStatement AddRule(RuleType.CaseStatement, LookAhead(TokenType.CaseKeyword), delegate { Token theCase = ParseToken(TokenType.CaseKeyword); AstNode expression = ParseRuleInternal(RuleType.Expression); Token of = ParseToken(TokenType.OfKeyword); ListNode<CaseSelectorNode> selectorList = ParseRequiredRuleList<CaseSelectorNode>(RuleType.CaseSelector); Token theElse = null; ListNode<DelimitedItemNode<AstNode>> elseStatements = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); if (CanParseToken(TokenType.ElseKeyword)) { theElse = ParseToken(TokenType.ElseKeyword); elseStatements = ParseOptionalStatementList(); } Token end = ParseToken(TokenType.EndKeyword); return new CaseStatementNode(theCase, expression, of, selectorList, theElse, elseStatements, end); }); #endregion #region ClassHelperType AddRule(RuleType.ClassHelperType, delegate { return Peek(0) == TokenType.ClassKeyword && Peek(1) == TokenType.HelperSemikeyword; }, delegate { Token typeKeyword = ParseToken(TokenType.ClassKeyword); Token helper = ParseToken(TokenType.HelperSemikeyword); Token openParenthesis = null; AstNode baseHelperType = null; Token closeParenthesis = null; if (CanParseToken(TokenType.OpenParenthesis)) { openParenthesis = ParseToken(TokenType.OpenParenthesis); baseHelperType = ParseRuleInternal(RuleType.QualifiedIdent); closeParenthesis = ParseToken(TokenType.CloseParenthesis); } Token theFor = ParseToken(TokenType.ForKeyword); AstNode type = ParseRuleInternal(RuleType.QualifiedIdent); ListNode<VisibilitySectionNode> contents = ParseOptionalRuleList<VisibilitySectionNode>(RuleType.VisibilitySection); Token end = ParseToken(TokenType.EndKeyword); return new TypeHelperNode(typeKeyword, helper, openParenthesis, baseHelperType, closeParenthesis, theFor, type, contents, end); }); #endregion #region ClassOfType AddRule(RuleType.ClassOfType, delegate { return Peek(0) == TokenType.ClassKeyword && Peek(1) == TokenType.OfKeyword; }, delegate { Token theClass = ParseToken(TokenType.ClassKeyword); Token of = ParseToken(TokenType.OfKeyword); AstNode type = ParseRuleInternal(RuleType.QualifiedIdent); return new ClassOfNode(theClass, of, type); }); #endregion #region ClassType AddRule(RuleType.ClassType, LookAhead(TokenType.ClassKeyword), delegate { Token theClass = ParseToken(TokenType.ClassKeyword); Token disposition = null; if (CanParseToken(TokenSets.ClassDisposition)) disposition = ParseToken(TokenSets.ClassDisposition); Token openParenthesis = null; ListNode<DelimitedItemNode<AstNode>> inheritanceList = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); Token closeParenthesis = null; if (CanParseToken(TokenType.OpenParenthesis)) { openParenthesis = ParseToken(TokenType.OpenParenthesis); inheritanceList = ParseDelimitedList<AstNode>(RuleType.QualifiedIdent, TokenType.Comma); closeParenthesis = ParseToken(TokenType.CloseParenthesis); } ListNode<VisibilitySectionNode> contents = CreateEmptyListNode<VisibilitySectionNode>(); Token end = null; if (!CanParseToken(TokenType.Semicolon)) { contents = ParseOptionalRuleList<VisibilitySectionNode>(RuleType.VisibilitySection); end = ParseToken(TokenType.EndKeyword); } return new ClassTypeNode(theClass, disposition, openParenthesis, inheritanceList, closeParenthesis, contents, end); }); #endregion #region ConstantDecl AddRule(RuleType.ConstantDecl, delegate { return CanParseRule(RuleType.Ident) && !CanParseRule(RuleType.Visibility); }, delegate { Token name = ParseIdent(); Token colon = null; AstNode type = null; if (CanParseToken(TokenType.Colon)) { colon = ParseToken(TokenType.Colon); type = ParseRuleInternal(RuleType.Type); } Token equalSign = ParseToken(TokenType.EqualSign); AstNode value = ParseRuleInternal(RuleType.TypedConstant); ListNode<Token> portabilityDirectiveList = ParseOptionalRuleList<Token>(RuleType.PortabilityDirective); Token semicolon = ParseToken(TokenType.Semicolon); return new ConstantDeclNode(name, colon, type, equalSign, value, portabilityDirectiveList, semicolon); }); #endregion #region ConstSection AddRule(RuleType.ConstSection, TokenSets.ConstHeader.LookAhead, delegate { Token theConst = ParseToken(TokenSets.ConstHeader); ListNode<ConstantDeclNode> constList = ParseRequiredRuleList<ConstantDeclNode>(RuleType.ConstantDecl); return new ConstSectionNode(theConst, constList); }); #endregion #region Directive TokenSet parameterizedDirectives = new TokenSet("'dispid' or 'message'"); parameterizedDirectives.Add(TokenType.DispIdSemikeyword); parameterizedDirectives.Add(TokenType.MessageSemikeyword); AddRule(RuleType.Directive, delegate{ return TokenSets.Directive.Contains(Peek(0)) || (Peek(0) == TokenType.Semicolon && TokenSets.Directive.Contains(Peek(1))); }, delegate { Token semicolon = null; if (CanParseToken(TokenType.Semicolon)) semicolon = ParseToken(TokenType.Semicolon); Token directive; AstNode value = null; AstNode data = _emptyList; if (CanParseToken(parameterizedDirectives)) { directive = ParseToken(parameterizedDirectives); value = ParseRuleInternal(RuleType.Expression); } else if (CanParseToken(TokenType.ExternalSemikeyword)) { directive = ParseToken(TokenType.ExternalSemikeyword); if (CanParseRule(RuleType.Expression)) { value = ParseRuleInternal(RuleType.Expression); data = ParseOptionalRuleList<ExportsSpecifierNode>(RuleType.ExportsSpecifier); } } else directive = ParseToken(TokenSets.Directive); return new DirectiveNode(semicolon, directive, value, data); }); #endregion #region EnumeratedType AddRule(RuleType.EnumeratedType, LookAhead(TokenType.OpenParenthesis), delegate { Token openParenthesis = ParseToken(TokenType.OpenParenthesis); ListNode<DelimitedItemNode<EnumeratedTypeElementNode>> itemList = ParseDelimitedList<EnumeratedTypeElementNode>( RuleType.EnumeratedTypeElement, TokenType.Comma); Token closeParenthesis = ParseToken(TokenType.CloseParenthesis); return new EnumeratedTypeNode(openParenthesis, itemList, closeParenthesis); }); #endregion #region EnumeratedTypeElement AddRule(RuleType.EnumeratedTypeElement, TokenSets.Ident.LookAhead, delegate { Token name = ParseIdent(); Token equalSign = null; AstNode value = null; if (CanParseToken(TokenType.EqualSign)) { equalSign = ParseToken(TokenType.EqualSign); value = ParseRuleInternal(RuleType.Expression); } return new EnumeratedTypeElementNode(name, equalSign, value); }); #endregion #region ExceptionItem AddRule(RuleType.ExceptionItem, LookAhead(TokenType.OnSemikeyword), delegate { Token on = ParseToken(TokenType.OnSemikeyword); Token name = null; Token colon = null; if (Peek(1) == TokenType.Colon) { name = ParseIdent(); colon = ParseToken(TokenType.Colon); } AstNode type = ParseRuleInternal(RuleType.QualifiedIdent); Token theDo = ParseToken(TokenType.DoKeyword); AstNode statement = null; if (CanParseRule(RuleType.Statement)) statement = ParseRuleInternal(RuleType.Statement); Token semicolon = null; if (CanParseToken(TokenType.Semicolon)) semicolon = ParseToken(TokenType.Semicolon); return new ExceptionItemNode(on, name, colon, type, theDo, statement, semicolon); }); #endregion #region ExportsItem AddRule(RuleType.ExportsItem, TokenSets.Ident.LookAhead, delegate { AstNode name = ParseRuleInternal(RuleType.QualifiedIdent); ListNode<ExportsSpecifierNode> specifierList = ParseOptionalRuleList<ExportsSpecifierNode>(RuleType.ExportsSpecifier); return new ExportsItemNode(name, specifierList); }); #endregion #region ExportsSpecifier AddRule(RuleType.ExportsSpecifier, TokenSets.ExportsSpecifier.LookAhead, delegate { Token keyword = ParseToken(TokenSets.ExportsSpecifier); AstNode value = ParseRuleInternal(RuleType.Expression); return new ExportsSpecifierNode(keyword, value); }); #endregion #region ExportsStatement AddRule(RuleType.ExportsStatement, LookAhead(TokenType.ExportsKeyword), delegate { Token exports = ParseToken(TokenType.ExportsKeyword); ListNode<DelimitedItemNode<ExportsItemNode>> itemList = ParseDelimitedList<ExportsItemNode>( RuleType.ExportsItem, TokenType.Comma); Token semicolon = ParseToken(TokenType.Semicolon); return new ExportsStatementNode(exports, itemList, semicolon); }); #endregion #region Expression AddRule(RuleType.Expression, TokenSets.Expression.LookAhead, delegate { AstNode node = ParseRuleInternal(RuleType.SimpleExpression); while (CanParseRule(RuleType.RelOp)) { Token theOperator = (Token) ParseRuleInternal(RuleType.RelOp); AstNode right = ParseRuleInternal(RuleType.SimpleExpression); node = new BinaryOperationNode(node, theOperator, right); } return node; }); #endregion #region ExpressionList AddRule(RuleType.ExpressionList, TokenSets.Expression.LookAhead, delegate { return ParseDelimitedList<AstNode>(RuleType.Expression, TokenType.Comma); }); #endregion #region ExpressionOrAssignment AddRule(RuleType.ExpressionOrAssignment, TokenSets.Expression.LookAhead, delegate { AstNode node = ParseRuleInternal(RuleType.Expression); if (CanParseToken(TokenType.ColonEquals)) { Token theOperator = ParseToken(TokenType.ColonEquals); AstNode right = ParseRuleInternal(RuleType.Expression); return new BinaryOperationNode(node, theOperator, right); } else return node; }); #endregion #region ExpressionOrRange AddRule(RuleType.ExpressionOrRange, TokenSets.Expression.LookAhead, delegate { AstNode node = ParseRuleInternal(RuleType.SimpleExpression); if (CanParseToken(TokenType.DotDot)) { Token dotDot = ParseToken(TokenType.DotDot); AstNode right = ParseRuleInternal(RuleType.SimpleExpression); return new BinaryOperationNode(node, dotDot, right); } return node; }); #endregion #region ExpressionOrRangeList AddRule(RuleType.ExpressionOrRangeList, TokenSets.Expression.LookAhead, delegate { return ParseDelimitedList<AstNode>(RuleType.ExpressionOrRange, TokenType.Comma); }); #endregion #region ExtendedIdent AddRule(RuleType.ExtendedIdent, TokenSets.ExtendedIdent.LookAhead, delegate { Token token = ParseToken(TokenSets.ExtendedIdent); return token.WithTokenType(TokenType.Identifier); }); #endregion #region Factor AddRule(RuleType.Factor, TokenSets.Expression.LookAhead, delegate { if (CanParseRule(RuleType.UnaryOperator)) { Token theOperator = (Token) ParseRuleInternal(RuleType.UnaryOperator); AstNode operand = ParseRuleInternal(RuleType.Factor); return new UnaryOperationNode(theOperator, operand); } else return ParseRuleInternal(RuleType.Atom); }); #endregion #region FancyBlock AddRule(RuleType.FancyBlock, delegate { return CanParseRule(RuleType.Block) || CanParseRule(RuleType.ImplementationDecl); }, delegate { ListNode<AstNode> declList = ParseOptionalRuleList<AstNode>(RuleType.ImplementationDecl); AstNode block = ParseRuleInternal(RuleType.Block); return new FancyBlockNode(declList, block); }); #endregion #region FieldDecl AddRule(RuleType.FieldDecl, delegate { return CanParseRule(RuleType.IdentList) && !CanParseRule(RuleType.Visibility); }, delegate { ListNode<DelimitedItemNode<Token>> nameList = ParseIdentList(); Token colon = ParseToken(TokenType.Colon); AstNode type = ParseRuleInternal(RuleType.Type); ListNode<Token> portabilityDirectiveList = ParseTokenList(TokenSets.PortabilityDirective); Token semicolon = null; if (CanParseToken(TokenType.Semicolon)) semicolon = ParseToken(TokenType.Semicolon); return new FieldDeclNode(nameList, colon, type, portabilityDirectiveList, semicolon); }); #endregion #region FieldSection AddRule(RuleType.FieldSection, delegate { return (Peek(0) == TokenType.VarKeyword) || (Peek(0) == TokenType.ClassKeyword && Peek(1) == TokenType.VarKeyword) || CanParseRule(RuleType.FieldDecl); }, delegate { Token theClass = null; Token var = null; if (CanParseToken(TokenType.ClassKeyword)) { theClass = ParseToken(TokenType.ClassKeyword); var = ParseToken(TokenType.VarKeyword); } else if (CanParseToken(TokenType.VarKeyword)) var = ParseToken(TokenType.VarKeyword); ListNode<FieldDeclNode> fieldList = ParseOptionalRuleList<FieldDeclNode>(RuleType.FieldDecl); return new FieldSectionNode(theClass, var, fieldList); }); #endregion #region FileType AddRule(RuleType.FileType, LookAhead(TokenType.FileKeyword), delegate { Token file = ParseToken(TokenType.FileKeyword); Token of = null; AstNode type = null; if (CanParseToken(TokenType.OfKeyword)) { of = ParseToken(TokenType.OfKeyword); type = ParseRuleInternal(RuleType.QualifiedIdent); } return new FileTypeNode(file, of, type); }); #endregion #region ForStatement AddRule(RuleType.ForStatement, LookAhead(TokenType.ForKeyword), delegate { Token theFor = ParseToken(TokenType.ForKeyword); Token loopVariable = ParseIdent(); if (CanParseToken(TokenType.InKeyword)) { Token theIn = ParseToken(TokenType.InKeyword); AstNode expression = ParseRuleInternal(RuleType.Expression); Token theDo = ParseToken(TokenType.DoKeyword); AstNode statement = null; if (CanParseRule(RuleType.Statement)) statement = ParseRuleInternal(RuleType.Statement); return new ForInStatementNode(theFor, loopVariable, theIn, expression, theDo, statement); } else { Token colonEquals = ParseToken(TokenType.ColonEquals); AstNode startingValue = ParseRuleInternal(RuleType.Expression); Token direction = ParseToken(TokenSets.ForDirection); AstNode endingValue = ParseRuleInternal(RuleType.Expression); Token theDo = ParseToken(TokenType.DoKeyword); AstNode statement = null; if (CanParseRule(RuleType.Statement)) statement = ParseRuleInternal(RuleType.Statement); return new ForStatementNode(theFor, loopVariable, colonEquals, startingValue, direction, endingValue, theDo, statement); } }); #endregion #region Goal Alternator goalAlternator = new Alternator(); goalAlternator.AddRule(RuleType.Package); goalAlternator.AddRule(RuleType.Program); goalAlternator.AddRule(RuleType.Unit); AddRule(RuleType.Goal, goalAlternator.LookAhead, delegate { return goalAlternator.Execute(this); }); #endregion #region GotoStatement AddRule(RuleType.GotoStatement, LookAhead(TokenType.GotoKeyword), delegate { Token theGoto = ParseToken(TokenType.GotoKeyword); Token labelId = (Token) ParseRuleInternal(RuleType.LabelId); return new GotoStatementNode(theGoto, labelId); }); #endregion #region Ident AddRule(RuleType.Ident, TokenSets.Ident.LookAhead, delegate { Token token = ParseToken(TokenSets.Ident); return token.WithTokenType(TokenType.Identifier); }); #endregion #region IdentList AddRule(RuleType.IdentList, TokenSets.Ident.LookAhead, delegate { return ParseDelimitedList<Token>(RuleType.Ident, TokenType.Comma); }); #endregion #region IfStatement AddRule(RuleType.IfStatement, LookAhead(TokenType.IfKeyword), delegate { Token theIf = ParseToken(TokenType.IfKeyword); AstNode condition = ParseRuleInternal(RuleType.Expression); Token then = ParseToken(TokenType.ThenKeyword); AstNode thenStatement = null; if (CanParseRule(RuleType.Statement)) thenStatement = ParseRuleInternal(RuleType.Statement); Token theElse = null; AstNode elseStatement = null; if (CanParseToken(TokenType.ElseKeyword)) { theElse = ParseToken(TokenType.ElseKeyword); if (CanParseRule(RuleType.Statement)) elseStatement = ParseRuleInternal(RuleType.Statement); } return new IfStatementNode(theIf, condition, then, thenStatement, theElse, elseStatement); }); #endregion #region ImplementationDecl Alternator implementationDeclAlternator = new Alternator(); implementationDeclAlternator.AddRule(RuleType.AssemblyAttribute); implementationDeclAlternator.AddRule(RuleType.ConstSection); implementationDeclAlternator.AddRule(RuleType.ExportsStatement); implementationDeclAlternator.AddRule(RuleType.LabelDeclSection); implementationDeclAlternator.AddRule(RuleType.MethodImplementation); implementationDeclAlternator.AddRule(RuleType.TypeSection); implementationDeclAlternator.AddRule(RuleType.VarSection); AddRule(RuleType.ImplementationDecl, implementationDeclAlternator.LookAhead, delegate { return implementationDeclAlternator.Execute(this); }); #endregion #region ImplementationSection AddRule(RuleType.ImplementationSection, LookAhead(TokenType.ImplementationKeyword), delegate { Token implementation = ParseToken(TokenType.ImplementationKeyword); UsesClauseNode usesClause = null; if (CanParseRule(RuleType.UsesClause)) usesClause = (UsesClauseNode) ParseRuleInternal(RuleType.UsesClause); ListNode<AstNode> contents = ParseOptionalRuleList<AstNode>(RuleType.ImplementationDecl); return new UnitSectionNode(implementation, usesClause, contents); }); #endregion #region InitSection AddRule(RuleType.InitSection, TokenSets.InitSection.LookAhead, delegate { Token initializationHeader = null; ListNode<DelimitedItemNode<AstNode>> initializationStatements = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); Token finalizationHeader = null; ListNode<DelimitedItemNode<AstNode>> finalizationStatements = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); Token end = null; if (CanParseToken(TokenType.BeginKeyword)) { BlockNode block = (BlockNode) ParseRuleInternal(RuleType.Block); initializationHeader = block.BeginKeywordNode; initializationStatements = block.StatementListNode; end = block.EndKeywordNode; } else if (CanParseToken(TokenType.AsmKeyword)) { AssemblerStatementNode asm = (AssemblerStatementNode) ParseRuleInternal(RuleType.AssemblerStatement); DelimitedItemNode<AstNode> item = new DelimitedItemNode<AstNode>(asm, null); initializationStatements = new ListNode<DelimitedItemNode<AstNode>>( new DelimitedItemNode<AstNode>[] { item }); } else { if (CanParseToken(TokenType.InitializationKeyword)) { initializationHeader = ParseToken(TokenType.InitializationKeyword); initializationStatements = ParseOptionalStatementList(); if (CanParseToken(TokenType.FinalizationKeyword)) { finalizationHeader = ParseToken(TokenType.FinalizationKeyword); finalizationStatements = ParseOptionalStatementList(); } } end = ParseToken(TokenType.EndKeyword); } return new InitSectionNode(initializationHeader, initializationStatements, finalizationHeader, finalizationStatements, end); }); #endregion #region InterfaceDecl Alternator interfaceDeclAlternator = new Alternator(); interfaceDeclAlternator.AddRule(RuleType.ConstSection); interfaceDeclAlternator.AddRule(RuleType.TypeSection); interfaceDeclAlternator.AddRule(RuleType.VarSection); interfaceDeclAlternator.AddRule(RuleType.MethodHeading); AddRule(RuleType.InterfaceDecl, interfaceDeclAlternator.LookAhead, delegate { return interfaceDeclAlternator.Execute(this); }); #endregion #region InterfaceSection AddRule(RuleType.InterfaceSection, LookAhead(TokenType.InterfaceKeyword), delegate { Token theInterface = ParseToken(TokenType.InterfaceKeyword); UsesClauseNode usesClause = null; if (CanParseRule(RuleType.UsesClause)) usesClause = (UsesClauseNode) ParseRuleInternal(RuleType.UsesClause); ListNode<AstNode> contents = ParseOptionalRuleList<AstNode>(RuleType.InterfaceDecl); return new UnitSectionNode(theInterface, usesClause, contents); }); #endregion #region InterfaceType AddRule(RuleType.InterfaceType, TokenSets.InterfaceType.LookAhead, delegate { Token theInterface = ParseToken(TokenSets.InterfaceType); Token openParenthesis = null; AstNode baseInterface = null; Token closeParenthesis = null; if (CanParseToken(TokenType.OpenParenthesis)) { openParenthesis = ParseToken(TokenType.OpenParenthesis); baseInterface = ParseRuleInternal(RuleType.QualifiedIdent); closeParenthesis = ParseToken(TokenType.CloseParenthesis); } Token openBracket = null; AstNode guid = null; Token closeBracket = null; if (CanParseToken(TokenType.OpenBracket)) { openBracket = ParseToken(TokenType.OpenBracket); guid = ParseRuleInternal(RuleType.Expression); closeBracket = ParseToken(TokenType.CloseBracket); } ListNode<AstNode> methodAndPropertyList = ParseOptionalRuleList<AstNode>(RuleType.MethodOrProperty); Token end = ParseToken(TokenType.EndKeyword); return new InterfaceTypeNode(theInterface, openParenthesis, baseInterface, closeParenthesis, openBracket, guid, closeBracket, methodAndPropertyList, end); }); #endregion #region LabelDeclSection AddRule(RuleType.LabelDeclSection, LookAhead(TokenType.LabelKeyword), delegate { Token label = ParseToken(TokenType.LabelKeyword); ListNode<DelimitedItemNode<Token>> labelList = ParseDelimitedList<Token>(RuleType.LabelId, TokenType.Comma); Token semicolon = ParseToken(TokenType.Semicolon); return new LabelDeclSectionNode(label, labelList, semicolon); }); #endregion #region LabelId Alternator labelIdAlternator = new Alternator(); labelIdAlternator.AddToken(TokenType.Number); labelIdAlternator.AddRule(RuleType.Ident); AddRule(RuleType.LabelId, TokenSets.LabelId.LookAhead, delegate { return labelIdAlternator.Execute(this); }); #endregion #region MethodHeading AddRule(RuleType.MethodHeading, delegate { return (Peek(0) == TokenType.ClassKeyword && TokenSets.MethodType.Contains(Peek(1))) || CanParseToken(TokenSets.MethodType); }, delegate { Token theClass = null; if (CanParseToken(TokenType.ClassKeyword)) theClass = ParseToken(TokenType.ClassKeyword); Token methodType = ParseToken(TokenSets.MethodType); AstNode name = ParseRuleInternal(RuleType.QualifiedIdent); if (CanParseToken(TokenType.EqualSign)) { AstNode interfaceMethod = name; Token equalSign = ParseToken(TokenType.EqualSign); Token implementationMethod = ParseIdent(); Token semicolon = ParseToken(TokenType.Semicolon); return new MethodResolutionNode(methodType, interfaceMethod, equalSign, implementationMethod, semicolon); } else { Token openParenthesis = null; ListNode<DelimitedItemNode<ParameterNode>> parameterList = CreateEmptyListNode<DelimitedItemNode<ParameterNode>>(); Token closeParenthesis = null; if (CanParseToken(TokenType.OpenParenthesis)) { openParenthesis = ParseToken(TokenType.OpenParenthesis); if (CanParseRule(RuleType.Parameter)) { parameterList = ParseDelimitedList<ParameterNode>( RuleType.Parameter, TokenType.Semicolon); } closeParenthesis = ParseToken(TokenType.CloseParenthesis); } Token colon = null; AstNode returnType = null; if (CanParseToken(TokenType.Colon)) { colon = ParseToken(TokenType.Colon); returnType = ParseRuleInternal(RuleType.MethodReturnType); } ListNode<DirectiveNode> directiveList = ParseOptionalRuleList<DirectiveNode>(RuleType.Directive); Token semicolon = null; if (CanParseToken(TokenType.Semicolon)) semicolon = ParseToken(TokenType.Semicolon); return new MethodHeadingNode(theClass, methodType, name, openParenthesis, parameterList, closeParenthesis, colon, returnType, directiveList, semicolon); } }); #endregion #region MethodImplementation AddRule(RuleType.MethodImplementation, delegate { return CanParseRule(RuleType.MethodHeading); }, delegate { MethodHeadingNode methodHeading = (MethodHeadingNode) ParseRuleInternal(RuleType.MethodHeading); if (!methodHeading.RequiresBody) return methodHeading; else { FancyBlockNode fancyBlock = (FancyBlockNode) ParseRuleInternal(RuleType.FancyBlock); Token semicolon = ParseToken(TokenType.Semicolon); return new MethodImplementationNode(methodHeading, fancyBlock, semicolon); } }); #endregion #region MethodOrProperty Alternator methodOrPropertyAlternator = new Alternator(); methodOrPropertyAlternator.AddRule(RuleType.MethodHeading); methodOrPropertyAlternator.AddRule(RuleType.Property); AddRule(RuleType.MethodOrProperty, methodOrPropertyAlternator.LookAhead, delegate { return methodOrPropertyAlternator.Execute(this); }); #endregion #region MethodReturnType Alternator methodReturnTypeAlternator = new Alternator(); methodReturnTypeAlternator.AddToken(TokenType.StringKeyword); methodReturnTypeAlternator.AddRule(RuleType.QualifiedIdent); AddRule(RuleType.MethodReturnType, methodReturnTypeAlternator.LookAhead, delegate { return methodReturnTypeAlternator.Execute(this); }); #endregion #region MulOp AddTokenRule(RuleType.MulOp, TokenSets.MulOp); #endregion #region OpenArray Alternator openArrayAlternator = new Alternator(); openArrayAlternator.AddRule(RuleType.QualifiedIdent); openArrayAlternator.AddToken(TokenType.ConstKeyword); openArrayAlternator.AddToken(TokenType.FileKeyword); openArrayAlternator.AddToken(TokenType.StringKeyword); AddRule(RuleType.OpenArray, LookAhead(TokenType.ArrayKeyword), delegate { Token array = ParseToken(TokenType.ArrayKeyword); Token of = ParseToken(TokenType.OfKeyword); AstNode type = openArrayAlternator.Execute(this); return new OpenArrayNode(array, of, type); }); #endregion #region Package AddRule(RuleType.Package, LookAhead(TokenType.PackageSemikeyword), delegate { Token package = ParseToken(TokenType.PackageSemikeyword); AstNode name = ParseRuleInternal(RuleType.QualifiedIdent); Token semicolon = ParseToken(TokenType.Semicolon); RequiresClauseNode requiresClause = null; if (CanParseRule(RuleType.RequiresClause)) requiresClause = (RequiresClauseNode) ParseRuleInternal(RuleType.RequiresClause); UsesClauseNode containsClause = null; if (CanParseRule(RuleType.UsesClause)) containsClause = (UsesClauseNode) ParseRuleInternal(RuleType.UsesClause); ListNode<AttributeNode> attributeList = ParseOptionalRuleList<AttributeNode>(RuleType.AssemblyAttribute); Token end = ParseToken(TokenType.EndKeyword); Token dot = ParseToken(TokenType.Dot); return new PackageNode(package, name, semicolon, requiresClause, containsClause, attributeList, end, dot); }); #endregion #region PackedType AddRule(RuleType.PackedType, LookAhead(TokenType.PackedKeyword), delegate { Token packed = ParseToken(TokenType.PackedKeyword); AstNode type = ParseRuleInternal(RuleType.Type); return new PackedTypeNode(packed, type); }); #endregion #region Parameter AddRule(RuleType.Parameter, TokenSets.Parameter.LookAhead, delegate { Token modifier = null; if (CanParseToken(TokenSets.ParameterModifier)) modifier = ParseToken(TokenSets.ParameterModifier); ListNode<DelimitedItemNode<Token>> names = ParseIdentList(); Token colon = null; AstNode type = null; if (CanParseToken(TokenType.Colon)) { colon = ParseToken(TokenType.Colon); type = ParseRuleInternal(RuleType.ParameterType); } Token equalSign = null; AstNode defaultValue = null; if (CanParseToken(TokenType.EqualSign)) { equalSign = ParseToken(TokenType.EqualSign); defaultValue = ParseRuleInternal(RuleType.Expression); } return new ParameterNode(modifier, names, colon, type, equalSign, defaultValue); }); #endregion #region ParameterExpression AddRule(RuleType.ParameterExpression, delegate { return CanParseRule(RuleType.Expression); }, delegate { AstNode node = ParseRuleInternal(RuleType.Expression); if (CanParseToken(TokenType.Colon)) { Token sizeColon = ParseToken(TokenType.Colon); AstNode size = ParseRuleInternal(RuleType.Expression); Token precisionColon = null; AstNode precision = null; if (CanParseToken(TokenType.Colon)) { precisionColon = ParseToken(TokenType.Colon); precision = ParseRuleInternal(RuleType.Expression); } return new NumberFormatNode(node, sizeColon, size, precisionColon, precision); } else return node; }); #endregion #region ParameterType Alternator parameterTypeAlternator = new Alternator(); parameterTypeAlternator.AddRule(RuleType.QualifiedIdent); parameterTypeAlternator.AddRule(RuleType.OpenArray); parameterTypeAlternator.AddToken(TokenType.FileKeyword); parameterTypeAlternator.AddToken(TokenType.StringKeyword); AddRule(RuleType.ParameterType, parameterTypeAlternator.LookAhead, delegate { return parameterTypeAlternator.Execute(this); }); #endregion #region ParenthesizedExpression AddRule(RuleType.ParenthesizedExpression, LookAhead(TokenType.OpenParenthesis), delegate { Token openParenthesis = ParseToken(TokenType.OpenParenthesis); AstNode expression = ParseRuleInternal(RuleType.Expression); Token closeParenthesis = ParseToken(TokenType.CloseParenthesis); return new ParenthesizedExpressionNode(openParenthesis, expression, closeParenthesis); }); #endregion #region Particle Alternator particleAlternator = new Alternator(); particleAlternator.AddToken(TokenType.FileKeyword); particleAlternator.AddToken(TokenType.NilKeyword); particleAlternator.AddToken(TokenType.Number); particleAlternator.AddToken(TokenType.StringKeyword); particleAlternator.AddToken(TokenType.StringLiteral); particleAlternator.AddRule(RuleType.Ident); particleAlternator.AddRule(RuleType.ParenthesizedExpression); particleAlternator.AddRule(RuleType.SetLiteral); AddRule(RuleType.Particle, TokenSets.Particle.LookAhead, delegate { return particleAlternator.Execute(this); }); #endregion #region PointerType AddRule(RuleType.PointerType, LookAhead(TokenType.Caret), delegate { Token caret = ParseToken(TokenType.Caret); AstNode type = ParseRuleInternal(RuleType.Type); return new PointerTypeNode(caret, type); }); #endregion #region PortabilityDirective AddTokenRule(RuleType.PortabilityDirective, TokenSets.PortabilityDirective); #endregion #region ProcedureType AddRule(RuleType.ProcedureType, TokenSets.MethodType.LookAhead, delegate { Token methodType = ParseToken(TokenSets.MethodType); Token openParenthesis = null; ListNode<DelimitedItemNode<ParameterNode>> parameterList = CreateEmptyListNode<DelimitedItemNode<ParameterNode>>(); Token closeParenthesis = null; if (CanParseToken(TokenType.OpenParenthesis)) { openParenthesis = ParseToken(TokenType.OpenParenthesis); if (CanParseRule(RuleType.Parameter)) { parameterList = ParseDelimitedList<ParameterNode>( RuleType.Parameter, TokenType.Semicolon); } closeParenthesis = ParseToken(TokenType.CloseParenthesis); } Token colon = null; AstNode returnType = null; if (CanParseToken(TokenType.Colon)) { colon = ParseToken(TokenType.Colon); returnType = ParseRuleInternal(RuleType.MethodReturnType); } ListNode<DirectiveNode> firstDirectives = ParseOptionalRuleList<DirectiveNode>(RuleType.Directive); Token of = null; Token theObject = null; if (CanParseToken(TokenType.OfKeyword)) { of = ParseToken(TokenType.OfKeyword); theObject = ParseToken(TokenType.ObjectKeyword); } ListNode<DirectiveNode> secondDirectives = ParseOptionalRuleList<DirectiveNode>(RuleType.Directive); return new ProcedureTypeNode(methodType, openParenthesis, parameterList, closeParenthesis, colon, returnType, firstDirectives, of, theObject, secondDirectives); }); #endregion #region Program AddRule(RuleType.Program, TokenSets.Program.LookAhead, delegate { Token program = ParseToken(TokenSets.Program); Token name = ParseIdent(); Token noiseOpenParenthesis = null; ListNode<DelimitedItemNode<Token>> noiseContents = CreateEmptyListNode<DelimitedItemNode<Token>>(); Token noiseCloseParenthesis = null; if (CanParseToken(TokenType.OpenParenthesis)) { noiseOpenParenthesis = ParseToken(TokenType.OpenParenthesis); noiseContents = ParseDelimitedList<Token>(RuleType.Ident, TokenType.Comma); noiseCloseParenthesis = ParseToken(TokenType.CloseParenthesis); } Token semicolon = ParseToken(TokenType.Semicolon); UsesClauseNode usesClause = null; if (CanParseRule(RuleType.UsesClause)) usesClause = (UsesClauseNode) ParseRuleInternal(RuleType.UsesClause); ListNode<AstNode> declarationList = ParseOptionalRuleList<AstNode>(RuleType.ImplementationDecl); InitSectionNode initSection = (InitSectionNode) ParseRuleInternal(RuleType.InitSection); Token dot = ParseToken(TokenType.Dot); return new ProgramNode(program, name, noiseOpenParenthesis, noiseContents, noiseCloseParenthesis, semicolon, usesClause, declarationList, initSection, dot); }); #endregion #region Property AddRule(RuleType.Property, delegate { return (Peek(0) == TokenType.ClassKeyword && Peek(1) == TokenType.PropertyKeyword) || (Peek(0) == TokenType.PropertyKeyword); }, delegate { Token theClass = null; if (CanParseToken(TokenType.ClassKeyword)) theClass = ParseToken(TokenType.ClassKeyword); Token property = ParseToken(TokenType.PropertyKeyword); Token name = ParseIdent(); Token openBracket = null; ListNode<DelimitedItemNode<ParameterNode>> parameterList = CreateEmptyListNode<DelimitedItemNode<ParameterNode>>(); Token closeBracket = null; if (CanParseToken(TokenType.OpenBracket)) { openBracket = ParseToken(TokenType.OpenBracket); parameterList = ParseDelimitedList<ParameterNode>(RuleType.Parameter, TokenType.Semicolon); closeBracket = ParseToken(TokenType.CloseBracket); } Token colon = null; AstNode type = null; if (CanParseToken(TokenType.Colon)) { colon = ParseToken(TokenType.Colon); type = ParseRuleInternal(RuleType.MethodReturnType); } ListNode<DirectiveNode> directiveList = ParseOptionalRuleList<DirectiveNode>(RuleType.PropertyDirective); Token semicolon = ParseToken(TokenType.Semicolon); return new PropertyNode(theClass, property, name, openBracket, parameterList, closeBracket, colon, type, directiveList, semicolon); }); #endregion #region PropertyDirective AddRule(RuleType.PropertyDirective, delegate { return CanParseToken(TokenSets.ParameterizedPropertyDirective) || CanParseToken(TokenSets.ParameterlessPropertyDirective) || (Peek(0) == TokenType.Semicolon && Peek(1) == TokenType.DefaultSemikeyword); }, delegate { Token semicolon = null; Token directive; AstNode value = null; ListNode<AstNode> data = _emptyList; if (CanParseToken(TokenType.Semicolon)) { semicolon = ParseToken(TokenType.Semicolon); directive = ParseToken(TokenType.DefaultSemikeyword); } else if (CanParseToken(TokenType.ImplementsSemikeyword)) { directive = ParseToken(TokenType.ImplementsSemikeyword); value = ParseDelimitedList<AstNode>(RuleType.QualifiedIdent, TokenType.Comma); } else if (CanParseToken(TokenSets.ParameterizedPropertyDirective)) { directive = ParseToken(TokenSets.ParameterizedPropertyDirective); value = ParseRuleInternal(RuleType.Expression); } else directive = ParseToken(TokenSets.ParameterlessPropertyDirective); return new DirectiveNode(semicolon, directive, value, data); }); #endregion #region QualifiedIdent AddRule(RuleType.QualifiedIdent, TokenSets.Ident.LookAhead, delegate { AstNode node = ParseIdent(); while (CanParseToken(TokenType.Dot)) { Token dot = ParseToken(TokenType.Dot); AstNode right = ParseRuleInternal(RuleType.ExtendedIdent); node = new BinaryOperationNode(node, dot, right); } return node; }); #endregion #region RaiseStatement AddRule(RuleType.RaiseStatement, LookAhead(TokenType.RaiseKeyword), delegate { Token raise = ParseToken(TokenType.RaiseKeyword); AstNode exception = null; Token at = null; AstNode address = null; if (CanParseRule(RuleType.Expression)) { exception = ParseRuleInternal(RuleType.Expression); if (CanParseToken(TokenType.AtSemikeyword)) { at = ParseToken(TokenType.AtSemikeyword); address = ParseRuleInternal(RuleType.Expression); } } return new RaiseStatementNode(raise, exception, at, address); }); #endregion #region RecordFieldConstant AddRule(RuleType.RecordFieldConstant, delegate { return CanParseRule(RuleType.QualifiedIdent); }, delegate { AstNode name = ParseRuleInternal(RuleType.QualifiedIdent); Token colon = ParseToken(TokenType.Colon); AstNode value = ParseRuleInternal(RuleType.TypedConstant); return new RecordFieldConstantNode(name, colon, value); }); #endregion #region RecordHelperType AddRule(RuleType.RecordHelperType, delegate { return Peek(0) == TokenType.RecordKeyword && Peek(1) == TokenType.HelperSemikeyword; }, delegate { Token typeKeyword = ParseToken(TokenType.RecordKeyword); Token helper = ParseToken(TokenType.HelperSemikeyword); // Record helpers cannot have base helper types, so these three are always null const Token openParenthesis = null; const AstNode baseHelperType = null; const Token closeParenthesis = null; Token theFor = ParseToken(TokenType.ForKeyword); AstNode type = ParseRuleInternal(RuleType.QualifiedIdent); ListNode<VisibilitySectionNode> contents = ParseOptionalRuleList<VisibilitySectionNode>(RuleType.VisibilitySection); Token end = ParseToken(TokenType.EndKeyword); return new TypeHelperNode(typeKeyword, helper, openParenthesis, baseHelperType, closeParenthesis, theFor, type, contents, end); }); #endregion #region RecordType AddRule(RuleType.RecordType, LookAhead(TokenType.RecordKeyword), delegate { Token record = ParseToken(TokenType.RecordKeyword); ListNode<VisibilitySectionNode> contents = ParseOptionalRuleList<VisibilitySectionNode>(RuleType.VisibilitySection); VariantSectionNode variantSection = null; if (CanParseRule(RuleType.VariantSection)) variantSection = (VariantSectionNode) ParseRuleInternal(RuleType.VariantSection); Token end = ParseToken(TokenType.EndKeyword); return new RecordTypeNode(record, contents, variantSection, end); }); #endregion #region RelOp AddTokenRule(RuleType.RelOp, TokenSets.RelOp); #endregion #region RepeatStatement AddRule(RuleType.RepeatStatement, LookAhead(TokenType.RepeatKeyword), delegate { Token repeat = ParseToken(TokenType.RepeatKeyword); ListNode<DelimitedItemNode<AstNode>> statementList = ParseOptionalStatementList(); Token until = ParseToken(TokenType.UntilKeyword); AstNode condition = ParseRuleInternal(RuleType.Expression); return new RepeatStatementNode(repeat, statementList, until, condition); }); #endregion #region RequiresClause AddRule(RuleType.RequiresClause, LookAhead(TokenType.RequiresSemikeyword), delegate { Token requires = ParseToken(TokenType.RequiresSemikeyword); ListNode<DelimitedItemNode<AstNode>> packageList = ParseDelimitedList<AstNode>(RuleType.QualifiedIdent, TokenType.Comma); Token semicolon = ParseToken(TokenType.Semicolon); return new RequiresClauseNode(requires, packageList, semicolon); }); #endregion #region SetLiteral AddRule(RuleType.SetLiteral, LookAhead(TokenType.OpenBracket), delegate { Token openBracket = ParseToken(TokenType.OpenBracket); ListNode<DelimitedItemNode<AstNode>> itemList; if (CanParseRule(RuleType.ExpressionOrRangeList)) itemList = (ListNode<DelimitedItemNode<AstNode>>) ParseRuleInternal(RuleType.ExpressionOrRangeList); else itemList = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); Token closeBracket = ParseToken(TokenType.CloseBracket); return new SetLiteralNode(openBracket, itemList, closeBracket); }); #endregion #region SetType AddRule(RuleType.SetType, LookAhead(TokenType.SetKeyword), delegate { Token set = ParseToken(TokenType.SetKeyword); Token of = ParseToken(TokenType.OfKeyword); AstNode type = ParseRuleInternal(RuleType.Type); return new SetOfNode(set, of, type); }); #endregion #region SimpleExpression AddRule(RuleType.SimpleExpression, TokenSets.Expression.LookAhead, delegate { AstNode node = ParseRuleInternal(RuleType.Term); while (CanParseRule(RuleType.AddOp)) { Token theOperator = (Token) ParseRuleInternal(RuleType.AddOp); AstNode right = ParseRuleInternal(RuleType.Term); node = new BinaryOperationNode(node, theOperator, right); } return node; }); #endregion #region SimpleStatement Alternator simpleExpressionAlternator = new Alternator(); simpleExpressionAlternator.AddRule(RuleType.BareInherited); simpleExpressionAlternator.AddRule(RuleType.Block); simpleExpressionAlternator.AddRule(RuleType.CaseStatement); simpleExpressionAlternator.AddRule(RuleType.ExpressionOrAssignment); simpleExpressionAlternator.AddRule(RuleType.ForStatement); simpleExpressionAlternator.AddRule(RuleType.GotoStatement); simpleExpressionAlternator.AddRule(RuleType.IfStatement); simpleExpressionAlternator.AddRule(RuleType.RaiseStatement); simpleExpressionAlternator.AddRule(RuleType.RepeatStatement); simpleExpressionAlternator.AddRule(RuleType.TryStatement); simpleExpressionAlternator.AddRule(RuleType.WhileStatement); simpleExpressionAlternator.AddRule(RuleType.WithStatement); AddRule(RuleType.SimpleStatement, simpleExpressionAlternator.LookAhead, delegate { return simpleExpressionAlternator.Execute(this); }); #endregion #region Statement AddRule(RuleType.Statement, delegate { return CanParseRule(RuleType.SimpleStatement); }, delegate { if (TokenSets.LabelId.Contains(Peek(0)) && Peek(1) == TokenType.Colon) { Token label = (Token) ParseRuleInternal(RuleType.LabelId); Token colon = ParseToken(TokenType.Colon); AstNode statement = null; if (CanParseRule(RuleType.SimpleStatement)) statement = ParseRuleInternal(RuleType.SimpleStatement); return new LabeledStatementNode(label, colon, statement); } else return ParseRuleInternal(RuleType.SimpleStatement); }); #endregion #region StatementList AddRule(RuleType.StatementList, delegate { return CanParseRule(RuleType.Statement) || CanParseToken(TokenType.Semicolon); }, delegate { List<DelimitedItemNode<AstNode>> items = new List<DelimitedItemNode<AstNode>>(); while (CanParseRule(RuleType.Statement) || CanParseToken(TokenType.Semicolon)) { AstNode item = null; if (CanParseRule(RuleType.Statement)) item = ParseRuleInternal(RuleType.Statement); Token delimiter = null; if (CanParseToken(TokenType.Semicolon)) delimiter = ParseToken(TokenType.Semicolon); items.Add(new DelimitedItemNode<AstNode>(item, delimiter)); } return new ListNode<DelimitedItemNode<AstNode>>(items); }); #endregion #region StringType AddRule(RuleType.StringType, LookAhead(TokenType.StringKeyword), delegate { Token theString = ParseToken(TokenType.StringKeyword); if (CanParseToken(TokenType.OpenBracket)) { Token openBracket = ParseToken(TokenType.OpenBracket); AstNode length = ParseRuleInternal(RuleType.Expression); Token closeBracket = ParseToken(TokenType.CloseBracket); return new StringOfLengthNode(theString, openBracket, length, closeBracket); } else return theString; }); #endregion #region Term AddRule(RuleType.Term, TokenSets.Expression.LookAhead, delegate { AstNode node = ParseRuleInternal(RuleType.Factor); while (CanParseRule(RuleType.MulOp)) { Token theOperator = (Token) ParseRuleInternal(RuleType.MulOp); AstNode right = ParseRuleInternal(RuleType.Factor); node = new BinaryOperationNode(node, theOperator, right); } return node; }); #endregion #region TryStatement AddRule(RuleType.TryStatement, LookAhead(TokenType.TryKeyword), delegate { Token theTry = ParseToken(TokenType.TryKeyword); ListNode<DelimitedItemNode<AstNode>> tryStatements = ParseOptionalStatementList(); if (CanParseToken(TokenType.ExceptKeyword)) { Token except = ParseToken(TokenType.ExceptKeyword); ListNode<ExceptionItemNode> exceptionItemList = CreateEmptyListNode<ExceptionItemNode>(); Token theElse = null; ListNode<DelimitedItemNode<AstNode>> elseStatements = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); if (CanParseRule(RuleType.ExceptionItem) || CanParseToken(TokenType.ElseKeyword)) { if (CanParseRule(RuleType.ExceptionItem)) exceptionItemList = ParseRequiredRuleList<ExceptionItemNode>(RuleType.ExceptionItem); if (CanParseToken(TokenType.ElseKeyword)) { theElse = ParseToken(TokenType.ElseKeyword); elseStatements = ParseOptionalStatementList(); } } else elseStatements = ParseOptionalStatementList(); Token end = ParseToken(TokenType.EndKeyword); return new TryExceptNode(theTry, tryStatements, except, exceptionItemList, theElse, elseStatements, end); } else { Token theFinally = ParseToken(TokenType.FinallyKeyword); ListNode<DelimitedItemNode<AstNode>> finallyStatements = ParseOptionalStatementList(); Token end = ParseToken(TokenType.EndKeyword); return new TryFinallyNode(theTry, tryStatements, theFinally, finallyStatements, end); } }); #endregion #region Type Alternator typeAlternator = new Alternator(); typeAlternator.AddRule(RuleType.FileType); typeAlternator.AddRule(RuleType.StringType); typeAlternator.AddRule(RuleType.ArrayType); typeAlternator.AddRule(RuleType.ClassHelperType); typeAlternator.AddRule(RuleType.ClassOfType); typeAlternator.AddRule(RuleType.ClassType); typeAlternator.AddRule(RuleType.EnumeratedType); typeAlternator.AddRule(RuleType.ExpressionOrRange); typeAlternator.AddRule(RuleType.InterfaceType); typeAlternator.AddRule(RuleType.PackedType); typeAlternator.AddRule(RuleType.PointerType); typeAlternator.AddRule(RuleType.ProcedureType); typeAlternator.AddRule(RuleType.RecordHelperType); typeAlternator.AddRule(RuleType.RecordType); typeAlternator.AddRule(RuleType.SetType); AddRule(RuleType.Type, typeAlternator.LookAhead, delegate { return typeAlternator.Execute(this); }); #endregion #region TypedConstant AddRule(RuleType.TypedConstant, TokenSets.Expression.LookAhead, delegate { IFrame originalFrame = _nextFrame; try { return ParseRuleInternal(RuleType.Expression); } catch (ParseException) { _nextFrame = originalFrame; } Token openParenthesis; ListNode<DelimitedItemNode<AstNode>> itemList; Token closeParenthesis; try { openParenthesis = ParseToken(TokenType.OpenParenthesis); itemList = ParseDelimitedList<AstNode>(RuleType.TypedConstant, TokenType.Comma); closeParenthesis = ParseToken(TokenType.CloseParenthesis); } catch (ParseException) { _nextFrame = originalFrame; openParenthesis = ParseToken(TokenType.OpenParenthesis); if (!CanParseToken(TokenType.CloseParenthesis)) itemList = ParseDelimitedList<AstNode>(RuleType.RecordFieldConstant, TokenType.Semicolon); else itemList = CreateEmptyListNode<DelimitedItemNode<AstNode>>(); closeParenthesis = ParseToken(TokenType.CloseParenthesis); } return new ConstantListNode(openParenthesis, itemList, closeParenthesis); }); #endregion #region TypeDecl AddRule(RuleType.TypeDecl, TokenSets.Ident.LookAhead, delegate { Token name = ParseIdent(); Token equalSign = ParseToken(TokenType.EqualSign); if (TokenSets.ForwardableType.Contains(Peek(0)) && Peek(1) == TokenType.Semicolon) { Token type = ParseToken(TokenSets.ForwardableType); Token semicolon = ParseToken(TokenType.Semicolon); return new TypeForwardDeclarationNode(name, equalSign, type, semicolon); } else { Token typeKeyword = TryParseToken(TokenType.TypeKeyword); AstNode type = ParseRuleInternal(RuleType.Type); ListNode<Token> portabilityDirectiveList = ParseOptionalRuleList<Token>(RuleType.PortabilityDirective); Token semicolon = ParseToken(TokenType.Semicolon); return new TypeDeclNode(name, equalSign, typeKeyword, type, portabilityDirectiveList, semicolon); } }); #endregion #region TypeSection AddRule(RuleType.TypeSection, LookAhead(TokenType.TypeKeyword), delegate { Token type = ParseToken(TokenType.TypeKeyword); ListNode<AstNode> typeList = ParseRequiredRuleList<AstNode>(RuleType.TypeDecl); return new TypeSectionNode(type, typeList); }); #endregion #region UnaryOperator AddTokenRule(RuleType.UnaryOperator, TokenSets.UnaryOperator); #endregion #region Unit AddRule(RuleType.Unit, LookAhead(TokenType.UnitKeyword), delegate { Token unit = ParseToken(TokenType.UnitKeyword); Token unitName = ParseIdent(); ListNode<Token> portabilityDirectives = ParseTokenList(TokenSets.PortabilityDirective); Token semicolon = ParseToken(TokenType.Semicolon); UnitSectionNode interfaceSection = (UnitSectionNode) ParseRuleInternal(RuleType.InterfaceSection); UnitSectionNode implementationSection = (UnitSectionNode) ParseRuleInternal(RuleType.ImplementationSection); InitSectionNode initSection = (InitSectionNode) ParseRuleInternal(RuleType.InitSection); Token dot = ParseToken(TokenType.Dot); return new UnitNode(unit, unitName, portabilityDirectives, semicolon, interfaceSection, implementationSection, initSection, dot); }); #endregion #region UsedUnit AddRule(RuleType.UsedUnit, TokenSets.Ident.LookAhead, delegate { AstNode name = ParseRuleInternal(RuleType.QualifiedIdent); Token theIn = null; Token fileName = null; if (CanParseToken(TokenType.InKeyword)) { theIn = ParseToken(TokenType.InKeyword); fileName = ParseToken(TokenType.StringLiteral); } return new UsedUnitNode(name, theIn, fileName); }); #endregion #region UsesClause AddRule(RuleType.UsesClause, TokenSets.Uses.LookAhead, delegate { Token uses = ParseToken(TokenSets.Uses); ListNode<DelimitedItemNode<UsedUnitNode>> unitList = ParseDelimitedList<UsedUnitNode>(RuleType.UsedUnit, TokenType.Comma); Token semicolon = ParseToken(TokenType.Semicolon); return new UsesClauseNode(uses, unitList, semicolon); }); #endregion #region VarDecl AddRule(RuleType.VarDecl, TokenSets.Ident.LookAhead, delegate { ListNode<DelimitedItemNode<Token>> names = ParseDelimitedList<Token>(RuleType.Ident, TokenType.Comma); Token colon = ParseToken(TokenType.Colon); AstNode type = ParseRuleInternal(RuleType.Type); ListNode<Token> firstPortabilityDirectives = ParseOptionalRuleList<Token>(RuleType.PortabilityDirective); Token absolute = null; AstNode absoluteAddress = null; Token equalSign = null; AstNode value = null; if (CanParseToken(TokenType.AbsoluteSemikeyword)) { absolute = ParseToken(TokenType.AbsoluteSemikeyword); absoluteAddress = ParseRuleInternal(RuleType.Expression); } else if (CanParseToken(TokenType.EqualSign)) { equalSign = ParseToken(TokenType.EqualSign); value = ParseRuleInternal(RuleType.TypedConstant); } ListNode<Token> secondPortabilityDirectives = ParseOptionalRuleList<Token>(RuleType.PortabilityDirective); Token semicolon = ParseToken(TokenType.Semicolon); return new VarDeclNode(names, colon, type, firstPortabilityDirectives, absolute, absoluteAddress, equalSign, value, secondPortabilityDirectives, semicolon); }); #endregion #region VariantGroup AddRule(RuleType.VariantGroup, delegate { return CanParseRule(RuleType.ExpressionList); }, delegate { ListNode<DelimitedItemNode<AstNode>> valueList = ParseDelimitedList<AstNode>(RuleType.Expression, TokenType.Comma); Token colon = ParseToken(TokenType.Colon); Token openParenthesis = ParseToken(TokenType.OpenParenthesis); ListNode<FieldDeclNode> fieldDeclList = ParseOptionalRuleList<FieldDeclNode>(RuleType.FieldDecl); VariantSectionNode variantSection = null; if (CanParseRule(RuleType.VariantSection)) variantSection = (VariantSectionNode) ParseRuleInternal(RuleType.VariantSection); Token closeParenthesis = ParseToken(TokenType.CloseParenthesis); Token semicolon = null; if (CanParseToken(TokenType.Semicolon)) semicolon = ParseToken(TokenType.Semicolon); return new VariantGroupNode(valueList, colon, openParenthesis, fieldDeclList, variantSection, closeParenthesis, semicolon); }); #endregion #region VariantSection AddRule(RuleType.VariantSection, LookAhead(TokenType.CaseKeyword), delegate { Token theCase = ParseToken(TokenType.CaseKeyword); Token name = null; Token colon = null; if (Peek(1) == TokenType.Colon) { name = ParseIdent(); colon = ParseToken(TokenType.Colon); } AstNode type = ParseRuleInternal(RuleType.QualifiedIdent); Token of = ParseToken(TokenType.OfKeyword); ListNode<VariantGroupNode> variantGroupList = ParseRequiredRuleList<VariantGroupNode>(RuleType.VariantGroup); return new VariantSectionNode(theCase, name, colon, type, of, variantGroupList); }); #endregion #region VarSection AddRule(RuleType.VarSection, TokenSets.VarHeader.LookAhead, delegate { Token var = ParseToken(TokenSets.VarHeader); ListNode<VarDeclNode> varList = ParseRequiredRuleList<VarDeclNode>(RuleType.VarDecl); return new VarSectionNode(var, varList); }); #endregion #region Visibility AddRule(RuleType.Visibility, TokenSets.Visibility.LookAhead, delegate { Token strict = null; if (CanParseToken(TokenType.StrictSemikeyword)) strict = ParseToken(TokenType.StrictSemikeyword); Token visibility = ParseToken(TokenSets.VisibilitySingleWord); return new VisibilityNode(strict, visibility); }); #endregion #region VisibilitySection AddRule(RuleType.VisibilitySection, delegate { return CanParseRule(RuleType.Visibility) || CanParseRule(RuleType.VisibilitySectionContent); }, delegate { VisibilityNode visibility = null; if (CanParseRule(RuleType.Visibility)) visibility = (VisibilityNode) ParseRuleInternal(RuleType.Visibility); ListNode<AstNode> contents = ParseOptionalRuleList<AstNode>(RuleType.VisibilitySectionContent); return new VisibilitySectionNode(visibility, contents); }); #endregion #region VisibilitySectionContent Alternator visibilitySectionContentAlternator = new Alternator(); visibilitySectionContentAlternator.AddRule(RuleType.FieldSection); visibilitySectionContentAlternator.AddRule(RuleType.MethodOrProperty); visibilitySectionContentAlternator.AddRule(RuleType.ConstSection); visibilitySectionContentAlternator.AddRule(RuleType.TypeSection); AddRule(RuleType.VisibilitySectionContent, visibilitySectionContentAlternator.LookAhead, delegate { return visibilitySectionContentAlternator.Execute(this); }); #endregion #region WhileStatement AddRule(RuleType.WhileStatement, LookAhead(TokenType.WhileKeyword), delegate { Token theWhile = ParseToken(TokenType.WhileKeyword); AstNode condition = ParseRuleInternal(RuleType.Expression); Token theDo = ParseToken(TokenType.DoKeyword); AstNode statement = null; if (CanParseRule(RuleType.Statement)) statement = ParseRuleInternal(RuleType.Statement); return new WhileStatementNode(theWhile, condition, theDo, statement); }); #endregion #region WithStatement AddRule(RuleType.WithStatement, LookAhead(TokenType.WithKeyword), delegate { Token with = ParseToken(TokenType.WithKeyword); ListNode<DelimitedItemNode<AstNode>> expressionList = ParseDelimitedList<AstNode>(RuleType.Expression, TokenType.Comma); Token theDo = ParseToken(TokenType.DoKeyword); AstNode statement = null; if (CanParseRule(RuleType.Statement)) statement = ParseRuleInternal(RuleType.Statement); return new WithStatementNode(with, expressionList, theDo, statement); }); #endregion } private static IFrame FrameFromTokens(IEnumerable<Token> tokens) { IFrame firstFrame = new EofFrame(new Location("", "", 0)); IFrame previousFrame = null; foreach (Token token in tokens) { IFrame frame = new Frame(token); if (previousFrame != null) previousFrame.Next = frame; else firstFrame = frame; previousFrame = frame; } return firstFrame; } public static Parser FromFrame(IFrame frame) { return new Parser(frame); } public static Parser FromText(string text, string fileName, CompilerDefines compilerDefines, IFileLoader fileLoader) { Lexer lexer = new Lexer(text, fileName); TokenFilter filter = new TokenFilter(lexer.Tokens, compilerDefines, fileLoader); return FromTokens(filter.Tokens); } private static Parser FromTokens(IEnumerable<Token> tokens) { return FromFrame(FrameFromTokens(tokens)); } public bool AtEof { get { return _nextFrame.IsEof; } } private void AddRule(RuleType ruleType, Predicate<Parser> lookAhead, RuleDelegate evaluate) { _rules[(int) ruleType] = new Rule(this, ruleType, lookAhead, evaluate); } private void AddTokenRule(RuleType ruleType, ITokenSet tokenSet) { AddRule(ruleType, delegate { return CanParseToken(tokenSet); }, delegate { return ParseToken(tokenSet); }); } public bool CanParseRule(RuleType ruleType) { return _rules[(int) ruleType].CanParse(); } public bool CanParseToken(ITokenSet tokenSet) { return tokenSet.Contains(Peek(0)); } private bool CanParseToken(TokenType tokenType) { return Peek(0) == tokenType; } private ListNode<T> CreateEmptyListNode<T>() where T : AstNode { return new ListNode<T>(new List<T>().AsReadOnly()); } public ParseException Failure(string expected) { return new ParseException("Expected " + expected + " but was " + _nextFrame.DisplayName, _nextFrame.Location); } private Predicate<Parser> LookAhead(TokenType tokenType) { return delegate { return CanParseToken(tokenType); }; } private void MoveNext() { _nextFrame = _nextFrame.Next; } private ListNode<DelimitedItemNode<T>> ParseDelimitedList<T>(RuleType itemRule, TokenType delimiterType) where T : AstNode { List<DelimitedItemNode<T>> items = new List<DelimitedItemNode<T>>(); do { T item = (T) ParseRuleInternal(itemRule); Token delimiter = null; if (CanParseToken(delimiterType)) delimiter = ParseToken(delimiterType); items.Add(new DelimitedItemNode<T>(item, delimiter)); } while (CanParseRule(itemRule)); return new ListNode<DelimitedItemNode<T>>(items); } private Token ParseIdent() { return (Token) ParseRuleInternal(RuleType.Ident); } private ListNode<DelimitedItemNode<Token>> ParseIdentList() { return (ListNode<DelimitedItemNode<Token>>) ParseRuleInternal(RuleType.IdentList); } private ListNode<T> ParseOptionalRuleList<T>(RuleType ruleType) where T : AstNode { List<T> items = new List<T>(); while (CanParseRule(ruleType)) items.Add((T) ParseRuleInternal(ruleType)); return new ListNode<T>(items); } private ListNode<DelimitedItemNode<AstNode>> ParseOptionalStatementList() { if (CanParseRule(RuleType.StatementList)) return ParseRequiredStatementList(); else return CreateEmptyListNode<DelimitedItemNode<AstNode>>(); } private ListNode<T> ParseRequiredRuleList<T>(RuleType ruleType) where T : AstNode { List<T> items = new List<T>(); do { items.Add((T) ParseRuleInternal(ruleType)); } while (CanParseRule(ruleType)); return new ListNode<T>(items); } private ListNode<DelimitedItemNode<AstNode>> ParseRequiredStatementList() { return (ListNode<DelimitedItemNode<AstNode>>) ParseRuleInternal(RuleType.StatementList); } public AstNode ParseRule(RuleType ruleType) { AstNode result = ParseRuleInternal(ruleType); result.BuildParentReferences(null); return result; } private AstNode ParseRuleInternal(RuleType ruleType) { return _rules[(int) ruleType].Execute(); } public Token ParseToken(ITokenSet tokenSet) { Token result = _nextFrame.ParseToken(tokenSet); _nextFrame = _nextFrame.Next; return result; } private Token ParseToken(TokenType tokenType) { return ParseToken(new SingleTokenTokenSet(tokenType)); } private ListNode<Token> ParseTokenList(ITokenSet tokenSet) { List<Token> nodes = new List<Token>(); while (CanParseToken(tokenSet)) nodes.Add(ParseToken(tokenSet)); return new ListNode<Token>(nodes); } private TokenType Peek(int offset) { IFrame frame = _nextFrame; while (offset > 0) { frame = frame.Next; --offset; } return frame.TokenType; } private Token TryParseToken(TokenType tokenType) { if (CanParseToken(tokenType)) return ParseToken(tokenType); else return null; } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Tossit.Core; namespace Tossit.RabbitMQ { /// <summary> /// RabbitMQ message queue implementation. /// </summary> public class RabbitMQMessageQueue : IMessageQueue { /// <summary> /// Main exchange name constant. /// </summary> private const string MAIN_EXCHANGE_NAME = "tossit.exchange.main"; /// <summary> /// Main retry exchange name constant. /// </summary> private const string MAIN_RETRY_EXCHANGE_NAME = "tossit.exchange.main.retry"; /// <summary> /// Retry queue name constant. /// </summary> private const string RETRY_QUEUE_NAME_SUFFIX = "retry"; /// <summary> /// ConnectionWrapper field. /// </summary> private readonly IConnectionWrapper _connectionWrapper; /// <summary> /// JsonConverter field. /// </summary> private readonly IJsonConverter _jsonConverter; /// <summary> /// ChannelFactory field. /// </summary> private readonly IChannelFactory _channelFactory; /// <summary> /// EventingBasicConsumerImpl field. /// </summary> private readonly IEventingBasicConsumerImpl _eventingBasicConsumerImpl; /// <summary> /// SendOptions field. /// </summary> private readonly IOptions<SendOptions> _sendOptions; /// <summary> /// Logger field. /// </summary> private readonly ILogger<RabbitMQMessageQueue> _logger; /// <summary> /// Ctor /// </summary> /// <param name="connectionWrapper">IConnectionWrapper</param> /// <param name="jsonConverter">IJsonConverter</param> /// <param name="channelFactory">IChannelFactory</param> /// <param name="eventingBasicConsumerImpl">IEventingBasicConsumerImpl</param> /// <param name="sendOptions">IOptions{SendOptions}</param> /// <param name="logger">ILogger{RabbitMQMessageQueue}</param> public RabbitMQMessageQueue( IConnectionWrapper connectionWrapper, IJsonConverter jsonConverter, IChannelFactory channelFactory, IEventingBasicConsumerImpl eventingBasicConsumerImpl, IOptions<SendOptions> sendOptions, ILogger<RabbitMQMessageQueue> logger) { _connectionWrapper = connectionWrapper; _jsonConverter = jsonConverter; _channelFactory = channelFactory; _eventingBasicConsumerImpl = eventingBasicConsumerImpl; _sendOptions = sendOptions; _logger = logger; } /// <summary> /// Send to queue. /// </summary> /// <param name="name">Name of queue or whatever using to describing work/job/event. Same as Receive method's name.</param> /// <param name="message">Message string to sends to queue.</param> /// <returns>Returns true if data send completed successfully, otherwise returns false.</returns> /// <exception cref="ArgumentNullException">Throws when name or message is null.</exception> public bool Send(string name, string message) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(message)) throw new ArgumentNullException(nameof(message)); // Create new channel for each dispatch. using (var channel = _connectionWrapper.ProducerConnection.CreateModel()) { // Prepare channel to send messages. var queueName = name; var exchangeName = this.PrepareChannel(channel, queueName); // Enable publisher confirms. if (_sendOptions.Value.ConfirmReceiptIsActive) { channel.ConfirmSelect(); } var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); // Set message as persistent. properties.Persistent = true; // Publish message. channel.BasicPublish(exchange: exchangeName, routingKey: queueName, basicProperties: properties, body: body); // Wait form ack from worker. if (_sendOptions.Value.ConfirmReceiptIsActive) { channel.WaitForConfirmsOrDie(TimeSpan.FromSeconds(_sendOptions.Value.ConfirmReceiptTimeoutSeconds)); } } _logger.LogInformation($"Message sent to {name}."); return true; } /// <summary> /// Receive messages from message queue. /// This method will register the given function to consume queue. /// </summary> /// <param name="name">Name of queue or whatever using to describing work/job/event. Same as Send method's name.</param> /// <param name="func">Receiver function.</param> /// <returns>Returns true if receiver method registered successfully, otherwise returns false.</returns> /// <exception cref="ArgumentNullException">Throws when name or func is null.</exception> public bool Receive(string name, Func<string, bool> func) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); if (func == null) throw new ArgumentNullException(nameof(func)); // Get new channel and connect receiver to it. _channelFactory.Channel(channel => { // Prepare channel to consume messages and retry. var queueName = name; // To consume. var exchangeName = PrepareChannel(channel, queueName); // To retry. PrepareChannelForRetry(channel, queueName, exchangeName); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); // Create new consumer. var consumer = _eventingBasicConsumerImpl.GetEventingBasicConsumer(channel); // Register to job received event. consumer.Received += (model, ea) => { this.Invoke(func, ea, channel, queueName); }; // Start consuming. channel.BasicConsume(queueName, autoAck: false, consumer: consumer); }); return true; } /// <summary> /// Declare main exchange, queue and bind. /// </summary> /// <param name="channel">Channel where the queue will be created.</param> /// <param name="queueName">The queue name to declare the queue.</param> /// <returns>Returns name of exchange that has binding for given queue name.</returns> private string PrepareChannel(IModel channel, string queueName) { // Declare main exchange and queue. channel.ExchangeDeclare(MAIN_EXCHANGE_NAME, ExchangeType.Direct, true, false); channel.QueueDeclare(queueName, durable: true, exclusive: false, autoDelete: false); // Bind queue to main exchange if did not binded before. try { channel.QueueBind(queueName, MAIN_EXCHANGE_NAME, routingKey: queueName); } catch (ArgumentException) { // Queue already binded before. // ignore. } return MAIN_EXCHANGE_NAME; } /// <summary> /// Declare exchange, queue and bind. To handle for failed messages to retry later. /// </summary> /// <param name="channel">Channel where the retry queue will be created.</param> /// <param name="queueName">The queue name to route failed messages after a time for process again.</param> /// <param name="mainExchangeName">Name of exhange that created for handle messages.</param> private void PrepareChannelForRetry(IModel channel, string queueName, string mainExchangeName) { // Declare retry exchange and queue for given queueName. channel.ExchangeDeclare(MAIN_RETRY_EXCHANGE_NAME, ExchangeType.Direct, true, false); // Arguments for dead letter exchange. It is required for retry functionality. var args = new Dictionary<string, object> { { "x-dead-letter-exchange", mainExchangeName }, { "x-message-ttl", _sendOptions.Value.WaitToRetrySeconds * 1000 } }; // Declare queue to store messages for waiting to retry. channel.QueueDeclare($"{queueName}.{RETRY_QUEUE_NAME_SUFFIX}", durable: true, exclusive: false, autoDelete: false, arguments: args); // Bind retry queue to retry exchange if did not binded before. try { channel.QueueBind($"{queueName}.{RETRY_QUEUE_NAME_SUFFIX}", MAIN_RETRY_EXCHANGE_NAME, routingKey: queueName); } catch (ArgumentException) { // Queue already binded before. // ignore. } } /// <summary> /// Invoke given consumer function. /// This method declared as an internal for test, because rabbitmq's event handler is not virtual. /// </summary> /// <param name="func">Function to invoke.</param> /// <param name="ea">RabbitMQ's BasicDeliverEventArgs.</param> /// <param name="channel">Channel to response ack or nack.</param> /// <param name="queueName">Queue name to route message to retry queue, if process failed.</param> internal void Invoke(Func<string, bool> func, BasicDeliverEventArgs ea, IModel channel, string queueName) { // Get message/body. var body = ea.Body != null ? Encoding.UTF8.GetString(ea.Body) : string.Empty; bool isSuccess; // Invoke! try { isSuccess = func(body); _logger.LogInformation($"Message received successfully from {queueName}."); } catch (Exception ex) { isSuccess = false; _logger.LogError(new EventId(), ex, $"Message could not received from {queueName}."); } // Success or not, doesn't matter. // Send ack everytime and publish message to dead letter exchange for trying again. channel.BasicAck(ea.DeliveryTag, multiple: false); if (!isSuccess) { var properties = channel.CreateBasicProperties(); // Set message as persistent. properties.Persistent = true; // Publish to retry queue to retry again after ttl. channel.BasicPublish(exchange: MAIN_RETRY_EXCHANGE_NAME, routingKey: queueName, basicProperties: properties, body: ea.Body); } } } }
// 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.Data; using System.Diagnostics; using System.Xml.XPath; #pragma warning disable 618 // ignore obsolete warning about XmlDataDocument namespace System.Xml { internal sealed class XPathNodePointer : IXmlDataVirtualNode { private readonly WeakReference _owner; // Owner of this pointer (an DataDocumentXPathNavigator). When the associated DataDocumentXPathNavigator (the owner) goes away, this XPathNodePointer can go away as well. private readonly XmlDataDocument _doc; private XmlNode _node; private DataColumn _column; private bool _fOnValue; internal XmlBoundElement _parentOfNS; internal static readonly int[] s_xmlNodeType_To_XpathNodeType_Map; internal const string StrReservedXmlns = "http://www.w3.org/2000/xmlns/"; internal const string StrReservedXml = "http://www.w3.org/XML/1998/namespace"; internal const string StrXmlNS = "xmlns"; private bool _bNeedFoliate; static XPathNodePointer() { #if DEBUG int max = 0, tempVal = 0; Array enumValues = Enum.GetValues(typeof(XmlNodeType)); for (int i = 0; i < enumValues.Length; i++) { tempVal = (int)enumValues.GetValue(i); if (tempVal > max) max = tempVal; } Debug.Assert(max == (int)XmlNodeType.XmlDeclaration); #endif s_xmlNodeType_To_XpathNodeType_Map = new int[20]; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.None)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Element)] = (int)XPathNodeType.Element; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Attribute)] = (int)XPathNodeType.Attribute; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Text)] = (int)XPathNodeType.Text; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.CDATA)] = (int)XPathNodeType.Text; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.EntityReference)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Entity)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.ProcessingInstruction)] = (int)XPathNodeType.ProcessingInstruction; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Comment)] = (int)XPathNodeType.Comment; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Document)] = (int)XPathNodeType.Root; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.DocumentType)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.DocumentFragment)] = (int)XPathNodeType.Root; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Notation)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.Whitespace)] = (int)XPathNodeType.Whitespace; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.SignificantWhitespace)] = (int)XPathNodeType.SignificantWhitespace; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.EndElement)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.EndEntity)] = -1; s_xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.XmlDeclaration)] = -1; // xmlNodeType_To_XpathNodeType_Map[(int)(XmlNodeType.All)] = -1; } private XPathNodeType DecideXPNodeTypeForTextNodes(XmlNode node) { //the function can only be called on text like nodes. Debug.Assert(XmlDataDocument.IsTextNode(node.NodeType)); XPathNodeType xnt = XPathNodeType.Whitespace; while (node != null) { switch (node.NodeType) { case XmlNodeType.Whitespace: break; case XmlNodeType.SignificantWhitespace: xnt = XPathNodeType.SignificantWhitespace; break; case XmlNodeType.Text: case XmlNodeType.CDATA: return XPathNodeType.Text; default: return xnt; } node = _doc.SafeNextSibling(node); } return xnt; } private XPathNodeType ConvertNodeType(XmlNode node) { int xnt = -1; if (XmlDataDocument.IsTextNode(node.NodeType)) return DecideXPNodeTypeForTextNodes(node); xnt = s_xmlNodeType_To_XpathNodeType_Map[(int)(node.NodeType)]; if (xnt == (int)XPathNodeType.Attribute) { if (node.NamespaceURI == StrReservedXmlns) return XPathNodeType.Namespace; else return XPathNodeType.Attribute; } Debug.Assert(xnt != -1); return (XPathNodeType)xnt; } private bool IsNamespaceNode(XmlNodeType nt, string ns) => nt == XmlNodeType.Attribute && ns == StrReservedXmlns; //when the constructor is called, the node has to be a valid XPath node at the valid location ( for example, the first //text/WS/SWS/CData nodes of a series continuous text-like nodes. internal XPathNodePointer(DataDocumentXPathNavigator owner, XmlDataDocument doc, XmlNode node) : this(owner, doc, node, null, false, null) { } internal XPathNodePointer(DataDocumentXPathNavigator owner, XPathNodePointer pointer) : this(owner, pointer._doc, pointer._node, pointer._column, pointer._fOnValue, pointer._parentOfNS) { } private XPathNodePointer(DataDocumentXPathNavigator owner, XmlDataDocument doc, XmlNode node, DataColumn c, bool bOnValue, XmlBoundElement parentOfNS) { Debug.Assert(owner != null); _owner = new WeakReference(owner); _doc = doc; _node = node; _column = c; _fOnValue = bOnValue; _parentOfNS = parentOfNS; // Add this pointer to the document so it will be updated each time region changes it's foliation state. _doc.AddPointer(this); _bNeedFoliate = false; AssertValid(); } internal XPathNodePointer Clone(DataDocumentXPathNavigator owner) { RealFoliate(); return new XPathNodePointer(owner, this); } internal bool IsEmptyElement { get { AssertValid(); if (_node != null && _column == null) { if (_node.NodeType == XmlNodeType.Element) { return ((XmlElement)_node).IsEmpty; } } return false; } } internal XPathNodeType NodeType { get { RealFoliate(); AssertValid(); if (_node == null) { return XPathNodeType.All; } else if (_column == null) { return ConvertNodeType(_node); } else if (_fOnValue) { return XPathNodeType.Text; } else if (_column.ColumnMapping == MappingType.Attribute) { if (_column.Namespace == StrReservedXmlns) return XPathNodeType.Namespace; else return XPathNodeType.Attribute; } else { return XPathNodeType.Element; } } } //LDAI: From CodeReview: Perf: We should have another array similar w/ // xmlNodeType_To_XpathNodeType_Map that will return String.Empty for everything but the element and // attribute case. internal string LocalName { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { XmlNodeType nt = _node.NodeType; if (IsNamespaceNode(nt, _node.NamespaceURI) && _node.LocalName == StrXmlNS) return string.Empty; if (nt == XmlNodeType.Element || nt == XmlNodeType.Attribute || nt == XmlNodeType.ProcessingInstruction) return _node.LocalName; return string.Empty; } else if (_fOnValue) { return string.Empty; } else //when column is not null return _doc.NameTable.Add(_column.EncodedColumnName); } } //note that, we've have lost the prefix in this senario ( defoliation will toss prefix away. ) internal string Name { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { XmlNodeType nt = _node.NodeType; if (IsNamespaceNode(nt, _node.NamespaceURI)) { if (_node.LocalName == StrXmlNS) return string.Empty; else return _node.LocalName; } if (nt == XmlNodeType.Element || nt == XmlNodeType.Attribute || nt == XmlNodeType.ProcessingInstruction) return _node.Name; return string.Empty; } else if (_fOnValue) { return string.Empty; } else { //when column is not null //we've lost prefix in this senario. return _doc.NameTable.Add(_column.EncodedColumnName); } } } internal string NamespaceURI { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { XPathNodeType xnt = ConvertNodeType(_node); if (xnt == XPathNodeType.Element || xnt == XPathNodeType.Root || xnt == XPathNodeType.Attribute) return _node.NamespaceURI; return string.Empty; } else if (_fOnValue) { return string.Empty; } else { //When column is not null if (_column.Namespace == StrReservedXmlns) { //namespace nodes has empty string as namespaceURI return string.Empty; } return _doc.NameTable.Add(_column.Namespace); } } } internal string Prefix { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { if (IsNamespaceNode(_node.NodeType, _node.NamespaceURI)) return string.Empty; return _node.Prefix; } return string.Empty; } } internal string Value { get { RealFoliate(); AssertValid(); if (_node == null) return null; else if (_column == null) { string strRet = _node.Value; if (XmlDataDocument.IsTextNode(_node.NodeType)) { //concatenate adjacent textlike nodes XmlNode parent = _node.ParentNode; if (parent == null) return strRet; XmlNode n = _doc.SafeNextSibling(_node); while (n != null && XmlDataDocument.IsTextNode(n.NodeType)) { strRet += n.Value; n = _doc.SafeNextSibling(n); } } return strRet; } else if (_column.ColumnMapping == MappingType.Attribute || _fOnValue) { DataRow row = Row; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; object value = row[_column, rowVersion]; if (!Convert.IsDBNull(value)) return _column.ConvertObjectToXml(value); return null; } else return null; } } internal string InnerText { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { if (_node.NodeType == XmlNodeType.Document) { //document node's region should always be uncompressed XmlElement rootElem = ((XmlDocument)_node).DocumentElement; if (rootElem != null) return rootElem.InnerText; return string.Empty; } else return _node.InnerText; } else { DataRow row = Row; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; object value = row[_column, rowVersion]; if (!Convert.IsDBNull(value)) return _column.ConvertObjectToXml(value); return string.Empty; } } } internal string BaseURI { get { RealFoliate(); if (_node != null) return _node.BaseURI; return string.Empty; } } internal string XmlLang { get { RealFoliate(); XmlNode curNode = _node; XmlBoundElement curBoundElem = null; object colVal = null; while (curNode != null) { curBoundElem = curNode as XmlBoundElement; if (curBoundElem != null) { if (curBoundElem.ElementState == ElementState.Defoliated) { //if not foliated, going through the columns to get the xml:lang DataRow row = curBoundElem.Row; foreach (DataColumn col in row.Table.Columns) { if (col.Prefix == "xml" && col.EncodedColumnName == "lang") { colVal = row[col]; if (colVal == DBNull.Value) break; //goto its ancestor return (string)colVal; } } } else { //if folicated, get the attribute directly if (curBoundElem.HasAttribute("xml:lang")) return curBoundElem.GetAttribute("xml:lang"); } } if (curNode.NodeType == XmlNodeType.Attribute) curNode = ((XmlAttribute)curNode).OwnerElement; else curNode = curNode.ParentNode; } return string.Empty; } } private XmlBoundElement GetRowElement() { XmlBoundElement rowElem; if (_column != null) { rowElem = _node as XmlBoundElement; Debug.Assert(rowElem != null); Debug.Assert(rowElem.Row != null); return rowElem; } _doc.Mapper.GetRegion(_node, out rowElem); return rowElem; } private DataRow Row { get { XmlBoundElement rowElem = GetRowElement(); if (rowElem == null) return null; Debug.Assert(rowElem.Row != null); return rowElem.Row; } } internal bool MoveTo(XPathNodePointer pointer) { AssertValid(); if (_doc != pointer._doc) { return false; } _node = pointer._node; _column = pointer._column; _fOnValue = pointer._fOnValue; _bNeedFoliate = pointer._bNeedFoliate; AssertValid(); return true; } private void MoveTo(XmlNode node) { // Should not move outside of this document Debug.Assert(node == _doc || node.OwnerDocument == _doc); _node = node; _column = null; _fOnValue = false; } private void MoveTo(XmlNode node, DataColumn column, bool fOnValue) { // Should not move outside of this document Debug.Assert(node == _doc || node.OwnerDocument == _doc); _node = node; _column = column; _fOnValue = fOnValue; } private bool IsFoliated(XmlNode node) { if (node != null && node is XmlBoundElement) return ((XmlBoundElement)node).IsFoliated; return true; } private int ColumnCount(DataRow row, bool fAttribute) { DataColumn c = null; int count = 0; while ((c = NextColumn(row, c, fAttribute)) != null) { if (c.Namespace != StrReservedXmlns) count++; } return count; } internal int AttributeCount { get { RealFoliate(); AssertValid(); if (_node != null) { if (_column == null && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) return ColumnCount(Row, true); else { int nc = 0; foreach (XmlAttribute attr in _node.Attributes) { if (attr.NamespaceURI != StrReservedXmlns) nc++; } return nc; } } } return 0; } } internal DataColumn NextColumn(DataRow row, DataColumn col, bool fAttribute) { if (row.RowState == DataRowState.Deleted) return null; DataTable table = row.Table; DataColumnCollection columns = table.Columns; int iColumn = (col != null) ? col.Ordinal + 1 : 0; int cColumns = columns.Count; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; for (; iColumn < cColumns; iColumn++) { DataColumn c = columns[iColumn]; if (!_doc.IsNotMapped(c) && (c.ColumnMapping == MappingType.Attribute) == fAttribute && !Convert.IsDBNull(row[c, rowVersion])) return c; } return null; } internal DataColumn PreviousColumn(DataRow row, DataColumn col, bool fAttribute) { if (row.RowState == DataRowState.Deleted) return null; DataTable table = row.Table; DataColumnCollection columns = table.Columns; int iColumn = (col != null) ? col.Ordinal - 1 : columns.Count - 1; int cColumns = columns.Count; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; for (; iColumn >= 0; iColumn--) { DataColumn c = columns[iColumn]; if (!_doc.IsNotMapped(c) && (c.ColumnMapping == MappingType.Attribute) == fAttribute && !Convert.IsDBNull(row[c, rowVersion])) return c; } return null; } internal bool MoveToAttribute(string localName, string namespaceURI) { RealFoliate(); AssertValid(); if (namespaceURI == StrReservedXmlns) return false; if (_node != null) { //_column.ColumnMapping checkin below is not really needed since the pointer should be pointing at the node before this // function should even be called ( there is always a call MoveToOwnerElement() before MoveToAttribute(..) if ((_column == null || _column.ColumnMapping == MappingType.Attribute) && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) { DataColumn c = null; while ((c = NextColumn(Row, c, true)) != null) { if (c.EncodedColumnName == localName && c.Namespace == namespaceURI) { MoveTo(_node, c, false); return true; } } } else { Debug.Assert(_node.Attributes != null); XmlNode n = _node.Attributes.GetNamedItem(localName, namespaceURI); if (n != null) { MoveTo(n, null, false); return true; } } } } return false; } internal bool MoveToNextAttribute(bool bFirst) { RealFoliate(); AssertValid(); if (_node != null) { if (bFirst && (_column != null || _node.NodeType != XmlNodeType.Element)) return false; if (!bFirst) { if (_column != null && _column.ColumnMapping != MappingType.Attribute) return false; if (_column == null && _node.NodeType != XmlNodeType.Attribute) return false; } if (!IsFoliated(_node)) { DataColumn c = _column; while ((c = NextColumn(Row, c, true)) != null) { if (c.Namespace != StrReservedXmlns) { MoveTo(_node, c, false); return true; } } return false; } else { if (bFirst) { XmlAttributeCollection attrs = _node.Attributes; foreach (XmlAttribute attr in attrs) { if (attr.NamespaceURI != StrReservedXmlns) { MoveTo(attr, null, false); return true; } } } else { XmlAttributeCollection attrs = ((XmlAttribute)_node).OwnerElement.Attributes; bool bFound = false; foreach (XmlAttribute attr in attrs) { if (bFound && attr.NamespaceURI != StrReservedXmlns) { MoveTo(attr, null, false); return true; } if (attr == _node) bFound = true; } } } } return false; } private bool IsValidChild(XmlNode parent, XmlNode child) { int xntChildInt = s_xmlNodeType_To_XpathNodeType_Map[(int)(child.NodeType)]; if (xntChildInt == -1) return false; int xntInt = s_xmlNodeType_To_XpathNodeType_Map[(int)(parent.NodeType)]; Debug.Assert(xntInt != -1); switch (xntInt) { case (int)XPathNodeType.Root: return (xntChildInt == (int)XPathNodeType.Element || xntChildInt == (int)XPathNodeType.Comment || xntChildInt == (int)XPathNodeType.ProcessingInstruction); case (int)XPathNodeType.Element: return (xntChildInt == (int)XPathNodeType.Element || xntChildInt == (int)XPathNodeType.Text || xntChildInt == (int)XPathNodeType.Comment || xntChildInt == (int)XPathNodeType.Whitespace || xntChildInt == (int)XPathNodeType.SignificantWhitespace || xntChildInt == (int)XPathNodeType.ProcessingInstruction); default: return false; } } private bool IsValidChild(XmlNode parent, DataColumn c) { int xntInt = s_xmlNodeType_To_XpathNodeType_Map[(int)(parent.NodeType)]; Debug.Assert(xntInt != -1); switch (xntInt) { case (int)XPathNodeType.Root: return c.ColumnMapping == MappingType.Element; case (int)XPathNodeType.Element: return (c.ColumnMapping == MappingType.Element || c.ColumnMapping == MappingType.SimpleContent); default: return false; } } internal bool MoveToNextSibling() { RealFoliate(); AssertValid(); if (_node != null) { if (_column != null) { if (_fOnValue) { // _fOnValue could be true only when the column is mapped as simplecontent or element Debug.Assert(_column.ColumnMapping != MappingType.Attribute && _column.ColumnMapping != MappingType.Hidden); return false; } DataRow curRow = Row; DataColumn c = NextColumn(curRow, _column, false); while (c != null) { if (IsValidChild(_node, c)) { MoveTo(_node, c, _doc.IsTextOnly(c)); return true; } c = NextColumn(curRow, c, false); } XmlNode n = _doc.SafeFirstChild(_node); if (n != null) { MoveTo(n); return true; } } else { XmlNode n = _node; XmlNode parent = _node.ParentNode; if (parent == null) return false; bool bTextLike = XmlDataDocument.IsTextNode(_node.NodeType); do { do { n = _doc.SafeNextSibling(n); } while (n != null && bTextLike && XmlDataDocument.IsTextNode(n.NodeType)); } while (n != null && !IsValidChild(parent, n)); if (n != null) { MoveTo(n); return true; } } } return false; } internal bool MoveToPreviousSibling() { RealFoliate(); AssertValid(); if (_node != null) { if (_column != null) { if (_fOnValue) return false; DataRow curRow = Row; DataColumn c = PreviousColumn(curRow, _column, false); while (c != null) { if (IsValidChild(_node, c)) { MoveTo(_node, c, _doc.IsTextOnly(c)); return true; } c = PreviousColumn(curRow, c, false); } } else { XmlNode n = _node; XmlNode parent = _node.ParentNode; if (parent == null) return false; bool bTextLike = XmlDataDocument.IsTextNode(_node.NodeType); do { do { n = _doc.SafePreviousSibling(n); } while (n != null && bTextLike && XmlDataDocument.IsTextNode(n.NodeType)); } while (n != null && !IsValidChild(parent, n)); if (n != null) { MoveTo(n); return true; } if (!IsFoliated(parent) && (parent is XmlBoundElement)) { DataRow row = ((XmlBoundElement)parent).Row; if (row != null) { DataColumn c = PreviousColumn(row, null, false); if (c != null) { MoveTo(parent, c, _doc.IsTextOnly(c)); return true; } } } } } return false; } internal bool MoveToFirst() { RealFoliate(); AssertValid(); if (_node != null) { DataRow curRow = null; XmlNode parent = null; if (_column != null) { curRow = Row; parent = _node; } else { parent = _node.ParentNode; if (parent == null) return false; if (!IsFoliated(parent) && (parent is XmlBoundElement)) curRow = ((XmlBoundElement)parent).Row; } //first check with the columns in the row if (curRow != null) { DataColumn c = NextColumn(curRow, null, false); while (c != null) { if (IsValidChild(_node, c)) { MoveTo(_node, c, _doc.IsTextOnly(c)); return true; } c = NextColumn(curRow, c, false); } } //didn't find a valid column or maybe already Foliated, go through its children nodes XmlNode n = _doc.SafeFirstChild(parent); while (n != null) { if (IsValidChild(parent, n)) { MoveTo(n); return true; } n = _doc.SafeNextSibling(n); } } return false; } internal bool HasChildren { get { RealFoliate(); AssertValid(); if (_node == null) return false; if (_column != null) { if (_column.ColumnMapping == MappingType.Attribute || _column.ColumnMapping == MappingType.Hidden) return false; return !_fOnValue; } if (!IsFoliated(_node)) { // find virtual column elements first DataRow curRow = Row; DataColumn c = NextColumn(curRow, null, false); while (c != null) { if (IsValidChild(_node, c)) return true; c = NextColumn(curRow, c, false); } } // look for anything XmlNode n = _doc.SafeFirstChild(_node); while (n != null) { if (IsValidChild(_node, n)) return true; n = _doc.SafeNextSibling(n); } return false; } } internal bool MoveToFirstChild() { RealFoliate(); AssertValid(); if (_node == null) return false; if (_column != null) { if (_column.ColumnMapping == MappingType.Attribute || _column.ColumnMapping == MappingType.Hidden) return false; if (_fOnValue) //text node has no children to move to return false; _fOnValue = true; return true; } if (!IsFoliated(_node)) { // find virtual column elements first DataRow curRow = Row; DataColumn c = NextColumn(curRow, null, false); while (c != null) { if (IsValidChild(_node, c)) { MoveTo(_node, c, _doc.IsTextOnly(c)); return true; } c = NextColumn(curRow, c, false); } } // look for anything XmlNode n = _doc.SafeFirstChild(_node); while (n != null) { if (IsValidChild(_node, n)) { MoveTo(n); return true; } n = _doc.SafeNextSibling(n); } return false; } //this version of MoveToParent will consider Attribute type position and move to its owner element internal bool MoveToParent() { RealFoliate(); AssertValid(); if (NodeType == XPathNodeType.Namespace) { MoveTo(_parentOfNS); return true; } if (_node != null) { if (_column != null) { if (_fOnValue && !_doc.IsTextOnly(_column)) { MoveTo(_node, _column, false); return true; } MoveTo(_node, null, false); return true; } else { XmlNode n = null; if (_node.NodeType == XmlNodeType.Attribute) n = ((XmlAttribute)_node).OwnerElement; else n = _node.ParentNode; if (n != null) { MoveTo(n); return true; } } } return false; } private XmlNode GetParent(XmlNode node) { XPathNodeType xnt = ConvertNodeType(node); if (xnt == XPathNodeType.Namespace) { Debug.Assert(_parentOfNS != null); return _parentOfNS; } if (xnt == XPathNodeType.Attribute) return ((XmlAttribute)node).OwnerElement; return node.ParentNode; } internal void MoveToRoot() { XmlNode node = _node; XmlNode parent = _node; while (parent != null) { node = parent; parent = GetParent(parent); } _node = node; _column = null; _fOnValue = false; AssertValid(); } internal bool IsSamePosition(XPathNodePointer pointer) { RealFoliate(); pointer.RealFoliate(); AssertValid(); pointer.AssertValid(); if (_column == null && pointer._column == null) return (pointer._node == _node && pointer._parentOfNS == _parentOfNS); return (pointer._doc == _doc && pointer._node == _node && pointer._column == _column && pointer._fOnValue == _fOnValue && pointer._parentOfNS == _parentOfNS); } private XmlNodeOrder CompareNamespacePosition(XPathNodePointer other) { XPathNodePointer xp1 = Clone((DataDocumentXPathNavigator)(_owner.Target)); XPathNodePointer xp2 = other.Clone((DataDocumentXPathNavigator)(other._owner.Target)); while (xp1.MoveToNextNamespace(XPathNamespaceScope.All)) { if (xp1.IsSamePosition(other)) return XmlNodeOrder.Before; } return XmlNodeOrder.After; } private static XmlNode GetRoot(XmlNode node, ref int depth) { depth = 0; XmlNode curNode = node; XmlNode parent = ((curNode.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode).OwnerElement) : (curNode.ParentNode)); for (; parent != null; depth++) { curNode = parent; parent = curNode.ParentNode; // no need to check for attribute since navigator can't be built on its children or navigate to its children } return curNode; } internal XmlNodeOrder ComparePosition(XPathNodePointer other) { RealFoliate(); other.RealFoliate(); Debug.Assert(other != null); if (IsSamePosition(other)) return XmlNodeOrder.Same; XmlNode curNode1 = null, curNode2 = null; //deal with namespace node first if (NodeType == XPathNodeType.Namespace && other.NodeType == XPathNodeType.Namespace) { if (_parentOfNS == other._parentOfNS) return CompareNamespacePosition(other); //if not from the same parent curNode1 = _parentOfNS; curNode2 = other._parentOfNS; } else if (NodeType == XPathNodeType.Namespace) { Debug.Assert(other.NodeType != XPathNodeType.Namespace); if (_parentOfNS == other._node) { //from the same region, NS nodes come before all other nodes if (other._column == null) return XmlNodeOrder.After; else return XmlNodeOrder.Before; } //if not from the same region curNode1 = _parentOfNS; curNode2 = other._node; } else if (other.NodeType == XPathNodeType.Namespace) { Debug.Assert(NodeType != XPathNodeType.Namespace); if (_node == other._parentOfNS) { //from the same region if (_column == null) return XmlNodeOrder.Before; else return XmlNodeOrder.After; } //if not from the same region curNode1 = _node; curNode2 = other._parentOfNS; } else { if (_node == other._node) { //compare within the same region if (_column == other._column) { //one is the children of the other Debug.Assert(_fOnValue != other._fOnValue); if (_fOnValue) return XmlNodeOrder.After; else return XmlNodeOrder.Before; } else { Debug.Assert(Row == other.Row); //in the same row if (_column == null) return XmlNodeOrder.Before; else if (other._column == null) return XmlNodeOrder.After; else if (_column.Ordinal < other._column.Ordinal) return XmlNodeOrder.Before; else return XmlNodeOrder.After; } } curNode1 = _node; curNode2 = other._node; } Debug.Assert(curNode1 != null); Debug.Assert(curNode2 != null); if (curNode1 == null || curNode2 == null) { return XmlNodeOrder.Unknown; } int depth1 = -1, depth2 = -1; XmlNode root1 = XPathNodePointer.GetRoot(curNode1, ref depth1); XmlNode root2 = XPathNodePointer.GetRoot(curNode2, ref depth2); if (root1 != root2) return XmlNodeOrder.Unknown; if (depth1 > depth2) { while (curNode1 != null && depth1 > depth2) { curNode1 = ((curNode1.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode1).OwnerElement) : (curNode1.ParentNode)); depth1--; } if (curNode1 == curNode2) return XmlNodeOrder.After; } else if (depth2 > depth1) { while (curNode2 != null && depth2 > depth1) { curNode2 = ((curNode2.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode2).OwnerElement) : (curNode2.ParentNode)); depth2--; } if (curNode1 == curNode2) return XmlNodeOrder.Before; } XmlNode parent1 = GetParent(curNode1); XmlNode parent2 = GetParent(curNode2); XmlNode nextNode = null; while (parent1 != null && parent2 != null) { if (parent1 == parent2) { while (curNode1 != null) { nextNode = curNode1.NextSibling; if (nextNode == curNode2) return XmlNodeOrder.Before; curNode1 = nextNode; } return XmlNodeOrder.After; } curNode1 = parent1; curNode2 = parent2; parent1 = curNode1.ParentNode; parent2 = curNode2.ParentNode; } //logically, we shouldn't reach here Debug.Assert(false); return XmlNodeOrder.Unknown; } internal XmlNode Node { get { RealFoliate(); AssertValid(); if (_node == null) return null; XmlBoundElement rowElem = GetRowElement(); if (rowElem != null) { bool wasFoliationEnabled = _doc.IsFoliationEnabled; _doc.IsFoliationEnabled = true; _doc.Foliate(rowElem, ElementState.StrongFoliation); _doc.IsFoliationEnabled = wasFoliationEnabled; } RealFoliate(); AssertValid(); return _node; } } bool IXmlDataVirtualNode.IsOnNode(XmlNode nodeToCheck) { RealFoliate(); return nodeToCheck == _node; } bool IXmlDataVirtualNode.IsOnColumn(DataColumn col) { RealFoliate(); return col == _column; } void IXmlDataVirtualNode.OnFoliated(XmlNode foliatedNode) { // update the pointer if the element node has been foliated if (_node == foliatedNode) { // if already on this node, nothing to do! if (_column == null) return; _bNeedFoliate = true; } } private void RealFoliate() { if (!_bNeedFoliate) return; _bNeedFoliate = false; Debug.Assert(_column != null); XmlNode n = null; if (_doc.IsTextOnly(_column)) n = _node.FirstChild; else { if (_column.ColumnMapping == MappingType.Attribute) { n = _node.Attributes.GetNamedItem(_column.EncodedColumnName, _column.Namespace); } else { for (n = _node.FirstChild; n != null; n = n.NextSibling) { if (n.LocalName == _column.EncodedColumnName && n.NamespaceURI == _column.Namespace) break; } } if (n != null && _fOnValue) n = n.FirstChild; } if (n == null) throw new InvalidOperationException(SR.DataDom_Foliation); // Cannot use MoveTo( n ); b/c the initial state for MoveTo is invalid (region is foliated but this is not) _node = n; _column = null; _fOnValue = false; AssertValid(); _bNeedFoliate = false; } //The function only helps to find out if there is a namespace declaration of given name is defined on the given node //It will not check the ancestor of the given node. private string GetNamespace(XmlBoundElement be, string name) { if (be == null) return null; XmlAttribute attr = null; if (be.IsFoliated) { attr = be.GetAttributeNode(name, StrReservedXmlns); if (attr != null) return attr.Value; else return null; } else { //defoliated so that we need to search through its column DataRow curRow = be.Row; if (curRow == null) return null; //going through its attribute columns DataColumn curCol = PreviousColumn(curRow, null, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns) { DataRowVersion rowVersion = (curRow.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; return curCol.ConvertObjectToXml(curRow[curCol, rowVersion]); } curCol = PreviousColumn(curRow, curCol, true); } return null; } } internal string GetNamespace(string name) { //we are checking the namespace nodes backwards comparing its normal order in DOM tree if (name == "xml") return StrReservedXml; if (name == "xmlns") return StrReservedXmlns; if (name != null && name.Length == 0) name = "xmlns"; RealFoliate(); XmlNode node = _node; XmlNodeType nt = node.NodeType; string retVal = null; while (node != null) { //first identify an element node in the ancestor + itself while (node != null && ((nt = node.NodeType) != XmlNodeType.Element)) { if (nt == XmlNodeType.Attribute) node = ((XmlAttribute)node).OwnerElement; else node = node.ParentNode; } //found one -- inside if if (node != null) { //must be element node retVal = GetNamespace((XmlBoundElement)node, name); if (retVal != null) return retVal; //didn't find it, try the next parentnode node = node.ParentNode; } } //nothing happens, then return string.empty. return string.Empty; } internal bool MoveToNamespace(string name) { _parentOfNS = _node as XmlBoundElement; //only need to check with _node, even if _column is not null and its mapping type is element, it can't have attributes if (_parentOfNS == null) return false; string attrName = name; if (attrName == "xmlns") attrName = "xmlns:xmlns"; if (attrName != null && attrName.Length == 0) attrName = "xmlns"; RealFoliate(); XmlNode node = _node; XmlNodeType nt = node.NodeType; XmlAttribute attr = null; XmlBoundElement be = null; while (node != null) { //check current element node be = node as XmlBoundElement; if (be != null) { if (be.IsFoliated) { attr = be.GetAttributeNode(name, StrReservedXmlns); if (attr != null) { MoveTo(attr); return true; } } else {//defoliated so that we need to search through its column DataRow curRow = be.Row; if (curRow == null) return false; //going through its attribute columns DataColumn curCol = PreviousColumn(curRow, null, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns && curCol.ColumnName == name) { MoveTo(be, curCol, false); return true; } curCol = PreviousColumn(curRow, curCol, true); } } } //didn't find it, try the next element anccester. do { node = node.ParentNode; } while (node != null && node.NodeType != XmlNodeType.Element); } //nothing happens, the name doesn't exist as a namespace node. _parentOfNS = null; return false; } //the function will find the next namespace node on the given bound element starting with the given column or attribte // wether to use column or attribute depends on if the bound element is folicated or not. private bool MoveToNextNamespace(XmlBoundElement be, DataColumn col, XmlAttribute curAttr) { if (be != null) { if (be.IsFoliated) { XmlAttributeCollection attrs = be.Attributes; XmlAttribute attr = null; bool bFound = false; if (curAttr == null) bFound = true; //the first namespace will be the one #if DEBUG if (curAttr != null) Debug.Assert(curAttr.NamespaceURI == StrReservedXmlns); #endif Debug.Assert(attrs != null); int attrInd = attrs.Count; while (attrInd > 0) { attrInd--; attr = attrs[attrInd]; if (bFound && attr.NamespaceURI == StrReservedXmlns && !DuplicateNS(be, attr.LocalName)) { MoveTo(attr); return true; } if (attr == curAttr) bFound = true; } } else {//defoliated so that we need to search through its column DataRow curRow = be.Row; if (curRow == null) return false; //going through its attribute columns DataColumn curCol = PreviousColumn(curRow, col, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns && !DuplicateNS(be, curCol.ColumnName)) { MoveTo(be, curCol, false); return true; } curCol = PreviousColumn(curRow, curCol, true); } } } return false; } //Caller( DataDocumentXPathNavigator will make sure that the node is at the right position for this call ) internal bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { RealFoliate(); _parentOfNS = _node as XmlBoundElement; //only need to check with _node, even if _column is not null and its mapping type is element, it can't have attributes if (_parentOfNS == null) return false; XmlNode node = _node; XmlBoundElement be = null; while (node != null) { be = node as XmlBoundElement; if (MoveToNextNamespace(be, null, null)) return true; //didn't find it if (namespaceScope == XPathNamespaceScope.Local) goto labelNoNS; //try the next element anccestor. do { node = node.ParentNode; } while (node != null && node.NodeType != XmlNodeType.Element); } if (namespaceScope == XPathNamespaceScope.All) { MoveTo(_doc._attrXml, null, false); return true; } labelNoNS: //didn't find one namespace node _parentOfNS = null; return false; } //endElem is on the path from startElem to root is enforced by the caller private bool DuplicateNS(XmlBoundElement endElem, string lname) { if (_parentOfNS == null || endElem == null) return false; XmlBoundElement be = _parentOfNS; XmlNode node = null; while (be != null && be != endElem) { if (GetNamespace(be, lname) != null) return true; node = be; do { node = node.ParentNode; } while (node != null && node.NodeType != XmlNodeType.Element); be = node as XmlBoundElement; } return false; } //Caller( DataDocumentXPathNavigator will make sure that the node is at the right position for this call ) internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { RealFoliate(); Debug.Assert(_parentOfNS != null); XmlNode node = _node; //first check within the same boundelement if (_column != null) { Debug.Assert(_column.Namespace == StrReservedXmlns); if (namespaceScope == XPathNamespaceScope.Local && _parentOfNS != _node) //already outside scope return false; XmlBoundElement be = _node as XmlBoundElement; Debug.Assert(be != null); DataRow curRow = be.Row; Debug.Assert(curRow != null); DataColumn curCol = PreviousColumn(curRow, _column, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns) { MoveTo(be, curCol, false); return true; } curCol = PreviousColumn(curRow, curCol, true); } //didn't find it in this loop if (namespaceScope == XPathNamespaceScope.Local) return false; //try its ancesstor do { node = node.ParentNode; } while (node != null && node.NodeType != XmlNodeType.Element); } else if (_node.NodeType == XmlNodeType.Attribute) { XmlAttribute attr = (XmlAttribute)(_node); Debug.Assert(attr != null); node = attr.OwnerElement; if (node == null) return false; if (namespaceScope == XPathNamespaceScope.Local && _parentOfNS != node) //already outside scope return false; if (MoveToNextNamespace((XmlBoundElement)node, null, attr)) return true; //didn't find it if (namespaceScope == XPathNamespaceScope.Local) return false; do { node = node.ParentNode; } while (node != null && node.NodeType != XmlNodeType.Element); } // till now, node should be the next ancestor (bound) element of the element parent of current namespace node (attribute or data column) while (node != null) { //try the namespace attributes from the same element XmlBoundElement be = node as XmlBoundElement; if (MoveToNextNamespace(be, null, null)) return true; //no more namespace attribute under the same element do { node = node.ParentNode; } while (node != null && node.NodeType == XmlNodeType.Element); } //didn't find the next namespace, thus return if (namespaceScope == XPathNamespaceScope.All) { MoveTo(_doc._attrXml, null, false); return true; } return false; } [Conditional("DEBUG")] private void AssertValid() { // This pointer must be int the document list //RealFoliate(); _doc.AssertPointerPresent(this); if (_column != null) { // We must be on a de-foliated region XmlBoundElement rowElem = _node as XmlBoundElement; Debug.Assert(rowElem != null); DataRow row = rowElem.Row; Debug.Assert(row != null); // We cannot be on a column for which the value is DBNull DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; Debug.Assert(!Convert.IsDBNull(row[_column, rowVersion])); // If we are on the Text column, we should always have _fOnValue == true Debug.Assert((_column.ColumnMapping == MappingType.SimpleContent) ? (_fOnValue == true) : true); } if (_column == null) Debug.Assert(!_fOnValue); } internal XmlDataDocument Document { get { return _doc; } } bool IXmlDataVirtualNode.IsInUse() { return _owner.IsAlive; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Providers.Streams.AzureQueue; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Streams; using TestExtensions; using Xunit; using Xunit.Abstractions; using Orleans.Internal; namespace Tester.AzureUtils.Streaming { [Collection(TestEnvironmentFixture.DefaultCollection)] [TestCategory("Azure"), TestCategory("Streaming")] public class AzureQueueAdapterTests : AzureStorageBasicTests, IAsyncLifetime { private readonly ITestOutputHelper output; private readonly TestEnvironmentFixture fixture; private const int NumBatches = 20; private const int NumMessagesPerBatch = 20; public static readonly string AZURE_QUEUE_STREAM_PROVIDER_NAME = "AQAdapterTests"; private readonly ILoggerFactory loggerFactory; private static readonly SafeRandom Random = new SafeRandom(); private static List<string> azureQueueNames = AzureQueueUtilities.GenerateQueueNames($"AzureQueueAdapterTests-{Guid.NewGuid()}", 8); public AzureQueueAdapterTests(ITestOutputHelper output, TestEnvironmentFixture fixture) { this.output = output; this.fixture = fixture; this.loggerFactory = this.fixture.Services.GetService<ILoggerFactory>(); BufferPool.InitGlobalBufferPool(new SiloMessagingOptions()); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString)) { await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(this.loggerFactory, azureQueueNames, new AzureQueueOptions().ConfigureTestDefaults()); } } [SkippableFact, TestCategory("Functional"), TestCategory("Halo")] public async Task SendAndReceiveFromAzureQueue() { var options = new AzureQueueOptions { MessageVisibilityTimeout = TimeSpan.FromSeconds(30), QueueNames = azureQueueNames }; options.ConfigureTestDefaults(); var serializationManager = this.fixture.Services.GetService<SerializationManager>(); var clusterOptions = this.fixture.Services.GetRequiredService<IOptions<ClusterOptions>>(); var queueCacheOptions = new SimpleQueueCacheOptions(); var queueDataAdapter = new AzureQueueDataAdapterV2(serializationManager); var adapterFactory = new AzureQueueAdapterFactory( AZURE_QUEUE_STREAM_PROVIDER_NAME, options, queueCacheOptions, queueDataAdapter, this.fixture.Services, clusterOptions, serializationManager, loggerFactory); adapterFactory.Init(); await SendAndReceiveFromQueueAdapter(adapterFactory); } private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory) { IQueueAdapter adapter = await adapterFactory.CreateAdapter(); IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache(); // Create receiver per queue IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper(); Dictionary<QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver); Dictionary<QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache); await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5)))); // test using 2 streams Guid streamId1 = Guid.NewGuid(); Guid streamId2 = Guid.NewGuid(); int receivedBatches = 0; var streamsPerQueue = new ConcurrentDictionary<QueueId, HashSet<IStreamIdentity>>(); // reader threads (at most 2 active queues because only two streams) var work = new List<Task>(); foreach( KeyValuePair<QueueId, IQueueAdapterReceiver> receiverKvp in receivers) { QueueId queueId = receiverKvp.Key; var receiver = receiverKvp.Value; var qCache = caches[queueId]; Task task = Task.Factory.StartNew(() => { while (receivedBatches < NumBatches) { var messages = receiver.GetQueueMessagesAsync(QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG).Result.ToArray(); if (!messages.Any()) { continue; } foreach (IBatchContainer message in messages) { streamsPerQueue.AddOrUpdate(queueId, id => new HashSet<IStreamIdentity> { new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()) }, (id, set) => { set.Add(new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString())); return set; }); this.output.WriteLine("Queue {0} received message on stream {1}", queueId, message.StreamGuid); Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<int>().Count()); // "Half the events were ints" Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<string>().Count()); // "Half the events were strings" } Interlocked.Add(ref receivedBatches, messages.Length); qCache.AddToCache(messages); } }); work.Add(task); } // send events List<object> events = CreateEvents(NumMessagesPerBatch); work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches) .Select(i => i % 2 == 0 ? streamId1 : streamId2) .ToList() .ForEach(streamId => adapter.QueueMessageBatchAsync(streamId, streamId.ToString(), events.Take(NumMessagesPerBatch).ToArray(), null, RequestContextExtensions.Export(this.fixture.SerializationManager)).Wait()))); await Task.WhenAll(work); // Make sure we got back everything we sent Assert.Equal(NumBatches, receivedBatches); // check to see if all the events are in the cache and we can enumerate through them StreamSequenceToken firstInCache = new EventSequenceTokenV2(0); foreach (KeyValuePair<QueueId, HashSet<IStreamIdentity>> kvp in streamsPerQueue) { var receiver = receivers[kvp.Key]; var qCache = caches[kvp.Key]; foreach (IStreamIdentity streamGuid in kvp.Value) { // read all messages in cache for stream IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache); int messageCount = 0; StreamSequenceToken tenthInCache = null; StreamSequenceToken lastToken = firstInCache; while (cursor.MoveNext()) { Exception ex; messageCount++; IBatchContainer batch = cursor.GetCurrent(out ex); this.output.WriteLine("Token: {0}", batch.SequenceToken); Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}"); lastToken = batch.SequenceToken; if (messageCount == 10) { tenthInCache = batch.SequenceToken; } } this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid); Assert.Equal(NumBatches / 2, messageCount); Assert.NotNull(tenthInCache); // read all messages from the 10th cursor = qCache.GetCacheCursor(streamGuid, tenthInCache); messageCount = 0; while (cursor.MoveNext()) { messageCount++; } this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid); const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1) Assert.Equal(expected, messageCount); } } } private List<object> CreateEvents(int count) { return Enumerable.Range(0, count).Select(i => { if (i % 2 == 0) { return Random.Next(int.MaxValue) as object; } return Random.Next(int.MaxValue).ToString(CultureInfo.InvariantCulture); }).ToList(); } internal static string MakeClusterId() { const string DeploymentIdFormat = "cluster-{0}"; string now = DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff"); return string.Format(DeploymentIdFormat, now); } } }
/* * Copyright 2008-2016 the GAP developers. See the NOTICE file at the * top-level directory of this distribution, and at * https://gapwiki.chiro.be/copyright * Verfijnen gebruikersrechten Copyright 2015 Chirojeugd-Vlaanderen vzw * * 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.Runtime.Serialization; namespace Chiro.Gap.Domain { /// <summary> /// Maakt een onderscheid tussen kinderen en leiding /// </summary> [DataContract] [Flags] public enum LidType { // Opgelet: Niveau.LidInGroep = 2*LidType.Kind // en Niveau.LeidingInGroep = 2*LidType.Leiding // Origineel was dit toevallig, maar dit wordt gebruikt in // GroepenService.svc.cs voor conversie. // Let dus goed op als je die zaken zou wijzigen. [EnumMember] Geen = 0x0, [EnumMember] Kind = 0x01, [EnumMember] Leiding = 0x02, [EnumMember] Alles = Kind | Leiding, } /// <summary> /// Deelnemers, begeleiding, logistiek. Wordt voorlopig enkel gebruikt voor uitstappen van een groep, /// waar dit zich vertaalt als kind, leiding, logistiek. /// </summary> [DataContract] [Flags] public enum DeelnemerType { [EnumMember] Onbekend = 0x00, [EnumMember] Deelnemer = 0x01, [EnumMember] Begeleiding = 0x02, [EnumMember] Logistiek = 0x04 } /// <summary> /// Enum om informatie over het geslacht over te brengen /// </summary> /// <remarks>Kan zowel over personen als over groepen/afdelingen gaan</remarks> [DataContract] [Flags] public enum GeslachtsType { [EnumMember] Onbekend = 0x00, [EnumMember] Man = 0x01, [EnumMember] Vrouw = 0x02, [EnumMember] X = 0x04, // het derde geslacht [EnumMember] Gemengd = Man | Vrouw | X, // interessant voor gemengde groepen/afdelingen } /// <summary> /// Soorten abonnement /// </summary> [DataContract] public enum AbonnementType { /// <summary> /// <c>AbonnementType.Geen</c> mag niet in de database bewaard worden; in dat geval /// moet het abonnement gewoon verdwijnen. <c>Geen</c> is enkel van toepassing /// in een webform. /// </summary> [EnumMember] Geen = 0, [EnumMember] Digitaal = 1, [EnumMember] Papier = 2, } /// <summary> /// Niveau van een lid/groep/functie /// </summary> [DataContract] [Flags] public enum Niveau { // FUTURE // [EnumMember] // Satelliet = 0x01, // Opgelet: Niveau.LidInGroep = 2*LidType.Kind // en Niveau.LeidingInGroep = 2*LidType.Leiding // Origineel was dit toevallig, maar dit wordt gebruikt in // GroepenService.svc.cs voor conversie. // Let dus goed op als je die zaken zou wijzigen. [EnumMember] LidInGroep = 0x02, [EnumMember] LeidingInGroep = 0x04, [EnumMember] Groep = LidInGroep | LeidingInGroep, [EnumMember] Gewest = 0x08, [EnumMember] Verbond = 0x20, [EnumMember] Nationaal = 0x80, [EnumMember] KaderGroep = Gewest | Verbond | Nationaal, [EnumMember] Alles = /*Satelliet |*/ Groep | KaderGroep }; public static class NiveauExtensions { public static bool HeeftNiveau(this Niveau orig, Niveau n) { return (n & orig) != 0; } } /// <summary> /// Bepaalt de 'status' van het adres /// </summary> [DataContract] public enum AdresTypeEnum { [EnumMember] Thuis = 1, [EnumMember] Kot = 2, [EnumMember] Werk = 3, [EnumMember] Overig = 4 } /// <summary> /// Sorteringsopties van een lijst van personen /// </summary> [DataContract] public enum PersoonSorteringsEnum { [EnumMember] Naam = 1, [EnumMember] Leeftijd = 2, [EnumMember] Categorie = 3 } /// <summary> /// Enum voor (een aantal) eigenschappen relevant voor een lid. In eerste instantie wordt deze enum /// gebruikt om te bepalen op welke kolom gesorteerd moet worden. /// </summary> [DataContract] public enum LidEigenschap { [EnumMember] Naam = 1, [EnumMember] Leeftijd = 2, [EnumMember] Afdeling = 3, [EnumMember] InstapPeriode = 4, [EnumMember] Adres = 5, [EnumMember] Verjaardag = 6 } /// <summary> /// Enum voor ondersteunde communicatietypes /// </summary> /// <remarks>Moet overeenkomen met de database!</remarks> [DataContract] public enum CommunicatieTypeEnum { [EnumMember] TelefoonNummer = 1, [EnumMember] Fax = 2, [EnumMember] Email = 3, [EnumMember] WebSite = 4, [EnumMember] Msn = 5, [EnumMember] Xmpp = 6, [EnumMember] Twitter = 7, [EnumMember] StatusNet = 8 } /// <summary> /// Types verzekering; moet overeenkomen met database! /// </summary> [DataContract] public enum Verzekering { [EnumMember] LoonVerlies = 1 } /// <summary> /// Geeft aan of een werkJaar voorbij is, bezig is, of op zijn einde loopt (in overgang) /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags"), DataContract] [Flags] public enum WerkJaarStatus { [EnumMember] Onbekend = 0x00, /// <summary> /// Het werkjaar is voorbij. /// </summary> [EnumMember] Voorbij = 0x01, /// <summary> /// Het werkjaar is bezig. /// </summary> [EnumMember] Bezig = 0x02, /// <summary> /// De mogelijkheid bestaat om de jaarovergang te doen. /// </summary> [EnumMember] InOvergang = 0x06, // bewust 0x06, omdat een werkJaar in overgang dan ook bezig is. /// <summary> /// Het werkjaar is bezig, maar er zijn nog geen leden waarvan de probeerperiode voorbij is. /// </summary> [EnumMember] KanTerugDraaien = 0x12 } /// <summary> /// Geeft aan of de bivakaangifte al is ingevuld /// </summary> [DataContract] [Flags] public enum BivakAangifteStatus { [EnumMember] Ok = 0x00, [EnumMember] NogNietVanBelang = 0x01, [EnumMember] Ontbrekend = 0x02, [EnumMember] ContactOntbreekt = 0x04, [EnumMember] PlaatsOntbreekt = 0x08, [EnumMember] PlaatsEnContactOntbreekt = ContactOntbreekt|PlaatsOntbreekt, [EnumMember] Onbekend = 0x10 } /// <summary> /// Mogelijke problemen bij gegevens van leden /// </summary> [DataContract] public enum LidProbleem { [EnumMember] Onbekend, [EnumMember] AdresOntbreekt, [EnumMember] TelefoonNummerOntbreekt, [EnumMember] EmailOntbreekt, [EnumMember] EmailIsVerdacht } /// <summary> /// Sommige functies zijn gepredefinieerd, en hun codes moeten constant zijn. /// (Dit is enkel van toepassing op nationaal gedefinieerde functies) /// </summary> public enum NationaleFunctie { ContactPersoon = 1, GroepsLeiding = 2, Vb = 3, FinancieelVerantwoordelijke = 4, JeugdRaad = 5, KookPloeg = 6, Proost = 7, GroepsLeidingsBijeenkomsten = 196 + 1, SomVerantwoordelijke = 196 + 2, IkVerantwoordelijke = 196 + 3, RibbelVerantwoordelijke = 196 + 4, SpeelclubVerantwoordelijke = 196 + 5, RakwiVerantwoordelijke = 196 + 6, TitoVerantwoordelijke = 196 + 7, KetiVerantwoordelijke = 196 + 8, AspiVerantwoordelijke = 196 + 9, SomGewesten = 196 + 10, OpvolgingStadsGroepen = 196 + 11, Verbondsraad = 196 + 12, Verbondskern = 196 + 13, StartDagVerantwoordelijker = 196 + 14, SbVerantwoordelijke = 196 + 15 }; /// <summary> /// De ID's van de officiele afdelingen in GAP /// </summary> public enum NationaleAfdeling { Ribbels = 1, Speelclub = 2, Rakwis = 3, Titos = 4, Ketis = 5, Aspis = 6, Speciaal = 7 } [DataContract] [Flags] public enum Permissies { /// <summary> /// Geen rechten /// </summary> [EnumMember] Geen = 0x00, /// <summary> /// Leesrechten /// </summary> [EnumMember] Lezen = 0x01, /// <summary> /// Lezen en schrijven /// </summary> [EnumMember] Bewerken = 0x3, } /// <summary> /// Zaken waarop je permissies kunt hebben. /// </summary> [Flags] public enum SecurityAspect { [EnumMember] PersoonlijkeGegevens = 0x01, [EnumMember] GroepsGegevens = 0x02, [EnumMember] PersonenInAfdeling = 0x10, [EnumMember] PersonenInGroep = 0x90, [EnumMember] AllesVanGroep = (GroepsGegevens|PersonenInGroep) } public static class Nieuwebackend { public static string Info { get { return "Gewoon een marker om bij te houden wat ik weggooide voor de nieuwe backend"; } } } }
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using WebAPI.API.Comparers; using WebAPI.API.DataStructures; using WebAPI.Domain.ArcServerResponse.Geolocator; namespace WebAPI.API.Tests.DataStructures { [TestFixture] public class TopAddressCandidatesTests { [Test] public void GridWeightsMatter() { const int topItemCount = 3; const string tieBreakerInput = "GOLD"; var topCandidates = new TopAddressCandidates(topItemCount, new CandidateComparer(tieBreakerInput)); topCandidates.Add(new Candidate { Address = "GOLD", Score = 5, Weight = 100 }); topCandidates.Add(new Candidate { Address = "GOLDS", Score = 5, Weight = 100 }); topCandidates.Add(new Candidate { Address = "BRONZE", Score = 5, Weight = 1 }); topCandidates.Add(new Candidate { Address = "SILVER", Score = 5, Weight = 50 }); topCandidates.Add(new Candidate { Address = "Runner up", Score = 5, Weight = 0 }); var items = topCandidates.GetTopItems(); const int addOneForWinnerWhichIsRemoved = 1; Assert.That(items.Count(), Is.EqualTo(topItemCount + addOneForWinnerWhichIsRemoved)); var candidate = items.First(); Assert.That(candidate.Score, Is.EqualTo(5)); Assert.That(candidate.Address, Is.EqualTo("GOLD")); } [Test] public void SizeIsTwoWhenSuggestIsZeroForScoreDifferenceCalculating() { const int suggestCount = 0; const string tieBreakerInput = ""; var topCandidates = new TopAddressCandidates(suggestCount, new CandidateComparer(tieBreakerInput)); topCandidates.Add(new Candidate { Address = "GOLD", Score = 5, Weight = 100 }); topCandidates.Add(new Candidate { Address = "GOLDS", Score = 5, Weight = 100 }); topCandidates.Add(new Candidate { Address = "BRONZE", Score = 5, Weight = 1 }); topCandidates.Add(new Candidate { Address = "SILVER", Score = 5, Weight = 50 }); topCandidates.Add(new Candidate { Address = "Runner up", Score = 5, Weight = 0 }); Assert.That(topCandidates.GetTopItems().ToList().Count, Is.EqualTo(2)); } [Test] public void SizeIsOneLargerThanInputToGetExactSuggestionCount() { const int suggestCount = 2; const string tieBreakerInput = ""; var topCandidates = new TopAddressCandidates(suggestCount, new CandidateComparer(tieBreakerInput)); topCandidates.Add(new Candidate { Address = "GOLD", Score = 5, Weight = 100 }); topCandidates.Add(new Candidate { Address = "GOLDS", Score = 5, Weight = 100 }); topCandidates.Add(new Candidate { Address = "BRONZE", Score = 5, Weight = 1 }); topCandidates.Add(new Candidate { Address = "SILVER", Score = 5, Weight = 50 }); topCandidates.Add(new Candidate { Address = "Runner up", Score = 5, Weight = 0 }); Assert.That(topCandidates.GetTopItems().ToList().Count, Is.EqualTo(suggestCount + 1)); } [Test] public void TiesTakeHighRank() { const int suggestCount = 2; const string address = "669 3rd ave"; var topCandidates = new TopAddressCandidates(suggestCount, new CandidateComparer(address.ToUpperInvariant())); var streetCandidates = new List<Candidate> { new Candidate { Address = "669 W 3RD AVE", Score = 90.87, Weight = 1 }, new Candidate { Address = "669 E 3RD AVE", Score = 90.87, Weight = 1 }, new Candidate { Address = "670 W 3RD AVE", Score = 69.87, Weight = 1 }, new Candidate { Address = "670 E 3RD AVE", Score = 69.87, Weight = 1 } }; var addressPointCandidates = new List<Candidate> { new Candidate { Address = "669 W THIRD AVE", Score = 90.87, Weight = 2 }, new Candidate { Address = "669 E 3RD AVE", Score = 90.87, Weight = 2 } }; addressPointCandidates.ForEach(topCandidates.Add); streetCandidates.ForEach(topCandidates.Add); var items = topCandidates.GetTopItems(); const int addOneForWinnerWhichIsRemoved = 1; Assert.That(items.Count(), Is.EqualTo(suggestCount + addOneForWinnerWhichIsRemoved)); var topItems = topCandidates.GetTopItems().ToList(); topItems.ForEach(x => Assert.That(x.Score, Is.EqualTo(10))); Assert.That(topCandidates.GetTopItems().First().Address, Is.EqualTo("101 e 3rd ave")); } } }
// 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.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection.Emit; namespace System { [System.Runtime.InteropServices.ComVisible(true)] public abstract class MulticastDelegate : Delegate { // This is set under 3 circumstances // 1. Multicast delegate // 2. Secure/Wrapper delegate // 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method private Object _invocationList; private IntPtr _invocationCount; // This constructor is called from the class generated by the // compiler generated code (This must match the constructor // in Delegate protected MulticastDelegate(Object target, String method) : base(target, method) { } // This constructor is called from a class to generate a // delegate based upon a static method name and the Type object // for the class defining the method. protected MulticastDelegate(Type target, String method) : base(target, method) { } internal bool IsUnmanagedFunctionPtr() { return (_invocationCount == (IntPtr)(-1)); } internal bool InvocationListLogicallyNull() { return (_invocationList == null) || (_invocationList is LoaderAllocator) || (_invocationList is DynamicResolver); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new SerializationException(SR.Serialization_DelegatesNotSupported); } // equals returns true IIF the delegate is not null and has the // same target, method and invocation list as this object public override sealed bool Equals(Object obj) { if (obj == null) return false; if (object.ReferenceEquals(this, obj)) return true; if (!InternalEqualTypes(this, obj)) return false; // Since this is a MulticastDelegate and we know // the types are the same, obj should also be a // MulticastDelegate Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!"); var d = Unsafe.As<MulticastDelegate>(obj); if (_invocationCount != (IntPtr)0) { // there are 4 kind of delegate kinds that fall into this bucket // 1- Multicast (_invocationList is Object[]) // 2- Secure/Wrapper (_invocationList is Delegate) // 3- Unmanaged FntPtr (_invocationList == null) // 4- Open virtual (_invocationCount == MethodDesc of target, _invocationList == null, LoaderAllocator, or DynamicResolver) if (InvocationListLogicallyNull()) { if (IsUnmanagedFunctionPtr()) { if (!d.IsUnmanagedFunctionPtr()) return false; return CompareUnmanagedFunctionPtrs(this, d); } // now we know 'this' is not a special one, so we can work out what the other is if ((d._invocationList as Delegate) != null) // this is a secure/wrapper delegate so we need to unwrap and check the inner one return Equals(d._invocationList); return base.Equals(obj); } else { if ((_invocationList as Delegate) != null) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return _invocationList.Equals(obj); } else { Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate"); return InvocationListEquals(d); } } } else { // among the several kind of delegates falling into this bucket one has got a non // empty _invocationList (open static with special sig) // to be equals we need to check that _invocationList matches (both null is fine) // and call the base.Equals() if (!InvocationListLogicallyNull()) { if (!_invocationList.Equals(d._invocationList)) return false; return base.Equals(d); } // now we know 'this' is not a special one, so we can work out what the other is if ((d._invocationList as Delegate) != null) // this is a secure/wrapper delegate so we need to unwrap and check the inner one return Equals(d._invocationList); // now we can call on the base return base.Equals(d); } } // Recursive function which will check for equality of the invocation list. private bool InvocationListEquals(MulticastDelegate d) { Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison"); Object[] invocationList = _invocationList as Object[]; if (d._invocationCount != _invocationCount) return false; int invocationCount = (int)_invocationCount; for (int i = 0; i < invocationCount; i++) { Delegate dd = (Delegate)invocationList[i]; Object[] dInvocationList = d._invocationList as Object[]; if (!dd.Equals(dInvocationList[i])) return false; } return true; } private bool TrySetSlot(Object[] a, int index, Object o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null) return true; // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; if (dd._methodPtr == d._methodPtr && dd._target == d._target && dd._methodPtrAux == d._methodPtrAux) { return true; } } return false; } private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready) { // First, allocate a new multicast delegate just like this one, i.e. same type as the this object MulticastDelegate result = (MulticastDelegate)InternalAllocLike(this); // Performance optimization - if this already points to a true multicast delegate, // copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them if (thisIsMultiCastAlready) { result._methodPtr = this._methodPtr; result._methodPtrAux = this._methodPtrAux; } else { result._methodPtr = GetMulticastInvoke(); result._methodPtrAux = GetInvokeMethod(); } result._target = result; result._invocationList = invocationList; result._invocationCount = (IntPtr)invocationCount; return result; } internal MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount) { return NewMulticastDelegate(invocationList, invocationCount, false); } internal void StoreDynamicMethod(MethodInfo dynamicMethod) { if (_invocationCount != (IntPtr)0) { Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined"); // must be a secure/wrapper one, unwrap and save MulticastDelegate d = (MulticastDelegate)_invocationList; d._methodBase = dynamicMethod; } else _methodBase = dynamicMethod; } // This method will combine this delegate with the passed delegate // to form a new delegate. protected override sealed Delegate CombineImpl(Delegate follow) { if ((Object)follow == null) // cast to object for a more efficient test return this; // Verify that the types are the same... if (!InternalEqualTypes(this, follow)) throw new ArgumentException(SR.Arg_DlgtTypeMis); MulticastDelegate dFollow = (MulticastDelegate)follow; Object[] resultList; int followCount = 1; Object[] followList = dFollow._invocationList as Object[]; if (followList != null) followCount = (int)dFollow._invocationCount; int resultCount; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { resultCount = 1 + followCount; resultList = new Object[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[1 + i] = followList[i]; } return NewMulticastDelegate(resultList, resultCount); } else { int invocationCount = (int)_invocationCount; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) resultList = null; } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) allocCount *= 2; resultList = new Object[allocCount]; for (int i = 0; i < invocationCount; i++) resultList[i] = invocationList[i]; if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[invocationCount + i] = followList[i]; } } return NewMulticastDelegate(resultList, resultCount, true); } } private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount) { Object[] thisInvocationList = _invocationList as Object[]; int allocCount = thisInvocationList.Length; while (allocCount / 2 >= invocationCount - deleteCount) allocCount /= 2; Object[] newInvocationList = new Object[allocCount]; for (int i = 0; i < deleteIndex; i++) newInvocationList[i] = invocationList[i]; for (int i = deleteIndex + deleteCount; i < invocationCount; i++) newInvocationList[i - deleteCount] = invocationList[i]; return newInvocationList; } private bool EqualInvocationLists(Object[] a, Object[] b, int start, int count) { for (int i = 0; i < count; i++) { if (!(a[start + i].Equals(b[i]))) return false; } return true; } // This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. protected override sealed Delegate RemoveImpl(Delegate value) { // There is a special case were we are removing using a delegate as // the value we need to check for this case // MulticastDelegate v = value as MulticastDelegate; if (v == null) return this; if (v._invocationList as Object[] == null) { Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { // they are both not real Multicast if (this.Equals(value)) return null; } else { int invocationCount = (int)_invocationCount; for (int i = invocationCount; --i >= 0;) { if (value.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return (Delegate)invocationList[1 - i]; } else { Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return NewMulticastDelegate(list, invocationCount - 1, true); } } } } } else { Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int invocationCount = (int)_invocationCount; int vInvocationCount = (int)v._invocationCount; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v._invocationList as Object[], i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { // Special case - no values left return null; } else if (invocationCount - vInvocationCount == 1) { // Special case - only one value left, either at the beginning or the end return (Delegate)invocationList[i != 0 ? 0 : invocationCount - 1]; } else { Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return NewMulticastDelegate(list, invocationCount - vInvocationCount, true); } } } } } return this; } // This method returns the Invocation list of this multicast delegate. public override sealed Delegate[] GetInvocationList() { Contract.Ensures(Contract.Result<Delegate[]>() != null); Delegate[] del; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { del = new Delegate[1]; del[0] = this; } else { // Create an array of delegate copies and each // element into the array del = new Delegate[(int)_invocationCount]; for (int i = 0; i < del.Length; i++) del[i] = (Delegate)invocationList[i]; } return del; } public static bool operator ==(MulticastDelegate d1, MulticastDelegate d2) { if ((Object)d1 == null) return (Object)d2 == null; return d1.Equals(d2); } public static bool operator !=(MulticastDelegate d1, MulticastDelegate d2) { if ((Object)d1 == null) return (Object)d2 != null; return !d1.Equals(d2); } public override sealed int GetHashCode() { if (IsUnmanagedFunctionPtr()) return ValueType.GetHashCodeOfPtr(_methodPtr) ^ ValueType.GetHashCodeOfPtr(_methodPtrAux); if (_invocationCount != (IntPtr)0) { var t = _invocationList as Delegate; if (t != null) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return t.GetHashCode(); } } Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { return base.GetHashCode(); } else { int hash = 0; for (int i = 0; i < (int)_invocationCount; i++) { hash = hash * 33 + invocationList[i].GetHashCode(); } return hash; } } internal override Object GetTarget() { if (_invocationCount != (IntPtr)0) { // _invocationCount != 0 we are in one of these cases: // - Multicast -> return the target of the last delegate in the list // - Secure/wrapper delegate -> return the target of the inner delegate // - unmanaged function pointer - return null // - virtual open delegate - return null if (InvocationListLogicallyNull()) { // both open virtual and ftn pointer return null for the target return null; } else { Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int invocationCount = (int)_invocationCount; return ((Delegate)invocationList[invocationCount - 1]).GetTarget(); } else { Delegate receiver = _invocationList as Delegate; if (receiver != null) return receiver.GetTarget(); } } } return base.GetTarget(); } protected override MethodInfo GetMethodImpl() { if (_invocationCount != (IntPtr)0 && _invocationList != null) { // multicast case Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int index = (int)_invocationCount - 1; return ((Delegate)invocationList[index]).Method; } MulticastDelegate innerDelegate = _invocationList as MulticastDelegate; if (innerDelegate != null) { // must be a secure/wrapper delegate return innerDelegate.GetMethodImpl(); } } else if (IsUnmanagedFunctionPtr()) { // we handle unmanaged function pointers here because the generic ones (used for WinRT) would otherwise // be treated as open delegates by the base implementation, resulting in failure to get the MethodInfo if ((_methodBase == null) || !(_methodBase is MethodInfo)) { IRuntimeMethodInfo method = FindMethodHandle(); RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method); // need a proper declaring type instance method on a generic type if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType)) { // we are returning the 'Invoke' method of this delegate so use this.GetType() for the exact type RuntimeType reflectedType = GetType() as RuntimeType; declaringType = reflectedType; } _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method); } return (MethodInfo)_methodBase; } // Otherwise, must be an inner delegate of a SecureDelegate of an open virtual method. In that case, call base implementation return base.GetMethodImpl(); } // this should help inlining [System.Diagnostics.DebuggerNonUserCode] private void ThrowNullThisInDelegateToInstance() { throw new ArgumentException(SR.Arg_DlgtNullInst); } [System.Diagnostics.DebuggerNonUserCode] private void CtorClosed(Object target, IntPtr methodPtr) { if (target == null) ThrowNullThisInDelegateToInstance(); this._target = target; this._methodPtr = methodPtr; } [System.Diagnostics.DebuggerNonUserCode] private void CtorClosedStatic(Object target, IntPtr methodPtr) { this._target = target; this._methodPtr = methodPtr; } [System.Diagnostics.DebuggerNonUserCode] private void CtorRTClosed(Object target, IntPtr methodPtr) { this._target = target; this._methodPtr = AdjustTarget(target, methodPtr); } [System.Diagnostics.DebuggerNonUserCode] private void CtorOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = methodPtr; } [System.Diagnostics.DebuggerNonUserCode] private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = GetCallStub(methodPtr); } [System.Diagnostics.DebuggerNonUserCode] private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle) { this._target = target; this._methodPtr = methodPtr; this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle); } [System.Diagnostics.DebuggerNonUserCode] private void CtorCollectibleOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = methodPtr; this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle); } [System.Diagnostics.DebuggerNonUserCode] private void CtorCollectibleVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = GetCallStub(methodPtr); this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // This is a test case created by briansul. it compares // the result of a constant against the result of a variable shift operation. // It never repro'ed the actual issue, but it tests some of // the changes done by brian to the product code. // Well, and it runs fast. using System; class Program { static bool failed = false; static void check(long x, long y, string msg) { if (x != y) { Console.WriteLine("Failed " + msg); failed = true; } } static void check(ulong x, ulong y, string msg) { if (x != y) { Console.WriteLine("Failed " + msg); failed = true; } } static long VSHL(long x, int s) { return x << s; } static long SHL01(long x) { return x << 01; } static long SHL02(long x) { return x << 02; } static long SHL03(long x) { return x << 03; } static long SHL04(long x) { return x << 04; } static long SHL05(long x) { return x << 05; } static long SHL06(long x) { return x << 06; } static long SHL07(long x) { return x << 07; } static long SHL08(long x) { return x << 08; } static long SHL09(long x) { return x << 09; } static long SHL10(long x) { return x << 10; } static long SHL11(long x) { return x << 11; } static long SHL12(long x) { return x << 12; } static long SHL13(long x) { return x << 13; } static long SHL14(long x) { return x << 14; } static long SHL15(long x) { return x << 15; } static long SHL16(long x) { return x << 16; } static long SHL17(long x) { return x << 17; } static long SHL18(long x) { return x << 18; } static long SHL19(long x) { return x << 19; } static long SHL20(long x) { return x << 20; } static long SHL21(long x) { return x << 21; } static long SHL22(long x) { return x << 22; } static long SHL23(long x) { return x << 23; } static long SHL24(long x) { return x << 24; } static long SHL25(long x) { return x << 25; } static long SHL26(long x) { return x << 26; } static long SHL27(long x) { return x << 27; } static long SHL28(long x) { return x << 28; } static long SHL29(long x) { return x << 29; } static long SHL30(long x) { return x << 30; } static long SHL31(long x) { return x << 31; } static long SHL32(long x) { return x << 32; } static long SHL33(long x) { return x << 33; } static long SHL34(long x) { return x << 34; } static long SHL35(long x) { return x << 35; } static long SHL36(long x) { return x << 36; } static long SHL37(long x) { return x << 37; } static long SHL38(long x) { return x << 38; } static long SHL39(long x) { return x << 39; } static long SHL40(long x) { return x << 40; } static long SHL41(long x) { return x << 41; } static long SHL42(long x) { return x << 42; } static long SHL43(long x) { return x << 43; } static long SHL44(long x) { return x << 44; } static long SHL45(long x) { return x << 45; } static long SHL46(long x) { return x << 46; } static long SHL47(long x) { return x << 47; } static long SHL48(long x) { return x << 48; } static long SHL49(long x) { return x << 49; } static long SHL50(long x) { return x << 50; } static long SHL51(long x) { return x << 51; } static long SHL52(long x) { return x << 52; } static long SHL53(long x) { return x << 53; } static long SHL54(long x) { return x << 54; } static long SHL55(long x) { return x << 55; } static long SHL56(long x) { return x << 56; } static long SHL57(long x) { return x << 57; } static long SHL58(long x) { return x << 58; } static long SHL59(long x) { return x << 59; } static long SHL60(long x) { return x << 60; } static long SHL61(long x) { return x << 61; } static long SHL62(long x) { return x << 62; } static long SHL63(long x) { return x << 63; } static long SHL64(long x) { return x << 64; } static void TestSHL() { long x = 1; long resK; long resV; int s; for (int i = 0; i < 32; i++) { s = 1; resK = SHL01(x); resV = VSHL(x, s); check(resK, resV, "SHL01"); s += 1; resK = SHL02(x); resV = VSHL(x, s); check(resK, resV, "SHL02"); s += 1; resK = SHL03(x); resV = VSHL(x, s); check(resK, resV, "SHL03"); s += 1; resK = SHL04(x); resV = VSHL(x, s); check(resK, resV, "SHL04"); s += 1; resK = SHL05(x); resV = VSHL(x, s); check(resK, resV, "SHL05"); s += 1; resK = SHL06(x); resV = VSHL(x, s); check(resK, resV, "SHL06"); s += 1; resK = SHL07(x); resV = VSHL(x, s); check(resK, resV, "SHL07"); s += 1; resK = SHL08(x); resV = VSHL(x, s); check(resK, resV, "SHL08"); s += 1; resK = SHL09(x); resV = VSHL(x, s); check(resK, resV, "SHL09"); s += 1; resK = SHL10(x); resV = VSHL(x, s); check(resK, resV, "SHL10"); s += 1; resK = SHL11(x); resV = VSHL(x, s); check(resK, resV, "SHL11"); s += 1; resK = SHL12(x); resV = VSHL(x, s); check(resK, resV, "SHL12"); s += 1; resK = SHL13(x); resV = VSHL(x, s); check(resK, resV, "SHL13"); s += 1; resK = SHL14(x); resV = VSHL(x, s); check(resK, resV, "SHL14"); s += 1; resK = SHL15(x); resV = VSHL(x, s); check(resK, resV, "SHL15"); s += 1; resK = SHL16(x); resV = VSHL(x, s); check(resK, resV, "SHL16"); s += 1; resK = SHL17(x); resV = VSHL(x, s); check(resK, resV, "SHL17"); s += 1; resK = SHL18(x); resV = VSHL(x, s); check(resK, resV, "SHL18"); s += 1; resK = SHL19(x); resV = VSHL(x, s); check(resK, resV, "SHL19"); s += 1; resK = SHL20(x); resV = VSHL(x, s); check(resK, resV, "SHL20"); s += 1; resK = SHL21(x); resV = VSHL(x, s); check(resK, resV, "SHL21"); s += 1; resK = SHL22(x); resV = VSHL(x, s); check(resK, resV, "SHL22"); s += 1; resK = SHL23(x); resV = VSHL(x, s); check(resK, resV, "SHL23"); s += 1; resK = SHL24(x); resV = VSHL(x, s); check(resK, resV, "SHL24"); s += 1; resK = SHL25(x); resV = VSHL(x, s); check(resK, resV, "SHL25"); s += 1; resK = SHL26(x); resV = VSHL(x, s); check(resK, resV, "SHL26"); s += 1; resK = SHL27(x); resV = VSHL(x, s); check(resK, resV, "SHL27"); s += 1; resK = SHL28(x); resV = VSHL(x, s); check(resK, resV, "SHL28"); s += 1; resK = SHL29(x); resV = VSHL(x, s); check(resK, resV, "SHL29"); s += 1; resK = SHL30(x); resV = VSHL(x, s); check(resK, resV, "SHL30"); s += 1; resK = SHL31(x); resV = VSHL(x, s); check(resK, resV, "SHL31"); s += 1; resK = SHL32(x); resV = VSHL(x, s); check(resK, resV, "SHL32"); s += 1; resK = SHL33(x); resV = VSHL(x, s); check(resK, resV, "SHL33"); s += 1; resK = SHL34(x); resV = VSHL(x, s); check(resK, resV, "SHL34"); s += 1; resK = SHL35(x); resV = VSHL(x, s); check(resK, resV, "SHL35"); s += 1; resK = SHL36(x); resV = VSHL(x, s); check(resK, resV, "SHL36"); s += 1; resK = SHL37(x); resV = VSHL(x, s); check(resK, resV, "SHL37"); s += 1; resK = SHL38(x); resV = VSHL(x, s); check(resK, resV, "SHL38"); s += 1; resK = SHL39(x); resV = VSHL(x, s); check(resK, resV, "SHL39"); s += 1; resK = SHL40(x); resV = VSHL(x, s); check(resK, resV, "SHL40"); s += 1; resK = SHL41(x); resV = VSHL(x, s); check(resK, resV, "SHL41"); s += 1; resK = SHL42(x); resV = VSHL(x, s); check(resK, resV, "SHL42"); s += 1; resK = SHL43(x); resV = VSHL(x, s); check(resK, resV, "SHL43"); s += 1; resK = SHL44(x); resV = VSHL(x, s); check(resK, resV, "SHL44"); s += 1; resK = SHL45(x); resV = VSHL(x, s); check(resK, resV, "SHL45"); s += 1; resK = SHL46(x); resV = VSHL(x, s); check(resK, resV, "SHL46"); s += 1; resK = SHL47(x); resV = VSHL(x, s); check(resK, resV, "SHL47"); s += 1; resK = SHL48(x); resV = VSHL(x, s); check(resK, resV, "SHL48"); s += 1; resK = SHL49(x); resV = VSHL(x, s); check(resK, resV, "SHL49"); s += 1; resK = SHL50(x); resV = VSHL(x, s); check(resK, resV, "SHL50"); s += 1; resK = SHL51(x); resV = VSHL(x, s); check(resK, resV, "SHL51"); s += 1; resK = SHL52(x); resV = VSHL(x, s); check(resK, resV, "SHL52"); s += 1; resK = SHL53(x); resV = VSHL(x, s); check(resK, resV, "SHL53"); s += 1; resK = SHL54(x); resV = VSHL(x, s); check(resK, resV, "SHL54"); s += 1; resK = SHL55(x); resV = VSHL(x, s); check(resK, resV, "SHL55"); s += 1; resK = SHL56(x); resV = VSHL(x, s); check(resK, resV, "SHL56"); s += 1; resK = SHL57(x); resV = VSHL(x, s); check(resK, resV, "SHL57"); s += 1; resK = SHL58(x); resV = VSHL(x, s); check(resK, resV, "SHL58"); s += 1; resK = SHL59(x); resV = VSHL(x, s); check(resK, resV, "SHL59"); s += 1; resK = SHL60(x); resV = VSHL(x, s); check(resK, resV, "SHL60"); s += 1; resK = SHL61(x); resV = VSHL(x, s); check(resK, resV, "SHL61"); s += 1; resK = SHL62(x); resV = VSHL(x, s); check(resK, resV, "SHL62"); s += 1; resK = SHL63(x); resV = VSHL(x, s); check(resK, resV, "SHL63"); s += 1; resK = SHL64(x); resV = VSHL(x, s); check(resK, resV, "SHL64"); s += 1; x *= 5; } } static long VSHR(long x, int s) { return x >> s; } static long SHR01(long x) { return x >> 01; } static long SHR02(long x) { return x >> 02; } static long SHR03(long x) { return x >> 03; } static long SHR04(long x) { return x >> 04; } static long SHR05(long x) { return x >> 05; } static long SHR06(long x) { return x >> 06; } static long SHR07(long x) { return x >> 07; } static long SHR08(long x) { return x >> 08; } static long SHR09(long x) { return x >> 09; } static long SHR10(long x) { return x >> 10; } static long SHR11(long x) { return x >> 11; } static long SHR12(long x) { return x >> 12; } static long SHR13(long x) { return x >> 13; } static long SHR14(long x) { return x >> 14; } static long SHR15(long x) { return x >> 15; } static long SHR16(long x) { return x >> 16; } static long SHR17(long x) { return x >> 17; } static long SHR18(long x) { return x >> 18; } static long SHR19(long x) { return x >> 19; } static long SHR20(long x) { return x >> 20; } static long SHR21(long x) { return x >> 21; } static long SHR22(long x) { return x >> 22; } static long SHR23(long x) { return x >> 23; } static long SHR24(long x) { return x >> 24; } static long SHR25(long x) { return x >> 25; } static long SHR26(long x) { return x >> 26; } static long SHR27(long x) { return x >> 27; } static long SHR28(long x) { return x >> 28; } static long SHR29(long x) { return x >> 29; } static long SHR30(long x) { return x >> 30; } static long SHR31(long x) { return x >> 31; } static long SHR32(long x) { return x >> 32; } static long SHR33(long x) { return x >> 33; } static long SHR34(long x) { return x >> 34; } static long SHR35(long x) { return x >> 35; } static long SHR36(long x) { return x >> 36; } static long SHR37(long x) { return x >> 37; } static long SHR38(long x) { return x >> 38; } static long SHR39(long x) { return x >> 39; } static long SHR40(long x) { return x >> 40; } static long SHR41(long x) { return x >> 41; } static long SHR42(long x) { return x >> 42; } static long SHR43(long x) { return x >> 43; } static long SHR44(long x) { return x >> 44; } static long SHR45(long x) { return x >> 45; } static long SHR46(long x) { return x >> 46; } static long SHR47(long x) { return x >> 47; } static long SHR48(long x) { return x >> 48; } static long SHR49(long x) { return x >> 49; } static long SHR50(long x) { return x >> 50; } static long SHR51(long x) { return x >> 51; } static long SHR52(long x) { return x >> 52; } static long SHR53(long x) { return x >> 53; } static long SHR54(long x) { return x >> 54; } static long SHR55(long x) { return x >> 55; } static long SHR56(long x) { return x >> 56; } static long SHR57(long x) { return x >> 57; } static long SHR58(long x) { return x >> 58; } static long SHR59(long x) { return x >> 59; } static long SHR60(long x) { return x >> 60; } static long SHR61(long x) { return x >> 61; } static long SHR62(long x) { return x >> 62; } static long SHR63(long x) { return x >> 63; } static long SHR64(long x) { return x >> 64; } static void TestSHR() { long x = 1; long resK; long resV; int s; for (int i = 0; i < 32; i++) { s = 1; resK = SHR01(x); resV = VSHR(x, s); check(resK, resV, "SHR01"); s += 1; resK = SHR02(x); resV = VSHR(x, s); check(resK, resV, "SHR02"); s += 1; resK = SHR03(x); resV = VSHR(x, s); check(resK, resV, "SHR03"); s += 1; resK = SHR04(x); resV = VSHR(x, s); check(resK, resV, "SHR04"); s += 1; resK = SHR05(x); resV = VSHR(x, s); check(resK, resV, "SHR05"); s += 1; resK = SHR06(x); resV = VSHR(x, s); check(resK, resV, "SHR06"); s += 1; resK = SHR07(x); resV = VSHR(x, s); check(resK, resV, "SHR07"); s += 1; resK = SHR08(x); resV = VSHR(x, s); check(resK, resV, "SHR08"); s += 1; resK = SHR09(x); resV = VSHR(x, s); check(resK, resV, "SHR09"); s += 1; resK = SHR10(x); resV = VSHR(x, s); check(resK, resV, "SHR10"); s += 1; resK = SHR11(x); resV = VSHR(x, s); check(resK, resV, "SHR11"); s += 1; resK = SHR12(x); resV = VSHR(x, s); check(resK, resV, "SHR12"); s += 1; resK = SHR13(x); resV = VSHR(x, s); check(resK, resV, "SHR13"); s += 1; resK = SHR14(x); resV = VSHR(x, s); check(resK, resV, "SHR14"); s += 1; resK = SHR15(x); resV = VSHR(x, s); check(resK, resV, "SHR15"); s += 1; resK = SHR16(x); resV = VSHR(x, s); check(resK, resV, "SHR16"); s += 1; resK = SHR17(x); resV = VSHR(x, s); check(resK, resV, "SHR17"); s += 1; resK = SHR18(x); resV = VSHR(x, s); check(resK, resV, "SHR18"); s += 1; resK = SHR19(x); resV = VSHR(x, s); check(resK, resV, "SHR19"); s += 1; resK = SHR20(x); resV = VSHR(x, s); check(resK, resV, "SHR20"); s += 1; resK = SHR21(x); resV = VSHR(x, s); check(resK, resV, "SHR21"); s += 1; resK = SHR22(x); resV = VSHR(x, s); check(resK, resV, "SHR22"); s += 1; resK = SHR23(x); resV = VSHR(x, s); check(resK, resV, "SHR23"); s += 1; resK = SHR24(x); resV = VSHR(x, s); check(resK, resV, "SHR24"); s += 1; resK = SHR25(x); resV = VSHR(x, s); check(resK, resV, "SHR25"); s += 1; resK = SHR26(x); resV = VSHR(x, s); check(resK, resV, "SHR26"); s += 1; resK = SHR27(x); resV = VSHR(x, s); check(resK, resV, "SHR27"); s += 1; resK = SHR28(x); resV = VSHR(x, s); check(resK, resV, "SHR28"); s += 1; resK = SHR29(x); resV = VSHR(x, s); check(resK, resV, "SHR29"); s += 1; resK = SHR30(x); resV = VSHR(x, s); check(resK, resV, "SHR30"); s += 1; resK = SHR31(x); resV = VSHR(x, s); check(resK, resV, "SHR31"); s += 1; resK = SHR32(x); resV = VSHR(x, s); check(resK, resV, "SHR32"); s += 1; resK = SHR33(x); resV = VSHR(x, s); check(resK, resV, "SHR33"); s += 1; resK = SHR34(x); resV = VSHR(x, s); check(resK, resV, "SHR34"); s += 1; resK = SHR35(x); resV = VSHR(x, s); check(resK, resV, "SHR35"); s += 1; resK = SHR36(x); resV = VSHR(x, s); check(resK, resV, "SHR36"); s += 1; resK = SHR37(x); resV = VSHR(x, s); check(resK, resV, "SHR37"); s += 1; resK = SHR38(x); resV = VSHR(x, s); check(resK, resV, "SHR38"); s += 1; resK = SHR39(x); resV = VSHR(x, s); check(resK, resV, "SHR39"); s += 1; resK = SHR40(x); resV = VSHR(x, s); check(resK, resV, "SHR40"); s += 1; resK = SHR41(x); resV = VSHR(x, s); check(resK, resV, "SHR41"); s += 1; resK = SHR42(x); resV = VSHR(x, s); check(resK, resV, "SHR42"); s += 1; resK = SHR43(x); resV = VSHR(x, s); check(resK, resV, "SHR43"); s += 1; resK = SHR44(x); resV = VSHR(x, s); check(resK, resV, "SHR44"); s += 1; resK = SHR45(x); resV = VSHR(x, s); check(resK, resV, "SHR45"); s += 1; resK = SHR46(x); resV = VSHR(x, s); check(resK, resV, "SHR46"); s += 1; resK = SHR47(x); resV = VSHR(x, s); check(resK, resV, "SHR47"); s += 1; resK = SHR48(x); resV = VSHR(x, s); check(resK, resV, "SHR48"); s += 1; resK = SHR49(x); resV = VSHR(x, s); check(resK, resV, "SHR49"); s += 1; resK = SHR50(x); resV = VSHR(x, s); check(resK, resV, "SHR50"); s += 1; resK = SHR51(x); resV = VSHR(x, s); check(resK, resV, "SHR51"); s += 1; resK = SHR52(x); resV = VSHR(x, s); check(resK, resV, "SHR52"); s += 1; resK = SHR53(x); resV = VSHR(x, s); check(resK, resV, "SHR53"); s += 1; resK = SHR54(x); resV = VSHR(x, s); check(resK, resV, "SHR54"); s += 1; resK = SHR55(x); resV = VSHR(x, s); check(resK, resV, "SHR55"); s += 1; resK = SHR56(x); resV = VSHR(x, s); check(resK, resV, "SHR56"); s += 1; resK = SHR57(x); resV = VSHR(x, s); check(resK, resV, "SHR57"); s += 1; resK = SHR58(x); resV = VSHR(x, s); check(resK, resV, "SHR58"); s += 1; resK = SHR59(x); resV = VSHR(x, s); check(resK, resV, "SHR59"); s += 1; resK = SHR60(x); resV = VSHR(x, s); check(resK, resV, "SHR60"); s += 1; resK = SHR61(x); resV = VSHR(x, s); check(resK, resV, "SHR61"); s += 1; resK = SHR62(x); resV = VSHR(x, s); check(resK, resV, "SHR62"); s += 1; resK = SHR63(x); resV = VSHR(x, s); check(resK, resV, "SHR63"); s += 1; resK = SHR64(x); resV = VSHR(x, s); check(resK, resV, "SHR64"); s += 1; x *= 5; } } static ulong VSZR(ulong x, int s) { return x >> s; } static ulong SZR01(ulong x) { return x >> 01; } static ulong SZR02(ulong x) { return x >> 02; } static ulong SZR03(ulong x) { return x >> 03; } static ulong SZR04(ulong x) { return x >> 04; } static ulong SZR05(ulong x) { return x >> 05; } static ulong SZR06(ulong x) { return x >> 06; } static ulong SZR07(ulong x) { return x >> 07; } static ulong SZR08(ulong x) { return x >> 08; } static ulong SZR09(ulong x) { return x >> 09; } static ulong SZR10(ulong x) { return x >> 10; } static ulong SZR11(ulong x) { return x >> 11; } static ulong SZR12(ulong x) { return x >> 12; } static ulong SZR13(ulong x) { return x >> 13; } static ulong SZR14(ulong x) { return x >> 14; } static ulong SZR15(ulong x) { return x >> 15; } static ulong SZR16(ulong x) { return x >> 16; } static ulong SZR17(ulong x) { return x >> 17; } static ulong SZR18(ulong x) { return x >> 18; } static ulong SZR19(ulong x) { return x >> 19; } static ulong SZR20(ulong x) { return x >> 20; } static ulong SZR21(ulong x) { return x >> 21; } static ulong SZR22(ulong x) { return x >> 22; } static ulong SZR23(ulong x) { return x >> 23; } static ulong SZR24(ulong x) { return x >> 24; } static ulong SZR25(ulong x) { return x >> 25; } static ulong SZR26(ulong x) { return x >> 26; } static ulong SZR27(ulong x) { return x >> 27; } static ulong SZR28(ulong x) { return x >> 28; } static ulong SZR29(ulong x) { return x >> 29; } static ulong SZR30(ulong x) { return x >> 30; } static ulong SZR31(ulong x) { return x >> 31; } static ulong SZR32(ulong x) { return x >> 32; } static ulong SZR33(ulong x) { return x >> 33; } static ulong SZR34(ulong x) { return x >> 34; } static ulong SZR35(ulong x) { return x >> 35; } static ulong SZR36(ulong x) { return x >> 36; } static ulong SZR37(ulong x) { return x >> 37; } static ulong SZR38(ulong x) { return x >> 38; } static ulong SZR39(ulong x) { return x >> 39; } static ulong SZR40(ulong x) { return x >> 40; } static ulong SZR41(ulong x) { return x >> 41; } static ulong SZR42(ulong x) { return x >> 42; } static ulong SZR43(ulong x) { return x >> 43; } static ulong SZR44(ulong x) { return x >> 44; } static ulong SZR45(ulong x) { return x >> 45; } static ulong SZR46(ulong x) { return x >> 46; } static ulong SZR47(ulong x) { return x >> 47; } static ulong SZR48(ulong x) { return x >> 48; } static ulong SZR49(ulong x) { return x >> 49; } static ulong SZR50(ulong x) { return x >> 50; } static ulong SZR51(ulong x) { return x >> 51; } static ulong SZR52(ulong x) { return x >> 52; } static ulong SZR53(ulong x) { return x >> 53; } static ulong SZR54(ulong x) { return x >> 54; } static ulong SZR55(ulong x) { return x >> 55; } static ulong SZR56(ulong x) { return x >> 56; } static ulong SZR57(ulong x) { return x >> 57; } static ulong SZR58(ulong x) { return x >> 58; } static ulong SZR59(ulong x) { return x >> 59; } static ulong SZR60(ulong x) { return x >> 60; } static ulong SZR61(ulong x) { return x >> 61; } static ulong SZR62(ulong x) { return x >> 62; } static ulong SZR63(ulong x) { return x >> 63; } static ulong SZR64(ulong x) { return x >> 64; } static void TestSZR() { ulong x = 1; ulong resK; ulong resV; int s; for (int i = 0; i < 32; i++) { s = 1; resK = SZR01(x); resV = VSZR(x, s); check(resK, resV, "SZR01"); s += 1; resK = SZR02(x); resV = VSZR(x, s); check(resK, resV, "SZR02"); s += 1; resK = SZR03(x); resV = VSZR(x, s); check(resK, resV, "SZR03"); s += 1; resK = SZR04(x); resV = VSZR(x, s); check(resK, resV, "SZR04"); s += 1; resK = SZR05(x); resV = VSZR(x, s); check(resK, resV, "SZR05"); s += 1; resK = SZR06(x); resV = VSZR(x, s); check(resK, resV, "SZR06"); s += 1; resK = SZR07(x); resV = VSZR(x, s); check(resK, resV, "SZR07"); s += 1; resK = SZR08(x); resV = VSZR(x, s); check(resK, resV, "SZR08"); s += 1; resK = SZR09(x); resV = VSZR(x, s); check(resK, resV, "SZR09"); s += 1; resK = SZR10(x); resV = VSZR(x, s); check(resK, resV, "SZR10"); s += 1; resK = SZR11(x); resV = VSZR(x, s); check(resK, resV, "SZR11"); s += 1; resK = SZR12(x); resV = VSZR(x, s); check(resK, resV, "SZR12"); s += 1; resK = SZR13(x); resV = VSZR(x, s); check(resK, resV, "SZR13"); s += 1; resK = SZR14(x); resV = VSZR(x, s); check(resK, resV, "SZR14"); s += 1; resK = SZR15(x); resV = VSZR(x, s); check(resK, resV, "SZR15"); s += 1; resK = SZR16(x); resV = VSZR(x, s); check(resK, resV, "SZR16"); s += 1; resK = SZR17(x); resV = VSZR(x, s); check(resK, resV, "SZR17"); s += 1; resK = SZR18(x); resV = VSZR(x, s); check(resK, resV, "SZR18"); s += 1; resK = SZR19(x); resV = VSZR(x, s); check(resK, resV, "SZR19"); s += 1; resK = SZR20(x); resV = VSZR(x, s); check(resK, resV, "SZR20"); s += 1; resK = SZR21(x); resV = VSZR(x, s); check(resK, resV, "SZR21"); s += 1; resK = SZR22(x); resV = VSZR(x, s); check(resK, resV, "SZR22"); s += 1; resK = SZR23(x); resV = VSZR(x, s); check(resK, resV, "SZR23"); s += 1; resK = SZR24(x); resV = VSZR(x, s); check(resK, resV, "SZR24"); s += 1; resK = SZR25(x); resV = VSZR(x, s); check(resK, resV, "SZR25"); s += 1; resK = SZR26(x); resV = VSZR(x, s); check(resK, resV, "SZR26"); s += 1; resK = SZR27(x); resV = VSZR(x, s); check(resK, resV, "SZR27"); s += 1; resK = SZR28(x); resV = VSZR(x, s); check(resK, resV, "SZR28"); s += 1; resK = SZR29(x); resV = VSZR(x, s); check(resK, resV, "SZR29"); s += 1; resK = SZR30(x); resV = VSZR(x, s); check(resK, resV, "SZR30"); s += 1; resK = SZR31(x); resV = VSZR(x, s); check(resK, resV, "SZR31"); s += 1; resK = SZR32(x); resV = VSZR(x, s); check(resK, resV, "SZR32"); s += 1; resK = SZR33(x); resV = VSZR(x, s); check(resK, resV, "SZR33"); s += 1; resK = SZR34(x); resV = VSZR(x, s); check(resK, resV, "SZR34"); s += 1; resK = SZR35(x); resV = VSZR(x, s); check(resK, resV, "SZR35"); s += 1; resK = SZR36(x); resV = VSZR(x, s); check(resK, resV, "SZR36"); s += 1; resK = SZR37(x); resV = VSZR(x, s); check(resK, resV, "SZR37"); s += 1; resK = SZR38(x); resV = VSZR(x, s); check(resK, resV, "SZR38"); s += 1; resK = SZR39(x); resV = VSZR(x, s); check(resK, resV, "SZR39"); s += 1; resK = SZR40(x); resV = VSZR(x, s); check(resK, resV, "SZR40"); s += 1; resK = SZR41(x); resV = VSZR(x, s); check(resK, resV, "SZR41"); s += 1; resK = SZR42(x); resV = VSZR(x, s); check(resK, resV, "SZR42"); s += 1; resK = SZR43(x); resV = VSZR(x, s); check(resK, resV, "SZR43"); s += 1; resK = SZR44(x); resV = VSZR(x, s); check(resK, resV, "SZR44"); s += 1; resK = SZR45(x); resV = VSZR(x, s); check(resK, resV, "SZR45"); s += 1; resK = SZR46(x); resV = VSZR(x, s); check(resK, resV, "SZR46"); s += 1; resK = SZR47(x); resV = VSZR(x, s); check(resK, resV, "SZR47"); s += 1; resK = SZR48(x); resV = VSZR(x, s); check(resK, resV, "SZR48"); s += 1; resK = SZR49(x); resV = VSZR(x, s); check(resK, resV, "SZR49"); s += 1; resK = SZR50(x); resV = VSZR(x, s); check(resK, resV, "SZR50"); s += 1; resK = SZR51(x); resV = VSZR(x, s); check(resK, resV, "SZR51"); s += 1; resK = SZR52(x); resV = VSZR(x, s); check(resK, resV, "SZR52"); s += 1; resK = SZR53(x); resV = VSZR(x, s); check(resK, resV, "SZR53"); s += 1; resK = SZR54(x); resV = VSZR(x, s); check(resK, resV, "SZR54"); s += 1; resK = SZR55(x); resV = VSZR(x, s); check(resK, resV, "SZR55"); s += 1; resK = SZR56(x); resV = VSZR(x, s); check(resK, resV, "SZR56"); s += 1; resK = SZR57(x); resV = VSZR(x, s); check(resK, resV, "SZR57"); s += 1; resK = SZR58(x); resV = VSZR(x, s); check(resK, resV, "SZR58"); s += 1; resK = SZR59(x); resV = VSZR(x, s); check(resK, resV, "SZR59"); s += 1; resK = SZR60(x); resV = VSZR(x, s); check(resK, resV, "SZR60"); s += 1; resK = SZR61(x); resV = VSZR(x, s); check(resK, resV, "SZR61"); s += 1; resK = SZR62(x); resV = VSZR(x, s); check(resK, resV, "SZR62"); s += 1; resK = SZR63(x); resV = VSZR(x, s); check(resK, resV, "SZR63"); s += 1; resK = SZR64(x); resV = VSZR(x, s); check(resK, resV, "SZR64"); s += 1; x *= 5; } } static int Main(string[] args) { TestSHL(); TestSHR(); TestSZR(); if (!failed) { Console.WriteLine("!!!!!!!!! PASSED !!!!!!!!!!!!"); return 100; } else { Console.WriteLine("!!!!!!!!! FAILED !!!!!!!!!!!!"); return 666; } } }
//----------------------------------------------------------------------- // <copyright company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; #pragma warning disable 1634, 1691 // suppressing PreSharp warnings namespace System.Windows.Input { /// <summary> /// StylusPointDescription describes the properties that a StylusPoint supports. /// </summary> public class StylusPointDescription { /// <summary> /// Internal statics for our magic numbers /// </summary> internal static readonly int RequiredCountOfProperties = 3; internal static readonly int RequiredXIndex = 0; internal static readonly int RequiredYIndex = 1; internal static readonly int RequiredPressureIndex = 2; internal static readonly int MaximumButtonCount = 31; private int _buttonCount = 0; private int _originalPressureIndex = RequiredPressureIndex; private StylusPointPropertyInfo[] _stylusPointPropertyInfos; /// <summary> /// StylusPointDescription /// </summary> public StylusPointDescription() { //implement the default packet description _stylusPointPropertyInfos = new StylusPointPropertyInfo[] { StylusPointPropertyInfoDefaults.X, StylusPointPropertyInfoDefaults.Y, StylusPointPropertyInfoDefaults.NormalPressure }; } /// <summary> /// StylusPointDescription /// </summary> public StylusPointDescription(IEnumerable<StylusPointPropertyInfo> stylusPointPropertyInfos) { if (null == stylusPointPropertyInfos) { throw new ArgumentNullException("stylusPointPropertyInfos"); } List<StylusPointPropertyInfo> infos = new List<StylusPointPropertyInfo>(stylusPointPropertyInfos); if (infos.Count < RequiredCountOfProperties || infos[RequiredXIndex].Id != StylusPointPropertyIds.X || infos[RequiredYIndex].Id != StylusPointPropertyIds.Y || infos[RequiredPressureIndex].Id != StylusPointPropertyIds.NormalPressure) { throw new ArgumentException(SR.Get(SRID.InvalidStylusPointDescription), "stylusPointPropertyInfos"); } // // look for duplicates, validate that buttons are last // List<Guid> seenIds = new List<Guid>(); seenIds.Add(StylusPointPropertyIds.X); seenIds.Add(StylusPointPropertyIds.Y); seenIds.Add(StylusPointPropertyIds.NormalPressure); int buttonCount = 0; for (int x = RequiredCountOfProperties; x < infos.Count; x++) { if (seenIds.Contains(infos[x].Id)) { throw new ArgumentException(SR.Get(SRID.InvalidStylusPointDescriptionDuplicatesFound), "stylusPointPropertyInfos"); } if (infos[x].IsButton) { buttonCount++; } else { //this is not a button, make sure we haven't seen one before if (buttonCount > 0) { throw new ArgumentException(SR.Get(SRID.InvalidStylusPointDescriptionButtonsMustBeLast), "stylusPointPropertyInfos"); } } seenIds.Add(infos[x].Id); } if (buttonCount > MaximumButtonCount) { throw new ArgumentException(SR.Get(SRID.InvalidStylusPointDescriptionTooManyButtons), "stylusPointPropertyInfos"); } _buttonCount = buttonCount; _stylusPointPropertyInfos = infos.ToArray(); } /// <summary> /// StylusPointDescription /// </summary> /// <param name="stylusPointPropertyInfos">stylusPointPropertyInfos</param> /// <param name="originalPressureIndex">originalPressureIndex - does the digitizer really support pressure? If so, the index this was at</param> internal StylusPointDescription(IEnumerable<StylusPointPropertyInfo> stylusPointPropertyInfos, int originalPressureIndex) : this (stylusPointPropertyInfos) { _originalPressureIndex = originalPressureIndex; } /// <summary> /// HasProperty /// </summary> /// <param name="stylusPointProperty">stylusPointProperty</param> public bool HasProperty(StylusPointProperty stylusPointProperty) { if (null == stylusPointProperty) { throw new ArgumentNullException("stylusPointProperty"); } int index = IndexOf(stylusPointProperty.Id); if (-1 == index) { return false; } return true; } /// <summary> /// The count of properties this StylusPointDescription contains /// </summary> public int PropertyCount { get { return _stylusPointPropertyInfos.Length; } } /// <summary> /// GetProperty /// </summary> /// <param name="stylusPointProperty">stylusPointProperty</param> public StylusPointPropertyInfo GetPropertyInfo(StylusPointProperty stylusPointProperty) { if (null == stylusPointProperty) { throw new ArgumentNullException("stylusPointProperty"); } return GetPropertyInfo(stylusPointProperty.Id); } /// <summary> /// GetPropertyInfo /// </summary> /// <param name="guid">guid</param> internal StylusPointPropertyInfo GetPropertyInfo(Guid guid) { int index = IndexOf(guid); if (-1 == index) { //we didn't find it throw new ArgumentException("stylusPointProperty"); } return _stylusPointPropertyInfos[index]; } /// <summary> /// Returns the index of the given StylusPointProperty by ID, or -1 if none is found /// </summary> internal int GetPropertyIndex(Guid guid) { return IndexOf(guid); } /// <summary> /// GetStylusPointProperties /// </summary> public ReadOnlyCollection<StylusPointPropertyInfo> GetStylusPointProperties() { return new ReadOnlyCollection<StylusPointPropertyInfo>(_stylusPointPropertyInfos); } /// <summary> /// GetStylusPointPropertyIdss /// </summary> internal Guid[] GetStylusPointPropertyIds() { Guid[] ret = new Guid[_stylusPointPropertyInfos.Length]; for (int x = 0; x < ret.Length; x++) { ret[x] = _stylusPointPropertyInfos[x].Id; } return ret; } /// <summary> /// Internal helper for determining how many ints in a raw int array /// correspond to one point we get from the input system /// </summary> internal int GetInputArrayLengthPerPoint() { int buttonLength = _buttonCount > 0 ? 1 : 0; int propertyLength = (_stylusPointPropertyInfos.Length - _buttonCount) + buttonLength; if (!this.ContainsTruePressure) { propertyLength--; } return propertyLength; } /// <summary> /// Internal helper for determining how many members a StylusPoint's /// internal int[] should be for additional data /// </summary> internal int GetExpectedAdditionalDataCount() { int buttonLength = _buttonCount > 0 ? 1 : 0; int expectedLength = ((_stylusPointPropertyInfos.Length - _buttonCount) + buttonLength) - 3 /*x, y, p*/; return expectedLength; } /// <summary> /// Internal helper for determining how many ints in a raw int array /// correspond to one point when saving to himetric /// </summary> /// <returns></returns> internal int GetOutputArrayLengthPerPoint() { int length = GetInputArrayLengthPerPoint(); if (!this.ContainsTruePressure) { length++; } return length; } /// <summary> /// Internal helper for determining how many buttons are present /// </summary> internal int ButtonCount { get { return _buttonCount; } } /// <summary> /// Internal helper for determining what bit position the button is at /// </summary> internal int GetButtonBitPosition(StylusPointProperty buttonProperty) { if (!buttonProperty.IsButton) { throw new InvalidOperationException(); } int buttonIndex = 0; for (int x = _stylusPointPropertyInfos.Length - _buttonCount; //start of the buttons x < _stylusPointPropertyInfos.Length; x++) { if (_stylusPointPropertyInfos[x].Id == buttonProperty.Id) { return buttonIndex; } if (_stylusPointPropertyInfos[x].IsButton) { // we're in the buttons, but this isn't the right one, // bump the button index and keep looking buttonIndex++; } } return -1; } /// <summary> /// ContainsTruePressure - true if this StylusPointDescription was instanced /// by a TabletDevice or by ISF serialization that contains NormalPressure /// </summary> internal bool ContainsTruePressure { get { return (_originalPressureIndex != -1); } } /// <summary> /// Internal helper to determine the original pressure index /// </summary> internal int OriginalPressureIndex { get { return _originalPressureIndex; } } /// <summary> /// Returns true if the two StylusPointDescriptions have the same StylusPointProperties. Metrics are ignored. /// </summary> /// <param name="stylusPointDescription1">stylusPointDescription1</param> /// <param name="stylusPointDescription2">stylusPointDescription2</param> public static bool AreCompatible(StylusPointDescription stylusPointDescription1, StylusPointDescription stylusPointDescription2) { if (stylusPointDescription1 == null || stylusPointDescription2 == null) { throw new ArgumentNullException("stylusPointDescription"); } #pragma warning disable 6506 // if a StylusPointDescription is not null, then _stylusPointPropertyInfos is not null. // // ignore X, Y, Pressure - they are guaranteed to be the first3 members // Debug.Assert( stylusPointDescription1._stylusPointPropertyInfos.Length >= RequiredCountOfProperties && stylusPointDescription1._stylusPointPropertyInfos[0].Id == StylusPointPropertyIds.X && stylusPointDescription1._stylusPointPropertyInfos[1].Id == StylusPointPropertyIds.Y && stylusPointDescription1._stylusPointPropertyInfos[2].Id == StylusPointPropertyIds.NormalPressure); Debug.Assert( stylusPointDescription2._stylusPointPropertyInfos.Length >= RequiredCountOfProperties && stylusPointDescription2._stylusPointPropertyInfos[0].Id == StylusPointPropertyIds.X && stylusPointDescription2._stylusPointPropertyInfos[1].Id == StylusPointPropertyIds.Y && stylusPointDescription2._stylusPointPropertyInfos[2].Id == StylusPointPropertyIds.NormalPressure); if (stylusPointDescription1._stylusPointPropertyInfos.Length != stylusPointDescription2._stylusPointPropertyInfos.Length) { return false; } for (int x = RequiredCountOfProperties; x < stylusPointDescription1._stylusPointPropertyInfos.Length; x++) { if (!StylusPointPropertyInfo.AreCompatible(stylusPointDescription1._stylusPointPropertyInfos[x], stylusPointDescription2._stylusPointPropertyInfos[x])) { return false; } } #pragma warning restore 6506 return true; } /// <summary> /// Returns a new StylusPointDescription with the common StylusPointProperties from both /// </summary> /// <param name="stylusPointDescription">stylusPointDescription</param> /// <param name="stylusPointDescriptionPreserveInfo">stylusPointDescriptionPreserveInfo</param> /// <remarks>The StylusPointProperties from stylusPointDescriptionPreserveInfo will be returned in the new StylusPointDescription</remarks> public static StylusPointDescription GetCommonDescription(StylusPointDescription stylusPointDescription, StylusPointDescription stylusPointDescriptionPreserveInfo) { if (stylusPointDescription == null) { throw new ArgumentNullException("stylusPointDescription"); } if (stylusPointDescriptionPreserveInfo == null) { throw new ArgumentNullException("stylusPointDescriptionPreserveInfo"); } #pragma warning disable 6506 // if a StylusPointDescription is not null, then _stylusPointPropertyInfos is not null. // // ignore X, Y, Pressure - they are guaranteed to be the first3 members // Debug.Assert(stylusPointDescription._stylusPointPropertyInfos.Length >= 3 && stylusPointDescription._stylusPointPropertyInfos[0].Id == StylusPointPropertyIds.X && stylusPointDescription._stylusPointPropertyInfos[1].Id == StylusPointPropertyIds.Y && stylusPointDescription._stylusPointPropertyInfos[2].Id == StylusPointPropertyIds.NormalPressure); Debug.Assert(stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos.Length >= 3 && stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[0].Id == StylusPointPropertyIds.X && stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[1].Id == StylusPointPropertyIds.Y && stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[2].Id == StylusPointPropertyIds.NormalPressure); //add x, y, p List<StylusPointPropertyInfo> commonProperties = new List<StylusPointPropertyInfo>(); commonProperties.Add(stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[0]); commonProperties.Add(stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[1]); commonProperties.Add(stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[2]); //add common properties for (int x = RequiredCountOfProperties; x < stylusPointDescription._stylusPointPropertyInfos.Length; x++) { for (int y = RequiredCountOfProperties; y < stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos.Length; y++) { if (StylusPointPropertyInfo.AreCompatible( stylusPointDescription._stylusPointPropertyInfos[x], stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[y])) { commonProperties.Add(stylusPointDescriptionPreserveInfo._stylusPointPropertyInfos[y]); } } } #pragma warning restore 6506 return new StylusPointDescription(commonProperties); } /// <summary> /// Returns true if this StylusPointDescription is a subset /// of the StylusPointDescription passed in /// </summary> /// <param name="stylusPointDescriptionSuperset">stylusPointDescriptionSuperset</param> /// <returns></returns> public bool IsSubsetOf(StylusPointDescription stylusPointDescriptionSuperset) { if (null == stylusPointDescriptionSuperset) { throw new ArgumentNullException("stylusPointDescriptionSuperset"); } if (stylusPointDescriptionSuperset._stylusPointPropertyInfos.Length < _stylusPointPropertyInfos.Length) { return false; } // // iterate through our local properties and make sure that the // superset contains them // for (int x = 0; x < _stylusPointPropertyInfos.Length; x++) { Guid id = _stylusPointPropertyInfos[x].Id; if (-1 == stylusPointDescriptionSuperset.IndexOf(id)) { return false; } } return true; } /// <summary> /// Returns the index of the given StylusPointProperty, or -1 if none is found /// </summary> /// <param name="propertyId">propertyId</param> private int IndexOf(Guid propertyId) { for (int x = 0; x < _stylusPointPropertyInfos.Length; x++) { if (_stylusPointPropertyInfos[x].Id == propertyId) { return x; } } return -1; } } }
using UnityEngine; using System.Collections; using System; using System.Threading; public class TestingAllCS : MonoBehaviour { public AnimationCurve customAnimationCurve; public Transform pt1; public Transform pt2; public Transform pt3; public Transform pt4; public Transform pt5; public delegate void NextFunc(); private int exampleIter = 0; private string[] exampleFunctions = new string[] { /**/"updateValue3Example", "loopTestClamp", "loopTestPingPong", "moveOnACurveExample", "customTweenExample", "moveExample", "rotateExample", "scaleExample", "updateValueExample", "delayedCallExample", "alphaExample", "moveLocalExample", "rotateAroundExample", "colorExample" }; private bool useEstimatedTime = true; private GameObject ltLogo; private TimingType timingType = TimingType.SteadyNormalTime; private int descrTimeScaleChangeId; private Vector3 origin; public enum TimingType{ SteadyNormalTime, IgnoreTimeScale, HalfTimeScale, VariableTimeScale, Length } void Awake(){ // LeanTween.init(3200); // This line is optional. Here you can specify the maximum number of tweens you will use (the default is 400). This must be called before any use of LeanTween is made for it to be effective. } void Start () { ltLogo = GameObject.Find("LeanTweenLogo"); LeanTween.delayedCall(1f, cycleThroughExamples); origin = ltLogo.transform.position; //LeanTween.move( ltLogo, Vector3.zero, 10f); //LeanTween.delayedCall(2f, pauseNow); //LeanTween.delayedCall(5,loopPause); //LeanTween.delayedCall(8, loopResume); } void pauseNow(){ Time.timeScale = 0f; Debug.Log("pausing"); } void OnGUI(){ string label = useEstimatedTime ? "useEstimatedTime" : "timeScale:"+Time.timeScale; GUI.Label(new Rect(0.03f*Screen.width,0.03f*Screen.height,0.5f*Screen.width,0.3f*Screen.height), label); } void endlessCallback(){ Debug.Log("endless"); } void cycleThroughExamples(){ if(exampleIter==0){ int iter = (int)timingType + 1; if(iter>(int)TimingType.Length) iter = 0; timingType = (TimingType)iter; useEstimatedTime = timingType==TimingType.IgnoreTimeScale; Time.timeScale = useEstimatedTime ? 0 : 1f; // pause the Time Scale to show the effectiveness of the useEstimatedTime feature (this is very usefull with Pause Screens) if(timingType==TimingType.HalfTimeScale) Time.timeScale = 0.5f; if(timingType==TimingType.VariableTimeScale){ descrTimeScaleChangeId = LeanTween.value( gameObject, 0.01f, 10.0f, 3f).setOnUpdate( (float val)=>{ //Debug.Log("timeScale val:"+val); Time.timeScale = val; }).setEase(LeanTweenType.easeInQuad).setUseEstimatedTime(true).setRepeat(-1).id; }else{ Debug.Log("cancel variable time"); LeanTween.cancel( descrTimeScaleChangeId ); } } gameObject.BroadcastMessage( exampleFunctions[ exampleIter ] ); // Debug.Log("cycleThroughExamples time:"+Time.time + " useEstimatedTime:"+useEstimatedTime); float delayTime = 1.1f; LeanTween.delayedCall( gameObject, delayTime, cycleThroughExamples).setUseEstimatedTime(useEstimatedTime); exampleIter = exampleIter+1>=exampleFunctions.Length ? 0 : exampleIter + 1; } public void updateValue3Example(){ Debug.Log("updateValue3Example Time:"+Time.time); LeanTween.value( gameObject, updateValue3ExampleCallback, new Vector3(0.0f, 270.0f, 0.0f), new Vector3(30.0f, 270.0f, 180f), 0.5f ).setEase(LeanTweenType.easeInBounce).setRepeat(2).setLoopPingPong().setOnUpdateVector3(updateValue3ExampleUpdate).setUseEstimatedTime(useEstimatedTime); } public void updateValue3ExampleUpdate( Vector3 val){ //Debug.Log("val:"+val+" obj:"+obj); } public void updateValue3ExampleCallback( Vector3 val ){ ltLogo.transform.eulerAngles = val; // Debug.Log("updateValue3ExampleCallback:"+val); } public void loopTestClamp(){ Debug.Log("loopTestClamp Time:"+Time.time); GameObject cube1 = GameObject.Find("Cube1"); cube1.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); LeanTween.scaleZ( cube1, 4.0f, 1.0f).setEase(LeanTweenType.easeOutElastic).setRepeat(7).setLoopClamp().setUseEstimatedTime(useEstimatedTime);// } public void loopTestPingPong(){ Debug.Log("loopTestPingPong Time:"+Time.time); GameObject cube2 = GameObject.Find("Cube2"); cube2.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); LeanTween.scaleY( cube2, 4.0f, 1.0f ).setEase(LeanTweenType.easeOutQuad).setLoopPingPong(4).setUseEstimatedTime(useEstimatedTime); //LeanTween.scaleY( cube2, 4.0f, 1.0f, LeanTween.options().setEaseOutQuad().setRepeat(8).setLoopPingPong().setUseEstimatedTime(useEstimatedTime) ); } public void colorExample(){ GameObject lChar = GameObject.Find("LCharacter"); LeanTween.color( lChar, new Color(1.0f,0.0f,0.0f,0.5f), 0.5f ).setEase(LeanTweenType.easeOutBounce).setRepeat(2).setLoopPingPong().setUseEstimatedTime(useEstimatedTime); } public void moveOnACurveExample(){ Debug.Log("moveOnACurveExample Time:"+Time.time); Vector3[] path = new Vector3[] { origin,pt1.position,pt2.position,pt3.position,pt3.position,pt4.position,pt5.position,origin}; LeanTween.move( ltLogo, path, 1.0f ).setEase(LeanTweenType.easeOutQuad).setOrientToPath(true).setUseEstimatedTime(useEstimatedTime); } public void customTweenExample(){ Debug.Log("customTweenExample starting pos:"+ltLogo.transform.position+" origin:"+origin); LeanTween.moveX( ltLogo, -10.0f, 0.5f ).setEase(customAnimationCurve).setUseEstimatedTime(useEstimatedTime); LeanTween.moveX( ltLogo, 0.0f, 0.5f ).setEase(customAnimationCurve).setDelay(0.5f).setUseEstimatedTime(useEstimatedTime); } public void moveExample(){ Debug.Log("moveExample"); LeanTween.move( ltLogo, new Vector3(-2f,-1f,0f), 0.5f).setUseEstimatedTime(useEstimatedTime); LeanTween.move( ltLogo, origin, 0.5f).setDelay(0.5f).setUseEstimatedTime(useEstimatedTime); } public void rotateExample(){ Debug.Log("rotateExample"); Hashtable returnParam = new Hashtable(); returnParam.Add("yo", 5.0); LeanTween.rotate( ltLogo, new Vector3(0f,360f,0f), 1f).setEase(LeanTweenType.easeOutQuad).setOnComplete(rotateFinished).setOnCompleteParam(returnParam).setOnUpdate(rotateOnUpdate).setUseEstimatedTime(useEstimatedTime); } public void rotateOnUpdate( float val ){ //Debug.Log("rotating val:"+val); } public void rotateFinished( object hash ){ Hashtable h = hash as Hashtable; Debug.Log("rotateFinished hash:"+h["yo"]); } public void scaleExample(){ Debug.Log("scaleExample"); Vector3 currentScale = ltLogo.transform.localScale; LeanTween.scale( ltLogo, new Vector3(currentScale.x+0.2f,currentScale.y+0.2f,currentScale.z+0.2f), 1f ).setEase(LeanTweenType.easeOutBounce).setUseEstimatedTime(useEstimatedTime); } public void updateValueExample(){ Debug.Log("updateValueExample"); Hashtable pass = new Hashtable(); pass.Add("message", "hi"); //LeanTween.value( gameObject, updateValueExampleCallback, ltLogo.transform.eulerAngles.y, 270f, 1f ).setEase(LeanTweenType.easeOutElastic).setOnUpdateParam(pass).setUseEstimatedTime(useEstimatedTime); } public void updateValueExampleCallback( float val, object hash ){ // Hashtable h = hash as Hashtable; // Debug.Log("message:"+h["message"]+" val:"+val); Vector3 tmp = ltLogo.transform.eulerAngles; tmp.y = val; ltLogo.transform.eulerAngles = tmp; } public void delayedCallExample(){ Debug.Log("delayedCallExample"); LeanTween.delayedCall(0.5f, delayedCallExampleCallback).setUseEstimatedTime(useEstimatedTime); } public void delayedCallExampleCallback(){ Debug.Log("Delayed function was called"); Vector3 currentScale = ltLogo.transform.localScale; LeanTween.scale( ltLogo, new Vector3(currentScale.x-0.2f,currentScale.y-0.2f,currentScale.z-0.2f), 0.5f ).setEase(LeanTweenType.easeInOutCirc).setUseEstimatedTime(useEstimatedTime); } public void alphaExample(){ Debug.Log("alphaExample"); GameObject lChar = GameObject.Find ("LCharacter"); LeanTween.alpha( lChar, 0.0f, 0.5f ).setUseEstimatedTime(useEstimatedTime); LeanTween.alpha( lChar, 1.0f, 0.5f ).setDelay(0.5f).setUseEstimatedTime(useEstimatedTime); } public void moveLocalExample(){ Debug.Log("moveLocalExample"); GameObject lChar = GameObject.Find ("LCharacter"); Vector3 origPos = lChar.transform.localPosition; LeanTween.moveLocal( lChar, new Vector3(0.0f,2.0f,0.0f), 0.5f ).setUseEstimatedTime(useEstimatedTime); LeanTween.moveLocal( lChar, origPos, 0.5f ).setDelay(0.5f).setUseEstimatedTime(useEstimatedTime); } public void rotateAroundExample(){ Debug.Log("rotateAroundExample"); GameObject lChar = GameObject.Find ("LCharacter"); LeanTween.rotateAround( lChar, Vector3.up, 360.0f, 1.0f ).setUseEstimatedTime(useEstimatedTime); } public void loopPause(){ GameObject cube1 = GameObject.Find("Cube1"); LeanTween.pause(cube1); } public void loopResume(){ GameObject cube1 = GameObject.Find("Cube1"); LeanTween.resume(cube1 ); } public void punchTest(){ LeanTween.moveX( ltLogo, 7.0f, 1.0f ).setEase(LeanTweenType.punch).setUseEstimatedTime(useEstimatedTime); } }
using System.ComponentModel; using Signum.Entities.Basics; using Signum.Entities.Authorization; namespace Signum.Entities.Processes; public class ProcessAlgorithmSymbol : Symbol { private ProcessAlgorithmSymbol() { } public ProcessAlgorithmSymbol(Type declaringType, string fieldName) : base(declaringType, fieldName) { } } [EntityKind(EntityKind.Main, EntityData.Transactional), TicksColumn(false)] public class ProcessEntity : Entity { internal ProcessEntity() { } public ProcessEntity(ProcessAlgorithmSymbol process) { this.Algorithm = process; } public ProcessAlgorithmSymbol Algorithm { get; private set; } public IProcessDataEntity? Data { get; set; } public const string None = "none"; [StringLengthValidator(Min = 3, Max = 100)] public string MachineName { get; set; } [StringLengthValidator(Min = 3, Max = 100)] public string ApplicationName { get; set; } public Lite<IUserEntity> User { get; set; } public ProcessState State { get; set; } public DateTime CreationDate { get; private set; } = Clock.Now; [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? PlannedDate { get; set; } [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? CancelationDate { get; set; } [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? QueuedDate { get; set; } DateTime? executionStart; [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? ExecutionStart { get { return executionStart; } set { if (Set(ref executionStart, value)) Notify(() => ExecutionEnd); } } DateTime? executionEnd; [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? ExecutionEnd { get { return executionEnd; } set { if (Set(ref executionEnd, value)) Notify(() => ExecutionStart); } } static Expression<Func<ProcessEntity, double?>> DurationExpression = log => (double?)(log.ExecutionEnd - log.ExecutionStart)!.Value.TotalMilliseconds; [ExpressionField("DurationExpression")] public double? Duration { get { return ExecutionEnd == null ? null : DurationExpression.Evaluate(this); } } static Expression<Func<ProcessEntity, TimeSpan?>> DurationSpanExpression = log => log.ExecutionEnd - log.ExecutionStart; [ExpressionField("DurationSpanExpression")] public TimeSpan? DurationSpan { get { return ExecutionEnd == null ? null : DurationSpanExpression.Evaluate(this); } } public DateTime? SuspendDate { get; set; } public DateTime? ExceptionDate { get; set; } public Lite<ExceptionEntity>? Exception { get; set; } [NumberBetweenValidator(0, 1), Format("p")] public decimal? Progress { get; set; } [DbType(Size = int.MaxValue)] public string? Status { get; set; } static StateValidator<ProcessEntity, ProcessState> stateValidator = new StateValidator<ProcessEntity, ProcessState> (e => e.State, e => e.PlannedDate, e => e.CancelationDate, e => e.QueuedDate, e => e.ExecutionStart, e => e.ExecutionEnd, e => e.SuspendDate, e => e.Progress, e => e.Status, e => e.ExceptionDate, e => e.Exception, e => e.MachineName, e => e.ApplicationName) { {ProcessState.Created, false, false, false, false, false, false, false, false, false, false, null, null }, {ProcessState.Planned, true, null, null, null, false, null, null, null, null, null , null, null }, {ProcessState.Canceled, null, true, null, null, false, null, null, null, null, null , null, null }, {ProcessState.Queued, null, null, true, false, false, false, false, false, false, false, null, null }, {ProcessState.Executing, null, null, true, true, false, false, true, null, false, false, true, true }, {ProcessState.Suspending,null, null, true, true, false, true, true, null, false, false, true, true }, {ProcessState.Suspended, null, null, true, true, false, true, true, null, false, false, null, null }, {ProcessState.Finished, null, null, true, true, true, false, false, null, false, false, null, null }, {ProcessState.Error, null, null, null, null, null, null, null, null, true, true , null, null }, }; protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(ExecutionStart) || pi.Name == nameof(ExecutionEnd)) { if (this.ExecutionEnd < this.ExecutionStart) return ProcessMessage.ProcessStartIsGreaterThanProcessEnd.NiceToString(); if (this.ExecutionStart == null && this.ExecutionEnd != null) return ProcessMessage.ProcessStartIsNullButProcessEndIsNot.NiceToString(); } return stateValidator.Validate(this, pi) ?? base.PropertyValidation(pi); } public override string ToString() { return State switch { ProcessState.Created => "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Created.NiceToString(), CreationDate), ProcessState.Planned => "{0} {1} for {2}".FormatWith(Algorithm, ProcessState.Planned.NiceToString(), PlannedDate), ProcessState.Canceled => "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Canceled.NiceToString(), CancelationDate), ProcessState.Queued => "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Queued.NiceToString(), QueuedDate), ProcessState.Executing => "{0} {1} since {2}".FormatWith(Algorithm, ProcessState.Executing.NiceToString(), executionStart), ProcessState.Suspending => "{0} {1} since {2}".FormatWith(Algorithm, ProcessState.Suspending.NiceToString(), SuspendDate), ProcessState.Suspended => "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Suspended.NiceToString(), SuspendDate), ProcessState.Finished => "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Finished.NiceToString(), executionEnd), ProcessState.Error => "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Error.NiceToString(), executionEnd), _ => "{0} ??".FormatWith(Algorithm), }; } } public interface IProcessDataEntity : IEntity { } public interface IProcessLineDataEntity : IEntity { } public enum ProcessState { Created, Planned, Canceled, Queued, Executing, Suspending, Suspended, Finished, Error, } [AutoInit] public static class ProcessOperation { public static ExecuteSymbol<ProcessEntity> Save; public static ExecuteSymbol<ProcessEntity> Execute; public static ExecuteSymbol<ProcessEntity> Suspend; public static ExecuteSymbol<ProcessEntity> Cancel; public static ExecuteSymbol<ProcessEntity> Plan; public static ConstructSymbol<ProcessEntity>.From<ProcessEntity> Retry; } [AutoInit] public static class ProcessPermission { public static PermissionSymbol ViewProcessPanel; } public enum ProcessMessage { [Description("Process {0} is not running anymore")] Process0IsNotRunningAnymore, [Description("Process Start is greater than Process End")] ProcessStartIsGreaterThanProcessEnd, [Description("Process Start is null but Process End is not")] ProcessStartIsNullButProcessEndIsNot, Lines, LastProcess, ExceptionLines, [Description("Suspend in the safer way of stoping a running process. Cancel anyway?")] SuspendIsTheSaferWayOfStoppingARunningProcessCancelAnyway } [EntityKind(EntityKind.System, EntityData.Transactional)] public class ProcessExceptionLineEntity : Entity { [DbType(Size = int.MaxValue)] public string? ElementInfo { get; set; } public Lite<IProcessLineDataEntity>? Line { get; set; } public Lite<ProcessEntity> Process { get; set; } public Lite<ExceptionEntity> Exception { get; set; } #pragma warning disable IDE0052 // Remove unread private members static Expression<Func<ProcessExceptionLineEntity, string>> ToStringExpression = pel => "ProcessExceptionLine (" + pel.Id + ")"; [ExpressionField("ToStringExpression")] public override string ToString() => "ProcessExceptionLine (" + (this.IdOrNull == null ? "New" : this.Id.ToString()) + ")"; #pragma warning restore IDE0052 // Remove unread private members }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Dynamic.Utils; using static System.Linq.Expressions.CachedReflectionInfo; using System.Collections; namespace System.Linq.Expressions.Compiler { internal enum VariableStorageKind { Local, Hoisted } /// <summary> /// CompilerScope is the data structure which the Compiler keeps information /// related to compiling scopes. It stores the following information: /// 1. Parent relationship (for resolving variables) /// 2. Information about hoisted variables /// 3. Information for resolving closures /// /// Instances are produced by VariableBinder, which does a tree walk /// looking for scope nodes: LambdaExpression, BlockExpression, and CatchBlock. /// </summary> internal sealed partial class CompilerScope { /// <summary> /// parent scope, if any /// </summary> private CompilerScope _parent; /// <summary> /// The expression node for this scope /// Can be LambdaExpression, BlockExpression, or CatchBlock /// </summary> internal readonly object Node; /// <summary> /// True if this node corresponds to an IL method. /// Can only be true if the Node is a LambdaExpression. /// But inlined lambdas will have it set to false. /// </summary> internal readonly bool IsMethod; /// <summary> /// Does this scope (or any inner scope) close over variables from any /// parent scope? /// Populated by VariableBinder /// </summary> internal bool NeedsClosure; /// <summary> /// Variables defined in this scope, and whether they're hoisted or not /// Populated by VariableBinder /// </summary> internal readonly Dictionary<ParameterExpression, VariableStorageKind> Definitions = new Dictionary<ParameterExpression, VariableStorageKind>(); /// <summary> /// Each variable referenced within this scope, and how often it was referenced /// Populated by VariableBinder /// </summary> internal Dictionary<ParameterExpression, int> ReferenceCount; /// <summary> /// Scopes whose variables were merged into this one /// /// Created lazily as we create hundreds of compiler scopes w/o merging scopes when compiling rules. /// </summary> internal HashSet<BlockExpression> MergedScopes; /// <summary> /// The scope's hoisted locals, if any. /// Provides storage for variables that are referenced from nested lambdas /// </summary> private HoistedLocals _hoistedLocals; /// <summary> /// The closed over hoisted locals /// </summary> private HoistedLocals _closureHoistedLocals; /// <summary> /// Mutable dictionary that maps non-hoisted variables to either local /// slots or argument slots /// </summary> private readonly Dictionary<ParameterExpression, Storage> _locals = new Dictionary<ParameterExpression, Storage>(); internal CompilerScope(object node, bool isMethod) { Node = node; IsMethod = isMethod; IReadOnlyList<ParameterExpression> variables = GetVariables(node); Definitions = new Dictionary<ParameterExpression, VariableStorageKind>(variables.Count); foreach (ParameterExpression v in variables) { Definitions.Add(v, VariableStorageKind.Local); } } /// <summary> /// This scope's hoisted locals, or the closed over locals, if any /// Equivalent to: _hoistedLocals ?? _closureHoistedLocals /// </summary> internal HoistedLocals NearestHoistedLocals { get { return _hoistedLocals ?? _closureHoistedLocals; } } /// <summary> /// Called when entering a lambda/block. Performs all variable allocation /// needed, including creating hoisted locals and IL locals for accessing /// parent locals /// </summary> internal CompilerScope Enter(LambdaCompiler lc, CompilerScope parent) { SetParent(lc, parent); AllocateLocals(lc); if (IsMethod && _closureHoistedLocals != null) { EmitClosureAccess(lc, _closureHoistedLocals); } EmitNewHoistedLocals(lc); if (IsMethod) { EmitCachedVariables(); } return this; } /// <summary> /// Frees unnamed locals, clears state associated with this compiler /// </summary> internal CompilerScope Exit() { // free scope's variables if (!IsMethod) { foreach (Storage storage in _locals.Values) { storage.FreeLocal(); } } // Clear state that is associated with this parent // (because the scope can be reused in another context) CompilerScope parent = _parent; _parent = null; _hoistedLocals = null; _closureHoistedLocals = null; _locals.Clear(); return parent; } #region RuntimeVariablesExpression support internal void EmitVariableAccess(LambdaCompiler lc, ReadOnlyCollection<ParameterExpression> vars) { if (NearestHoistedLocals != null && vars.Count > 0) { // Find what array each variable is on & its index var indexes = new ArrayBuilder<long>(vars.Count); foreach (ParameterExpression variable in vars) { // For each variable, find what array it's defined on ulong parents = 0; HoistedLocals locals = NearestHoistedLocals; while (!locals.Indexes.ContainsKey(variable)) { parents++; locals = locals.Parent; Debug.Assert(locals != null); } // combine the number of parents we walked, with the // real index of variable to get the index to emit. ulong index = (parents << 32) | (uint)locals.Indexes[variable]; indexes.UncheckedAdd((long)index); } EmitGet(NearestHoistedLocals.SelfVariable); lc.EmitConstantArray(indexes.ToArray()); lc.IL.Emit(OpCodes.Call, RuntimeOps_CreateRuntimeVariables_ObjectArray_Int64Array); } else { // No visible variables lc.IL.Emit(OpCodes.Call, RuntimeOps_CreateRuntimeVariables); } } #endregion #region Variable access /// <summary> /// Adds a new virtual variable corresponding to an IL local /// </summary> internal void AddLocal(LambdaCompiler gen, ParameterExpression variable) { _locals.Add(variable, new LocalStorage(gen, variable)); } internal void EmitGet(ParameterExpression variable) { ResolveVariable(variable).EmitLoad(); } internal void EmitSet(ParameterExpression variable) { ResolveVariable(variable).EmitStore(); } internal void EmitAddressOf(ParameterExpression variable) { ResolveVariable(variable).EmitAddress(); } private Storage ResolveVariable(ParameterExpression variable) { return ResolveVariable(variable, NearestHoistedLocals); } /// <summary> /// Resolve a local variable in this scope or a closed over scope /// Throws if the variable is not defined /// </summary> private Storage ResolveVariable(ParameterExpression variable, HoistedLocals hoistedLocals) { // Search IL locals and arguments, but only in this lambda for (CompilerScope s = this; s != null; s = s._parent) { Storage storage; if (s._locals.TryGetValue(variable, out storage)) { return storage; } // if this is a lambda, we're done if (s.IsMethod) { break; } } // search hoisted locals for (HoistedLocals h = hoistedLocals; h != null; h = h.Parent) { int index; if (h.Indexes.TryGetValue(variable, out index)) { return new ElementBoxStorage( ResolveVariable(h.SelfVariable, hoistedLocals), index, variable ); } } // // If this is an unbound variable in the lambda, the error will be // thrown from VariableBinder. So an error here is generally caused // by an internal error, e.g. a scope was created but it bypassed // VariableBinder. // throw Error.UndefinedVariable(variable.Name, variable.Type, CurrentLambdaName); } #endregion private void SetParent(LambdaCompiler lc, CompilerScope parent) { Debug.Assert(_parent == null && parent != this); _parent = parent; if (NeedsClosure && _parent != null) { _closureHoistedLocals = _parent.NearestHoistedLocals; } ReadOnlyCollection<ParameterExpression> hoistedVars = GetVariables().Where(p => Definitions[p] == VariableStorageKind.Hoisted).ToReadOnly(); if (hoistedVars.Count > 0) { _hoistedLocals = new HoistedLocals(_closureHoistedLocals, hoistedVars); AddLocal(lc, _hoistedLocals.SelfVariable); } } // Emits creation of the hoisted local storage private void EmitNewHoistedLocals(LambdaCompiler lc) { if (_hoistedLocals == null) { return; } // create the array lc.IL.EmitPrimitive(_hoistedLocals.Variables.Count); lc.IL.Emit(OpCodes.Newarr, typeof(object)); // initialize all elements int i = 0; foreach (ParameterExpression v in _hoistedLocals.Variables) { // array[i] = new StrongBox<T>(...); lc.IL.Emit(OpCodes.Dup); lc.IL.EmitPrimitive(i++); Type boxType = typeof(StrongBox<>).MakeGenericType(v.Type); int index; if (IsMethod && (index = lc.Parameters.IndexOf(v)) >= 0) { // array[i] = new StrongBox<T>(argument); lc.EmitLambdaArgument(index); lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(new Type[] { v.Type })); } else if (v == _hoistedLocals.ParentVariable) { // array[i] = new StrongBox<T>(closure.Locals); ResolveVariable(v, _closureHoistedLocals).EmitLoad(); lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(new Type[] { v.Type })); } else { // array[i] = new StrongBox<T>(); lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(Type.EmptyTypes)); } // if we want to cache this into a local, do it now if (ShouldCache(v)) { lc.IL.Emit(OpCodes.Dup); CacheBoxToLocal(lc, v); } lc.IL.Emit(OpCodes.Stelem_Ref); } // store it EmitSet(_hoistedLocals.SelfVariable); } // If hoisted variables are referenced "enough", we cache the // StrongBox<T> in an IL local, which saves an array index and a cast // when we go to look it up later private void EmitCachedVariables() { if (ReferenceCount == null) { return; } foreach (KeyValuePair<ParameterExpression, int> refCount in ReferenceCount) { if (ShouldCache(refCount.Key, refCount.Value)) { var storage = ResolveVariable(refCount.Key) as ElementBoxStorage; if (storage != null) { storage.EmitLoadBox(); CacheBoxToLocal(storage.Compiler, refCount.Key); } } } } private bool ShouldCache(ParameterExpression v, int refCount) { // This caching is too aggressive in the face of conditionals and // switch. Also, it is too conservative for variables used inside // of loops. return refCount > 2 && !_locals.ContainsKey(v); } private bool ShouldCache(ParameterExpression v) { if (ReferenceCount == null) { return false; } int refCount; return ReferenceCount.TryGetValue(v, out refCount) && ShouldCache(v, refCount); } private void CacheBoxToLocal(LambdaCompiler lc, ParameterExpression v) { Debug.Assert(ShouldCache(v) && !_locals.ContainsKey(v)); var local = new LocalBoxStorage(lc, v); local.EmitStoreBox(); _locals.Add(v, local); } // Creates IL locals for accessing closures private void EmitClosureAccess(LambdaCompiler lc, HoistedLocals locals) { if (locals == null) { return; } EmitClosureToVariable(lc, locals); while ((locals = locals.Parent) != null) { ParameterExpression v = locals.SelfVariable; var local = new LocalStorage(lc, v); local.EmitStore(ResolveVariable(v)); _locals.Add(v, local); } } private void EmitClosureToVariable(LambdaCompiler lc, HoistedLocals locals) { lc.EmitClosureArgument(); lc.IL.Emit(OpCodes.Ldfld, Closure_Locals); AddLocal(lc, locals.SelfVariable); EmitSet(locals.SelfVariable); } // Allocates slots for IL locals or IL arguments private void AllocateLocals(LambdaCompiler lc) { foreach (ParameterExpression v in GetVariables()) { if (Definitions[v] == VariableStorageKind.Local) { // // If v is in lc.Parameters, it is a parameter. // Otherwise, it is a local variable. // // Also, for inlined lambdas we'll create a local, which // is possibly a byref local if the parameter is byref. // Storage s; if (IsMethod && lc.Parameters.Contains(v)) { s = new ArgumentStorage(lc, v); } else { s = new LocalStorage(lc, v); } _locals.Add(v, s); } } } private IEnumerable<ParameterExpression> GetVariables() => MergedScopes == null ? GetVariables(Node) : GetVariablesIncludingMerged(); private IEnumerable<ParameterExpression> GetVariablesIncludingMerged() { foreach (ParameterExpression param in GetVariables(Node)) { yield return param; } foreach (BlockExpression scope in MergedScopes) { foreach (ParameterExpression param in scope.Variables) { yield return param; } } } private static IReadOnlyList<ParameterExpression> GetVariables(object scope) { var lambda = scope as LambdaExpression; if (lambda != null) { return new ParameterList(lambda); } var block = scope as BlockExpression; if (block != null) { return block.Variables; } return new[] { ((CatchBlock)scope).Variable }; } private string CurrentLambdaName { get { CompilerScope s = this; while (s != null) { var lambda = s.Node as LambdaExpression; if (lambda != null) { return lambda.Name; } s = s._parent; } throw ContractUtils.Unreachable; } } } internal static class ParameterProviderExtensions { public static int IndexOf(this IParameterProvider provider, ParameterExpression parameter) { for (int i = 0, n = provider.ParameterCount; i < n; i++) { if (provider.GetParameter(i) == parameter) { return i; } } return -1; } public static bool Contains(this IParameterProvider provider, ParameterExpression parameter) { return provider.IndexOf(parameter) >= 0; } } internal sealed class ParameterList : IReadOnlyList<ParameterExpression> { private readonly IParameterProvider _provider; public ParameterList(IParameterProvider provider) { _provider = provider; } public ParameterExpression this[int index] { get { return _provider.GetParameter(index); } } public int Count => _provider.ParameterCount; public IEnumerator<ParameterExpression> GetEnumerator() { for (int i = 0, n = _provider.ParameterCount; i < n; i++) { yield return _provider.GetParameter(i); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using Encog.MathUtil.RBF; using Encog.Util; namespace Encog.Neural.SOM.Training.Neighborhood { /// <summary> /// Implements a multi-dimensional RBF neighborhood function. /// </summary> /// public class NeighborhoodRBF : INeighborhoodFunction { /// <summary> /// The radial basis function to use. /// </summary> /// private readonly IRadialBasisFunction _rbf; /// <summary> /// The size of each dimension. /// </summary> /// private readonly int[] _size; /// <summary> /// The displacement of each dimension, when mapping the dimensions /// to a 1d array. /// </summary> /// private int[] _displacement; /// <summary> /// Construct a 2d neighborhood function based on the sizes for the /// x and y dimensions. /// </summary> /// /// <param name="type">The RBF type to use.</param> /// <param name="x">The size of the x-dimension.</param> /// <param name="y">The size of the y-dimension.</param> public NeighborhoodRBF(RBFEnum type, int x, int y) { var size = new int[2]; size[0] = x; size[1] = y; var centerArray = new double[2]; centerArray[0] = 0; centerArray[1] = 0; var widthArray = new double[2]; widthArray[0] = 1; widthArray[1] = 1; switch (type) { case RBFEnum.Gaussian: _rbf = new GaussianFunction(2); break; case RBFEnum.InverseMultiquadric: _rbf = new InverseMultiquadricFunction(2); break; case RBFEnum.Multiquadric: _rbf = new MultiquadricFunction(2); break; case RBFEnum.MexicanHat: _rbf = new MexicanHatFunction(2); break; } _rbf.Width = 1; EngineArray.ArrayCopy(centerArray, _rbf.Centers); _size = size; CalculateDisplacement(); } /// <summary> /// Construct a multi-dimensional neighborhood function. /// </summary> /// /// <param name="size">The sizes of each dimension.</param> /// <param name="type">The RBF type to use.</param> public NeighborhoodRBF(int[] size, RBFEnum type) { switch (type) { case RBFEnum.Gaussian: _rbf = new GaussianFunction(2); break; case RBFEnum.InverseMultiquadric: _rbf = new InverseMultiquadricFunction(2); break; case RBFEnum.Multiquadric: _rbf = new MultiquadricFunction(2); break; case RBFEnum.MexicanHat: _rbf = new MexicanHatFunction(2); break; } _size = size; CalculateDisplacement(); } /// <value>The RBF to use.</value> public IRadialBasisFunction RBF { get { return _rbf; } } #region INeighborhoodFunction Members /// <summary> /// Calculate the value for the multi RBF function. /// </summary> /// /// <param name="currentNeuron">The current neuron.</param> /// <param name="bestNeuron">The best neuron.</param> /// <returns>A percent that determines the amount of training the current /// neuron should get. Usually 100% when it is the bestNeuron.</returns> public virtual double Function(int currentNeuron, int bestNeuron) { var vector = new double[_displacement.Length]; int[] vectorCurrent = TranslateCoordinates(currentNeuron); int[] vectorBest = TranslateCoordinates(bestNeuron); for (int i = 0; i < vectorCurrent.Length; i++) { vector[i] = vectorCurrent[i] - vectorBest[i]; } return _rbf.Calculate(vector); } /// <summary> /// Set the radius. /// </summary> public virtual double Radius { get { return _rbf.Width; } set { _rbf.Width = value; } } #endregion /// <summary> /// Calculate all of the displacement values. /// </summary> /// private void CalculateDisplacement() { _displacement = new int[_size.Length]; for (int i = 0; i < _size.Length; i++) { int v; if (i == 0) { v = 0; } else if (i == 1) { v = _size[0]; } else { v = _displacement[i - 1]*_size[i - 1]; } _displacement[i] = v; } } /// <summary> /// Translate the specified index into a set of multi-dimensional /// coordinates that represent the same index. This is how the /// multi-dimensional coordinates are translated into a one dimensional /// index for the input neurons. /// </summary> /// /// <param name="index">The index to translate.</param> /// <returns>The multi-dimensional coordinates.</returns> private int[] TranslateCoordinates(int index) { var result = new int[_displacement.Length]; int countingIndex = index; for (int i = _displacement.Length - 1; i >= 0; i--) { int v; if (_displacement[i] > 0) { v = countingIndex/_displacement[i]; } else { v = countingIndex; } countingIndex -= _displacement[i]*v; result[i] = v; } return result; } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, 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 dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations { /// <summary> /// Scan Request Marshaller /// </summary> public class ScanRequestMarshaller : IMarshaller<IRequest, ScanRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ScanRequest)input); } public IRequest Marshall(ScanRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DynamoDBv2"); string target = "DynamoDB_20120810.Scan"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.0"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAttributesToGet()) { context.Writer.WritePropertyName("AttributesToGet"); context.Writer.WriteArrayStart(); foreach(var publicRequestAttributesToGetListValue in publicRequest.AttributesToGet) { context.Writer.Write(publicRequestAttributesToGetListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetConditionalOperator()) { context.Writer.WritePropertyName("ConditionalOperator"); context.Writer.Write(publicRequest.ConditionalOperator); } if(publicRequest.IsSetExclusiveStartKey()) { context.Writer.WritePropertyName("ExclusiveStartKey"); context.Writer.WriteObjectStart(); foreach (var publicRequestExclusiveStartKeyKvp in publicRequest.ExclusiveStartKey) { context.Writer.WritePropertyName(publicRequestExclusiveStartKeyKvp.Key); var publicRequestExclusiveStartKeyValue = publicRequestExclusiveStartKeyKvp.Value; context.Writer.WriteObjectStart(); var marshaller = AttributeValueMarshaller.Instance; marshaller.Marshall(publicRequestExclusiveStartKeyValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetExpressionAttributeNames()) { context.Writer.WritePropertyName("ExpressionAttributeNames"); context.Writer.WriteObjectStart(); foreach (var publicRequestExpressionAttributeNamesKvp in publicRequest.ExpressionAttributeNames) { context.Writer.WritePropertyName(publicRequestExpressionAttributeNamesKvp.Key); var publicRequestExpressionAttributeNamesValue = publicRequestExpressionAttributeNamesKvp.Value; context.Writer.Write(publicRequestExpressionAttributeNamesValue); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetExpressionAttributeValues()) { context.Writer.WritePropertyName("ExpressionAttributeValues"); context.Writer.WriteObjectStart(); foreach (var publicRequestExpressionAttributeValuesKvp in publicRequest.ExpressionAttributeValues) { context.Writer.WritePropertyName(publicRequestExpressionAttributeValuesKvp.Key); var publicRequestExpressionAttributeValuesValue = publicRequestExpressionAttributeValuesKvp.Value; context.Writer.WriteObjectStart(); var marshaller = AttributeValueMarshaller.Instance; marshaller.Marshall(publicRequestExpressionAttributeValuesValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetFilterExpression()) { context.Writer.WritePropertyName("FilterExpression"); context.Writer.Write(publicRequest.FilterExpression); } if(publicRequest.IsSetIndexName()) { context.Writer.WritePropertyName("IndexName"); context.Writer.Write(publicRequest.IndexName); } if(publicRequest.IsSetLimit()) { context.Writer.WritePropertyName("Limit"); context.Writer.Write(publicRequest.Limit); } if(publicRequest.IsSetProjectionExpression()) { context.Writer.WritePropertyName("ProjectionExpression"); context.Writer.Write(publicRequest.ProjectionExpression); } if(publicRequest.IsSetReturnConsumedCapacity()) { context.Writer.WritePropertyName("ReturnConsumedCapacity"); context.Writer.Write(publicRequest.ReturnConsumedCapacity); } if(publicRequest.IsSetScanFilter()) { context.Writer.WritePropertyName("ScanFilter"); context.Writer.WriteObjectStart(); foreach (var publicRequestScanFilterKvp in publicRequest.ScanFilter) { context.Writer.WritePropertyName(publicRequestScanFilterKvp.Key); var publicRequestScanFilterValue = publicRequestScanFilterKvp.Value; context.Writer.WriteObjectStart(); var marshaller = ConditionMarshaller.Instance; marshaller.Marshall(publicRequestScanFilterValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetSegment()) { context.Writer.WritePropertyName("Segment"); context.Writer.Write(publicRequest.Segment); } if(publicRequest.IsSetSelect()) { context.Writer.WritePropertyName("Select"); context.Writer.Write(publicRequest.Select); } if(publicRequest.IsSetTableName()) { context.Writer.WritePropertyName("TableName"); context.Writer.Write(publicRequest.TableName); } if(publicRequest.IsSetTotalSegments()) { context.Writer.WritePropertyName("TotalSegments"); context.Writer.Write(publicRequest.TotalSegments); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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. */ #define Experimental using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using Aurora.DataManager.Migration; using Aurora.Framework; using System.Data.SQLite; using OpenMetaverse; namespace Aurora.DataManager.SQLite { public class SQLiteLoader : DataManagerBase { private SQLiteConnection m_Connection; protected Dictionary<string, FieldInfo> m_Fields = new Dictionary<string, FieldInfo>(); // private static bool m_spammedmessage = false; private static bool m_copiedFile = false; public SQLiteLoader () { if (Environment.OSVersion.Platform == PlatformID.MacOSX || (Environment.OSVersion.Platform == PlatformID.Unix && Environment.OSVersion.Version.Major == 11 && Environment.OSVersion.Version.Minor == 3)) { throw new NotSupportedException ("Mac OSX currently does not support SQLite as a database option."); } try { if (!m_copiedFile) { m_copiedFile = true; if (System.IO.File.Exists("System.Data.SQLite.dll")) System.IO.File.Delete("System.Data.SQLite.dll"); string fileName = System.IntPtr.Size == 4 ? "System.Data.SQLitex86.dll" : "System.Data.SQLitex64.dll"; System.IO.File.Copy(fileName, "System.Data.SQLite.dll", true); } } catch { // if(!m_spammedmessage) // MainConsole.Instance.Output("[SQLite]: Failed to copy SQLite dll file, may have issues with SQLite! (Can be caused by running multiple instances in the same bin, if so, ignore this warning) " + ex.ToString(), log4net.Core.Level.Emergency); // m_spammedmessage = true; } } public override string Identifier { get { return "SQLiteConnector"; } } #region Database public override void ConnectToDatabase(string connectionString, string migratorName, bool validateTables) { string[] s1 = connectionString.Split(new[] { "Data Source=", "," }, StringSplitOptions.RemoveEmptyEntries); if (Path.GetFileName(s1[0]) == s1[0]) //Only add this if we arn't an absolute path already connectionString = connectionString.Replace("Data Source=", "Data Source=" + Util.BasePathCombine("") + "\\"); m_Connection = new SQLiteConnection(connectionString); m_Connection.Open(); var migrationManager = new MigrationManager(this, migratorName, validateTables); migrationManager.DetermineOperation(); migrationManager.ExecuteOperation(); } public override void CloseDatabase() { m_Connection.Close(); } #endregion #region Query protected IDataReader ExecuteReader(SQLiteCommand cmd) { try { var newConnection = (SQLiteConnection) (m_Connection).Clone(); if (newConnection.State != ConnectionState.Open) newConnection.Open(); cmd.Connection = newConnection; SQLiteDataReader reader = cmd.ExecuteReader(); return reader; } catch (SQLiteException ex) { MainConsole.Instance.Warn("[SQLiteDataManager]: Exception processing command: " + cmd.CommandText + ", Exception: " + ex); //throw ex; } catch (Exception ex) { MainConsole.Instance.Warn("[SQLiteDataManager]: Exception processing command: " + cmd.CommandText + ", Exception: " + ex); throw ex; } return null; } protected void PrepReader(ref SQLiteCommand cmd) { try { #if Experimental var newConnection = m_Connection; #else var newConnection = (SQLiteConnection)((ICloneable)m_Connection).Clone(); #endif if (newConnection.State != ConnectionState.Open) newConnection.Open(); cmd.Connection = newConnection; } catch (SQLiteException ex) { MainConsole.Instance.Warn("[SQLiteDataManager]: Exception processing command: " + cmd.CommandText + ", Exception: " + ex); //throw ex; } catch (Exception ex) { MainConsole.Instance.Warn("[SQLiteDataManager]: Exception processing command: " + cmd.CommandText + ", Exception: " + ex); throw ex; } } protected SQLiteCommand PrepReader(string query) { try { /*#if Experimental var newConnection = m_Connection; #else*/ var newConnection = (SQLiteConnection) (m_Connection).Clone(); //#endif if (newConnection.State != ConnectionState.Open) newConnection.Open(); var cmd = newConnection.CreateCommand(); cmd.CommandText = query; return cmd; } catch (SQLiteException) { //throw ex; } catch (Exception ex) { throw ex; } return null; } protected int ExecuteNonQuery(SQLiteCommand cmd) { try { lock (m_Connection) { /*#if Experimental var newConnection = m_Connection; #else*/ var newConnection = (SQLiteConnection) (m_Connection).Clone(); //#endif if (newConnection.State != ConnectionState.Open) newConnection.Open(); cmd.Connection = newConnection; UnescapeSQL(cmd); return cmd.ExecuteNonQuery(); } } catch (SQLiteException ex) { MainConsole.Instance.Warn("[SQLiteDataManager]: Exception processing command: " + cmd.CommandText + ", Exception: " + ex); } catch (Exception ex) { MainConsole.Instance.Warn("[SQLiteDataManager]: Exception processing command: " + cmd.CommandText + ", Exception: " + ex); throw ex; } return 0; } protected IDataReader GetReader(SQLiteCommand cmd) { return ExecuteReader(cmd); } private static void UnescapeSQL(SQLiteCommand cmd) { foreach (SQLiteParameter v in cmd.Parameters) { if (v.Value.ToString().Contains("\\'")) { v.Value = v.Value.ToString().Replace("\\'", "\'"); } if (v.Value.ToString().Contains("\\\"")) { v.Value = v.Value.ToString().Replace("\\\"", "\""); } } } protected void CloseReaderCommand(SQLiteCommand cmd) { cmd.Connection.Close(); cmd.Parameters.Clear(); //cmd.Dispose (); } private void AddParams(ref SQLiteCommand cmd, Dictionary<string, object> ps) { foreach (KeyValuePair<string, object> p in ps) cmd.Parameters.AddWithValue(p.Key, p.Value); } public override List<string> QueryFullData(string whereClause, string table, string wantedValue) { string query = String.Format("select {0} from {1} {2} ", wantedValue, table, whereClause); return QueryFullData2(query); } public override List<string> QueryFullData(string whereClause, QueryTables tables, string wantedValue) { string query = string.Format("SELECT {0} FROM {1} {2} ", wantedValue, tables.ToSQL(), whereClause); return QueryFullData2(query); } private List<string> QueryFullData2(string query) { var cmd = PrepReader(query); using (IDataReader reader = cmd.ExecuteReader()) { var RetVal = new List<string>(); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { RetVal.Add(reader.GetValue(i).ToString()); } } //reader.Close(); CloseReaderCommand(cmd); return RetVal; } } public override IDataReader QueryData(string whereClause, string table, string wantedValue) { string query = String.Format("select {0} from {1} {2}",wantedValue, table, whereClause); return QueryData2(query); } public override IDataReader QueryData(string whereClause, QueryTables tables, string wantedValue) { string query = string.Format("SELECT {0} FROM {1} {2}", wantedValue, tables, whereClause); return QueryData2(query); } private IDataReader QueryData2(string query) { var cmd = PrepReader(query); return cmd.ExecuteReader(); } public override List<string> Query(string[] wantedValue, string table, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { string query = string.Format("SELECT {0} FROM {1}", string.Join(", ", wantedValue), table); return Query2(query, queryFilter, sort, start, count); } public override List<string> Query(string[] wantedValue, QueryTables tables, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { string query = string.Format("SELECT {0} FROM {1} ", string.Join(", ", wantedValue), tables.ToSQL()); return Query2(query, queryFilter, sort, start, count); } private List<string> Query2(string query, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { Dictionary<string, object> ps = new Dictionary<string, object>(); List<string> retVal = new List<string>(); List<string> parts = new List<string>(); if (queryFilter != null && queryFilter.Count > 0) { query += " WHERE " + queryFilter.ToSQL(':', out ps); } if (sort != null && sort.Count > 0) { parts = new List<string>(); foreach (KeyValuePair<string, bool> sortOrder in sort) { parts.Add(string.Format("`{0}` {1}", sortOrder.Key, sortOrder.Value ? "ASC" : "DESC")); } query += " ORDER BY " + string.Join(", ", parts.ToArray()); } if (start.HasValue) { query += " LIMIT " + start.Value.ToString(); if (count.HasValue) { query += ", " + count.Value.ToString(); } } int i = 0; var cmd = PrepReader(query); AddParams(ref cmd, ps); using (IDataReader reader = cmd.ExecuteReader()) { var RetVal = new List<string>(); while (reader.Read()) { for (i = 0; i < reader.FieldCount; i++) { Type r = reader[i].GetType(); RetVal.Add(r == typeof(DBNull) ? null : reader[i].ToString()); } } //reader.Close(); CloseReaderCommand(cmd); return RetVal; } } public override Dictionary<string, List<string>> QueryNames(string[] keyRow, object[] keyValue, string table, string wantedValue) { string query = String.Format("select {0} from {1} where ", wantedValue, table); return QueryNames2(keyRow, keyValue, query); } public override Dictionary<string, List<string>> QueryNames(string[] keyRow, object[] keyValue, QueryTables tables, string wantedValue) { string query = string.Format("SELECT {0} FROM {1} where ", wantedValue, tables.ToSQL()); return QueryNames2(keyRow, keyValue, query); } private Dictionary<string, List<string>> QueryNames2(string[] keyRow, object[] keyValue, string query) { Dictionary<string, object> ps = new Dictionary<string, object>(); int i = 0; foreach (object value in keyValue) { ps[":" + keyRow[i].Replace("`", "")] = value; query += String.Format("{0} = :{1} and ", keyRow[i], keyRow[i].Replace("`", "")); i++; } query = query.Remove(query.Length - 5); var cmd = PrepReader(query); AddParams(ref cmd, ps); using (IDataReader reader = cmd.ExecuteReader()) { var RetVal = new Dictionary<string, List<string>>(); while (reader.Read()) { for (i = 0; i < reader.FieldCount; i++) { Type r = reader[i].GetType(); if (r == typeof (DBNull)) AddValueToList(ref RetVal, reader.GetName(i), null); else AddValueToList(ref RetVal, reader.GetName(i), reader[i].ToString()); } } //reader.Close(); CloseReaderCommand(cmd); return RetVal; } } private void AddValueToList(ref Dictionary<string, List<string>> dic, string key, string value) { if (!dic.ContainsKey(key)) dic.Add(key, new List<string>()); dic[key].Add(value); } #endregion #region Update public override bool Update(string table, Dictionary<string, object> values, Dictionary<string, int> incrementValues, QueryFilter queryFilter, uint? start, uint? count) { if ((values == null || values.Count < 1) && (incrementValues == null || incrementValues.Count < 1)) { MainConsole.Instance.Warn("Update attempted with no values"); return false; } string query = string.Format("UPDATE {0}", table); ; Dictionary<string, object> ps = new Dictionary<string, object>(); string filter = ""; if (queryFilter != null && queryFilter.Count > 0) { filter = " WHERE " + queryFilter.ToSQL(':', out ps); } List<string> parts = new List<string>(); if (values != null) { foreach (KeyValuePair<string, object> value in values) { string key = ":updateSet_" + value.Key.Replace("`", ""); ps[key] = value.Value; parts.Add(string.Format("{0} = {1}", value.Key, key)); } } if (incrementValues != null) { foreach (KeyValuePair<string, int> value in incrementValues) { string key = ":updateSet_increment_" + value.Key.Replace("`", ""); ps[key] = value.Value; parts.Add(string.Format("{0} = {0} + {1}", value.Key, key)); } } query += " SET " + string.Join(", ", parts.ToArray()) + filter; if (start.HasValue) { query += " LIMIT " + start.Value.ToString(); if (count.HasValue) { query += ", " + count.Value.ToString(); } } SQLiteCommand cmd = new SQLiteCommand(query); AddParams(ref cmd, ps); try { ExecuteNonQuery(cmd); } catch (SQLiteException e) { MainConsole.Instance.Error("[SQLiteLoader] Update(" + query + "), " + e); } CloseReaderCommand(cmd); return true; } #endregion #region Insert public override bool InsertMultiple(string table, List<object[]> values) { var cmd = new SQLiteCommand(); string query = String.Format("insert into {0} select ", table); int a = 0; foreach (object[] value in values) { foreach (object v in value) { query += ":" + Util.ConvertDecString(a) + ","; cmd.Parameters.AddWithValue(Util.ConvertDecString(a++), v is byte[] ? Utils.BytesToString((byte[])v) : v); } query = query.Remove(query.Length - 1); query += " union all select "; } query = query.Remove(query.Length - (" union all select ").Length); cmd.CommandText = query; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); return true; } public override bool Insert(string table, object[] values) { var cmd = new SQLiteCommand(); string query = ""; query = String.Format("insert into {0} values(", table); int a = 0; foreach (object value in values) { query += ":" + Util.ConvertDecString(a) + ","; cmd.Parameters.AddWithValue(Util.ConvertDecString(a++), value is byte[] ? Utils.BytesToString((byte[])value) : value); } query = query.Remove(query.Length - 1); query += ")"; cmd.CommandText = query; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); return true; } private bool InsertOrReplace(string table, Dictionary<string, object> row, bool insert) { SQLiteCommand cmd = new SQLiteCommand(); string query = (insert ? "INSERT" : "REPLACE") + " INTO " + table + " (" + string.Join(", ", row.Keys.ToArray<string>()) + ")"; List<string> ps = new List<string>(); foreach (KeyValuePair<string, object> field in row) { string key = ":" + field.Key.Replace("`", ""); ps.Add(key); cmd.Parameters.AddWithValue(key, field.Value); } query += " VALUES( " + string.Join(", ", ps.ToArray<string>()) + " )"; cmd.CommandText = query; try { ExecuteNonQuery(cmd); } catch (Exception e) { MainConsole.Instance.Error("[SQLiteLoader] " + (insert ? "Insert" : "Replace") + "(" + query + "), " + e); } CloseReaderCommand(cmd); return true; } public override bool Insert(string table, Dictionary<string, object> row) { return InsertOrReplace(table, row, true); } public override bool Insert(string table, object[] values, string updateKey, object updateValue) { var cmd = new SQLiteCommand(); Dictionary<string, object> ps = new Dictionary<string, object>(); string query = ""; query = String.Format("insert into {0} values (", table); int i = 0; foreach (object value in values) { ps[":" + Util.ConvertDecString(i)] = value; query = String.Format(query + ":{0},", Util.ConvertDecString(i++)); } query = query.Remove(query.Length - 1); query += ")"; cmd.CommandText = query; AddParams(ref cmd, ps); try { ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } //Execute the update then... catch (Exception) { cmd = new SQLiteCommand(); query = String.Format("UPDATE {0} SET {1} = '{2}'", table, updateKey, updateValue); cmd.CommandText = query; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } return true; } public override bool InsertSelect(string tableA, string[] fieldsA, string tableB, string[] valuesB) { SQLiteCommand cmd = PrepReader(string.Format("INSERT INTO {0}{1} SELECT {2} FROM {3}", tableA, (fieldsA.Length > 0 ? " (" + string.Join(", ", fieldsA) + ")" : ""), string.Join(", ", valuesB), tableB )); try { ExecuteNonQuery(cmd); } catch (Exception e) { MainConsole.Instance.Error("[SQLiteLoader] INSERT .. SELECT (" + cmd.CommandText + "), " + e); } CloseReaderCommand(cmd); return true; } #endregion #region REPLACE INTO public override bool Replace(string table, Dictionary<string, object> row) { return InsertOrReplace(table, row, false); } #endregion #region Delete public override bool DeleteByTime(string table, string key) { QueryFilter filter = new QueryFilter(); filter.andLessThanEqFilters["(datetime(" + key.Replace("`", "") + ", 'localtime') - datetime('now', 'localtime'))"] = 0; return Delete(table, filter); } public override bool Delete(string table, QueryFilter queryFilter) { Dictionary<string, object> ps = new Dictionary<string, object>(); string query = "DELETE FROM " + table + (queryFilter != null ? (" WHERE " + queryFilter.ToSQL(':', out ps)) : ""); SQLiteCommand cmd = new SQLiteCommand(query); AddParams(ref cmd, ps); try { ExecuteNonQuery(cmd); } catch (Exception e) { MainConsole.Instance.Error("[SQLiteDataManager] Delete(" + query + "), " + e); return false; } CloseReaderCommand(cmd); return true; } #endregion public override string ConCat(string[] toConcat) { #if (!ISWIN) string returnValue = ""; foreach (string s in toConcat) returnValue = returnValue + (s + " || "); #else string returnValue = toConcat.Aggregate("", (current, s) => current + (s + " || ")); #endif return returnValue.Substring(0, returnValue.Length - 4); } #region Tables public override bool TableExists(string tableName) { var cmd = PrepReader("SELECT name FROM SQLite_master WHERE name='" + tableName + "'"); using (IDataReader rdr = cmd.ExecuteReader()) { if (rdr.Read()) { CloseReaderCommand(cmd); return true; } else { CloseReaderCommand(cmd); return false; } } } public override void CreateTable(string table, ColumnDefinition[] columns, IndexDefinition[] indices) { if (TableExists(table)) { throw new DataManagerException("Trying to create a table with name of one that already exists."); } IndexDefinition primary = null; foreach (IndexDefinition index in indices) { if (index.Type == IndexType.Primary) { primary = index; break; } } List<string> columnDefinition = new List<string>(); bool has_auto_increment = false; foreach (ColumnDefinition column in columns) { if (column.Type.auto_increment) { has_auto_increment = true; } columnDefinition.Add(column.Name + " " + GetColumnTypeStringSymbol(column.Type)); } if (!has_auto_increment && primary != null && primary.Fields.Length > 0) { columnDefinition.Add("PRIMARY KEY (" + string.Join(", ", primary.Fields) + ")"); } var cmd = new SQLiteCommand { CommandText = string.Format("create table " + table + " ({0})", string.Join(", ", columnDefinition.ToArray())) }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); if (indices.Length >= 1 && (primary == null || indices.Length >= 2)) { columnDefinition = new List<string>(primary != null ? indices.Length : indices.Length - 1); // reusing existing variable for laziness uint i = 0; foreach (IndexDefinition index in indices) { if (index.Type == IndexType.Primary || index.Fields.Length < 1) { continue; } i++; columnDefinition.Add("CREATE " + (index.Type == IndexType.Unique ? "UNIQUE " : string.Empty) + "INDEX idx_" + table + "_" + i.ToString() + " ON " + table + "(" + string.Join(", ", index.Fields) + ")"); } foreach (string query in columnDefinition) { cmd = new SQLiteCommand { CommandText = query }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } } } public override void UpdateTable(string table, ColumnDefinition[] columns, IndexDefinition[] indices, Dictionary<string, string> renameColumns) { if (!TableExists(table)) { throw new DataManagerException("Trying to update a table with name of one that does not exist."); } List<ColumnDefinition> oldColumns = ExtractColumnsFromTable(table); Dictionary<string, ColumnDefinition> sameColumns = new Dictionary<string, ColumnDefinition>(); foreach (ColumnDefinition column in oldColumns) { #if (!ISWIN) foreach (ColumnDefinition innercolumn in columns) { if (innercolumn.Name.ToLower() == column.Name.ToLower() || renameColumns.ContainsKey(column.Name) && renameColumns[column.Name].ToLower() == innercolumn.Name.ToLower()) { sameColumns.Add(column.Name, column); break; } } #else if (columns.Any(innercolumn => innercolumn.Name.ToLower() == column.Name.ToLower() || renameColumns.ContainsKey(column.Name) && renameColumns[column.Name].ToLower() == innercolumn.Name.ToLower())) { sameColumns.Add(column.Name, column); } #endif } string renamedTempTableColumnDefinition = string.Empty; string renamedTempTableColumn = string.Empty; foreach (ColumnDefinition column in oldColumns) { if (renamedTempTableColumnDefinition != string.Empty) { renamedTempTableColumnDefinition += ", "; renamedTempTableColumn += ", "; } renamedTempTableColumn += column.Name; renamedTempTableColumnDefinition += column.Name + " " + GetColumnTypeStringSymbol(column.Type); } var cmd = new SQLiteCommand { CommandText = "CREATE TABLE " + table + "__temp(" + renamedTempTableColumnDefinition + ");" }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); cmd = new SQLiteCommand { CommandText = "INSERT INTO " + table + "__temp SELECT " + renamedTempTableColumn + " from " + table + ";" }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); cmd = new SQLiteCommand { CommandText = "drop table " + table }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); List<string> newTableColumnDefinition = new List<string>(columns.Length); IndexDefinition primary = null; foreach (IndexDefinition index in indices) { if (index.Type == IndexType.Primary) { primary = index; break; } } bool has_auto_increment = false; foreach (ColumnDefinition column in columns) { if (column.Type.auto_increment) { has_auto_increment = true; } newTableColumnDefinition.Add(column.Name + " " + GetColumnTypeStringSymbol(column.Type)); } if (!has_auto_increment && primary != null && primary.Fields.Length > 0){ newTableColumnDefinition.Add("PRIMARY KEY (" + string.Join(", ", primary.Fields) + ")"); } cmd = new SQLiteCommand { CommandText = string.Format("create table " + table + " ({0}) ", string.Join(", ", newTableColumnDefinition.ToArray())) }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); if (indices.Length >= 1 && (primary == null || indices.Length >= 2)) { newTableColumnDefinition = new List<string>(primary != null ? indices.Length : indices.Length - 1); // reusing existing variable for laziness uint i = 0; foreach (IndexDefinition index in indices) { if (index.Type == IndexType.Primary || index.Fields.Length < 1) { continue; } i++; newTableColumnDefinition.Add("CREATE " + (index.Type == IndexType.Unique ? "UNIQUE " : string.Empty) + "INDEX idx_" + table + "_" + i.ToString() + " ON " + table + "(" + string.Join(", ", index.Fields) + ")"); } foreach (string query in newTableColumnDefinition) { cmd = new SQLiteCommand { CommandText = query }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } } string InsertFromTempTableColumnDefinition = string.Empty; string InsertIntoFromTempTableColumnDefinition = string.Empty; foreach (ColumnDefinition column in sameColumns.Values) { if (InsertFromTempTableColumnDefinition != string.Empty) { InsertFromTempTableColumnDefinition += ", "; } if (InsertIntoFromTempTableColumnDefinition != string.Empty) { InsertIntoFromTempTableColumnDefinition += ", "; } if (renameColumns.ContainsKey(column.Name)) InsertIntoFromTempTableColumnDefinition += renameColumns[column.Name]; else InsertIntoFromTempTableColumnDefinition += column.Name; InsertFromTempTableColumnDefinition += column.Name; } cmd = new SQLiteCommand { CommandText = "INSERT INTO " + table + " (" + InsertIntoFromTempTableColumnDefinition + ") SELECT " + InsertFromTempTableColumnDefinition + " from " + table + "__temp;" }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); cmd = new SQLiteCommand { CommandText = "drop table " + table + "__temp" }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } public override string GetColumnTypeStringSymbol(ColumnTypes type) { switch (type) { case ColumnTypes.Double: return "DOUBLE"; case ColumnTypes.Integer11: return "INT(11)"; case ColumnTypes.Integer30: return "INT(30)"; case ColumnTypes.UInteger11: return "INT(11) UNSIGNED"; case ColumnTypes.UInteger30: return "INT(30) UNSIGNED"; case ColumnTypes.Char36: return "CHAR(36)"; case ColumnTypes.Char32: return "CHAR(32)"; case ColumnTypes.Char5: return "CHAR(5)"; case ColumnTypes.String: return "TEXT"; case ColumnTypes.String1: return "VARCHAR(1)"; case ColumnTypes.String2: return "VARCHAR(2)"; case ColumnTypes.String16: return "VARCHAR(16)"; case ColumnTypes.String30: return "VARCHAR(30)"; case ColumnTypes.String32: return "VARCHAR(32)"; case ColumnTypes.String36: return "VARCHAR(36)"; case ColumnTypes.String45: return "VARCHAR(45)"; case ColumnTypes.String50: return "VARCHAR(50)"; case ColumnTypes.String64: return "VARCHAR(64)"; case ColumnTypes.String128: return "VARCHAR(128)"; case ColumnTypes.String100: return "VARCHAR(100)"; case ColumnTypes.String10: return "VARCHAR(10)"; case ColumnTypes.String255: return "VARCHAR(255)"; case ColumnTypes.String512: return "VARCHAR(512)"; case ColumnTypes.String1024: return "VARCHAR(1024)"; case ColumnTypes.String8196: return "VARCHAR(8196)"; case ColumnTypes.Blob: return "blob"; case ColumnTypes.LongBlob: return "blob"; case ColumnTypes.Text: return "VARCHAR(512)"; case ColumnTypes.MediumText: return "VARCHAR(512)"; case ColumnTypes.LongText: return "VARCHAR(512)"; case ColumnTypes.Date: return "DATE"; case ColumnTypes.DateTime: return "DATETIME"; case ColumnTypes.Float: return "float"; case ColumnTypes.Unknown: return ""; case ColumnTypes.TinyInt1: return "TINYINT(1)"; case ColumnTypes.TinyInt4: return "TINYINT(4)"; default: throw new DataManagerException("Unknown column type."); } } public override string GetColumnTypeStringSymbol(ColumnTypeDef coldef) { string symbol; switch (coldef.Type) { case ColumnType.Blob: case ColumnType.LongBlob: symbol = "BLOB"; break; case ColumnType.Boolean: symbol = "TINYINT(1)"; break; case ColumnType.Char: symbol = "CHAR(" + coldef.Size + ")"; break; case ColumnType.Date: symbol = "DATE"; break; case ColumnType.DateTime: symbol = "DATETIME"; break; case ColumnType.Double: symbol = "DOUBLE"; break; case ColumnType.Float: symbol = "FLOAT"; break; case ColumnType.Integer: if (!coldef.auto_increment) { symbol = "INT(" + coldef.Size + ")"; } else { symbol = "INTEGER PRIMARY KEY AUTOINCREMENT"; } break; case ColumnType.TinyInt: symbol = "TINYINT(" + coldef.Size + ")"; break; case ColumnType.String: symbol = "VARCHAR(" + coldef.Size + ")"; break; case ColumnType.Text: case ColumnType.MediumText: case ColumnType.LongText: symbol = "TEXT"; break; case ColumnType.UUID: symbol = "CHAR(36)"; break; default: throw new DataManagerException("Unknown column type."); } return symbol + (coldef.isNull ? " NULL" : " NOT NULL") + ((coldef.isNull && coldef.defaultValue == null) ? " DEFAULT NULL" : (coldef.defaultValue != null ? " DEFAULT '" + coldef.defaultValue.MySqlEscape() + "'" : "")); } protected override List<ColumnDefinition> ExtractColumnsFromTable(string tableName) { List<ColumnDefinition> defs = new List<ColumnDefinition>(); IndexDefinition primary = null; bool isFaux = false; foreach (KeyValuePair<string, IndexDefinition> index in ExtractIndicesFromTable(tableName)) { if (index.Value.Type == IndexType.Primary) { isFaux = index.Key == "#fauxprimary#"; primary = index.Value; break; } } var cmd = PrepReader(string.Format("PRAGMA table_info({0})", tableName)); using (IDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { var name = rdr["name"]; var type = rdr["type"]; object defaultValue = rdr["dflt_value"]; ColumnTypeDef typeDef = ConvertTypeToColumnType(type.ToString()); typeDef.isNull = uint.Parse(rdr["notnull"].ToString()) == 0; typeDef.defaultValue = defaultValue.GetType() == typeof(System.DBNull) ? null : defaultValue.ToString(); if ( uint.Parse(rdr["pk"].ToString()) == 1 && primary != null && isFaux == true && primary.Fields.Length == 1 && primary.Fields[0].ToLower() == name.ToString().ToLower() && (typeDef.Type == ColumnType.Integer || typeDef.Type == ColumnType.TinyInt) ) { typeDef.auto_increment = true; } defs.Add(new ColumnDefinition { Name = name.ToString(), Type = typeDef, }); } rdr.Close(); } CloseReaderCommand(cmd); return defs; } protected override Dictionary<string, IndexDefinition> ExtractIndicesFromTable(string tableName) { Dictionary<string, IndexDefinition> defs = new Dictionary<string, IndexDefinition>(); IndexDefinition primary = new IndexDefinition { Fields = new string[]{}, Type = IndexType.Primary }; string autoIncrementField = null; List<string> fields = new List<string>(); SQLiteCommand cmd = PrepReader(string.Format("PRAGMA table_info({0})", tableName)); using (IDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { if (uint.Parse(rdr["pk"].ToString()) > 0) { fields.Add(rdr["name"].ToString()); if (autoIncrementField == null) { ColumnTypeDef typeDef = ConvertTypeToColumnType(rdr["type"].ToString()); if (typeDef.Type == ColumnType.Integer || typeDef.Type == ColumnType.TinyInt) { autoIncrementField = rdr["name"].ToString(); } } } } rdr.Close(); } CloseReaderCommand(cmd); primary.Fields = fields.ToArray(); cmd = PrepReader(string.Format("PRAGMA index_list({0})", tableName)); Dictionary<string, bool> indices = new Dictionary<string, bool>(); using (IDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { indices[rdr["name"].ToString()] = (uint.Parse(rdr["unique"].ToString()) > 0); } rdr.Close(); } CloseReaderCommand(cmd); bool checkForPrimary = primary.Fields.Length > 0; foreach (KeyValuePair<string, bool> index in indices) { defs[index.Key] = new IndexDefinition { Type = index.Value ? IndexType.Unique : IndexType.Index }; fields = new List<string>(); cmd = PrepReader(string.Format("PRAGMA index_info({0})", index.Key)); using (IDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { fields.Add(rdr["name"].ToString()); } rdr.Close(); } defs[index.Key].Fields = fields.ToArray(); CloseReaderCommand(cmd); if (checkForPrimary && defs[index.Key].Fields.Length == primary.Fields.Length) { uint i = 0; bool isPrimary = true; foreach (string pkField in primary.Fields) { if (defs[index.Key].Fields[i++] != pkField) { isPrimary = false; break; } } if (isPrimary) { // MainConsole.Instance.Warn("[" + Identifier + "]: Primary Key found (" + string.Join(", ", defs[index.Key].Fields) + ")"); defs[index.Key].Type = IndexType.Primary; checkForPrimary = false; } } } if (checkForPrimary == true && autoIncrementField != null) { primary = new IndexDefinition { Fields = new string[1] { autoIncrementField }, Type = IndexType.Primary }; defs["#fauxprimary#"] = primary; } return defs; } public override void DropTable(string tableName) { var cmd = new SQLiteCommand {CommandText = string.Format("drop table {0}", tableName)}; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } public override void ForceRenameTable(string oldTableName, string newTableName) { var cmd = new SQLiteCommand { CommandText = string.Format("ALTER TABLE {0} RENAME TO {1}", oldTableName, newTableName + "_renametemp") }; ExecuteNonQuery(cmd); cmd.CommandText = string.Format("ALTER TABLE {0} RENAME TO {1}", newTableName + "_renametemp", newTableName); ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } protected override void CopyAllDataBetweenMatchingTables(string sourceTableName, string destinationTableName, ColumnDefinition[] columnDefinitions, IndexDefinition[] indexDefinitions) { var cmd = new SQLiteCommand { CommandText = string.Format("insert into {0} select * from {1}", destinationTableName, sourceTableName) }; ExecuteNonQuery(cmd); CloseReaderCommand(cmd); } #endregion public override IGenericData Copy() { return new SQLiteLoader(); } } }
// *********************************************************************** // Copyright (c) 2006 Charlie Poole, Rob Prouse // // 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.Collections.Generic; using System.Linq; using NUnit.TestUtilities; using NUnit.TestUtilities.Collections; using NUnit.TestUtilities.Comparers; namespace NUnit.Framework.Assertions { /// <summary> /// Test Library for the NUnit CollectionAssert class. /// </summary> [TestFixture()] public class CollectionAssertTest { #region AllItemsAreInstancesOfType [Test()] public void ItemsOfType() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string)); } [Test] public void ItemsOfTypeFailure() { var collection = new SimpleObjectCollection("x", "y", new object()); var expectedMessage = " Expected: all items instance of <System.String>" + Environment.NewLine + " But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region AllItemsAreNotNull [Test()] public void ItemsNotNull() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AllItemsAreNotNull(collection); } [Test] public void ItemsNotNullFailure() { var collection = new SimpleObjectCollection("x", null, "z"); var expectedMessage = " Expected: all items not null" + Environment.NewLine + " But was: < \"x\", null, \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region AllItemsAreUnique [Test] public void Unique_WithObjects() { CollectionAssert.AllItemsAreUnique( new SimpleObjectCollection(new object(), new object(), new object())); } [Test] public void Unique_WithStrings() { CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z")); } [Test] public void Unique_WithNull() { CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z")); } [Test] public void UniqueFailure() { var expectedMessage = " Expected: all items unique" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x"))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void UniqueFailure_WithTwoNulls() { Assert.Throws<AssertionException>( () => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z"))); } static readonly IEnumerable<int> RANGE = Enumerable.Range(0, 10000); static readonly IEnumerable[] PerformanceData = { RANGE, new List<int>(RANGE), new List<double>(RANGE.Select(v => (double)v)), new List<string>(RANGE.Select(v => v.ToString())) }; [MaxTime(100)] [TestCaseSource(nameof(PerformanceData))] public void PerformanceTests(IEnumerable values) { CollectionAssert.AllItemsAreUnique(values); } #endregion #region AreEqual [Test] public void AreEqual() { var set1 = new SimpleEnumerable("x", "y", "z"); var set2 = new SimpleEnumerable("x", "y", "z"); CollectionAssert.AreEqual(set1,set2); CollectionAssert.AreEqual(set1,set2,new TestComparer()); Assert.AreEqual(set1,set2); } [Test] public void AreEqualFailCount() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("x", "y", "z", "a"); var expectedMessage = " Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine + " Values differ at index [3]" + Environment.NewLine + " Extra: < \"a\" >"; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEqualFail() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("x", "y", "a"); var expectedMessage = " Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine + " Values differ at index [2]" + Environment.NewLine + " String lengths are both 1. Strings differ at index 0." + Environment.NewLine + " Expected: \"z\"" + Environment.NewLine + " But was: \"a\"" + Environment.NewLine + " -----------^" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEqual_HandlesNull() { object[] set1 = new object[3]; object[] set2 = new object[3]; CollectionAssert.AreEqual(set1,set2); CollectionAssert.AreEqual(set1,set2,new TestComparer()); } [Test] public void EnsureComparerIsUsed() { // Create two collections int[] array1 = new int[2]; int[] array2 = new int[2]; array1[0] = 4; array1[1] = 5; array2[0] = 99; array2[1] = -99; CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer()); } [Test] public void AreEqual_UsingIterator() { int[] array = new int[] { 1, 2, 3 }; CollectionAssert.AreEqual(array, CountToThree()); } IEnumerable CountToThree() { yield return 1; yield return 2; yield return 3; } [Test] public void AreEqual_UsingIterator_Fails() { int[] array = new int[] { 1, 3, 5 }; AssertionException ex = Assert.Throws<AssertionException>( delegate { CollectionAssert.AreEqual(array, CountToThree()); } ); Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And. Contains("Expected: 3").And. Contains("But was: 2")); } #if !NET_2_0 [Test] public void AreEqual_UsingLinqQuery() { int[] array = new int[] { 1, 2, 3 }; CollectionAssert.AreEqual(array, array.Select((item) => item)); } [Test] public void AreEqual_UsingLinqQuery_Fails() { int[] array = new int[] { 1, 2, 3 }; AssertionException ex = Assert.Throws<AssertionException>( delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } ); Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And. Contains("Expected: 1").And. Contains("But was: 2")); } #endif [Test] public void AreEqual_IEquatableImplementationIsIgnored() { var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42); var y = new Constraints.EnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 15); // They are not equal using Assert Assert.AreNotEqual(x, y, "Assert 1"); Assert.AreNotEqual(y, x, "Assert 2"); // Using CollectionAssert they are equal CollectionAssert.AreEqual(x, y, "CollectionAssert 1"); CollectionAssert.AreEqual(y, x, "CollectionAssert 2"); } #endregion #region AreEquivalent [Test] public void Equivalent() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("z", "y", "x"); CollectionAssert.AreEquivalent(set1,set2); } [Test] public void EquivalentFailOne() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("x", "y", "x"); var expectedMessage = " Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine + " Missing (1): < \"z\" >" + Environment.NewLine + " Extra (1): < \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void EquivalentFailTwo() { ICollection set1 = new SimpleObjectCollection("x", "y", "x"); ICollection set2 = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine + " Missing (1): < \"x\" >" + Environment.NewLine + " Extra (1): < \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEquivalentHandlesNull() { ICollection set1 = new SimpleObjectCollection(null, "x", null, "z"); ICollection set2 = new SimpleObjectCollection("z", null, "x", null); CollectionAssert.AreEquivalent(set1,set2); } #endregion #region AreNotEqual [Test] public void AreNotEqual() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "x"); CollectionAssert.AreNotEqual(set1,set2); CollectionAssert.AreNotEqual(set1,set2,new TestComparer()); CollectionAssert.AreNotEqual(set1,set2,"test"); CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test"); CollectionAssert.AreNotEqual(set1,set2,"test {0}","1"); CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1"); } [Test] public void AreNotEqual_Fails() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreNotEqual_HandlesNull() { object[] set1 = new object[3]; var set2 = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AreNotEqual(set1,set2); CollectionAssert.AreNotEqual(set1,set2,new TestComparer()); } [Test] public void AreNotEqual_IEquatableImplementationIsIgnored() { var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42); var y = new Constraints.EnumerableObject<int>(new[] { 5, 4, 3, 2, 1 }, 42); // Equal using Assert Assert.AreEqual(x, y, "Assert 1"); Assert.AreEqual(y, x, "Assert 2"); // Not equal using CollectionAssert CollectionAssert.AreNotEqual(x, y, "CollectionAssert 1"); CollectionAssert.AreNotEqual(y, x, "CollectionAssert 2"); } #endregion #region AreNotEquivalent [Test] public void NotEquivalent() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "x"); CollectionAssert.AreNotEquivalent(set1,set2); } [Test] public void NotEquivalent_Fails() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "z", "y"); var expectedMessage = " Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NotEquivalentHandlesNull() { var set1 = new SimpleObjectCollection("x", null, "z"); var set2 = new SimpleObjectCollection("x", null, "x"); CollectionAssert.AreNotEquivalent(set1,set2); } #endregion #region Contains [Test] public void Contains_IList() { var list = new SimpleObjectList("x", "y", "z"); CollectionAssert.Contains(list, "x"); } [Test] public void Contains_ICollection() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.Contains(collection,"x"); } [Test] public void ContainsFails_ILIst() { var list = new SimpleObjectList("x", "y", "z"); var expectedMessage = " Expected: some item equal to \"a\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_ICollection() { var collection = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: some item equal to \"a\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_EmptyIList() { var list = new SimpleObjectList(); var expectedMessage = " Expected: some item equal to \"x\"" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_EmptyICollection() { var ca = new SimpleObjectCollection(new object[0]); var expectedMessage = " Expected: some item equal to \"x\"" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsNull_IList() { Object[] oa = new object[] { 1, 2, 3, null, 4, 5 }; CollectionAssert.Contains( oa, null ); } [Test] public void ContainsNull_ICollection() { var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 }); CollectionAssert.Contains( ca, null ); } #endregion #region DoesNotContain [Test] public void DoesNotContain() { var list = new SimpleObjectList(); CollectionAssert.DoesNotContain(list,"a"); } [Test] public void DoesNotContain_Empty() { var list = new SimpleObjectList(); CollectionAssert.DoesNotContain(list,"x"); } [Test] public void DoesNotContain_Fails() { var list = new SimpleObjectList("x", "y", "z"); var expectedMessage = " Expected: not some item equal to \"y\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region IsSubsetOf [Test] public void IsSubsetOf() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z"); CollectionAssert.IsSubsetOf(set2,set1); Assert.That(set2, Is.SubsetOf(set1)); } [Test] public void IsSubsetOf_Fails() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z", "a"); var expectedMessage = " Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsSubsetOfHandlesNull() { var set1 = new SimpleObjectList("x", null, "z"); var set2 = new SimpleObjectList(null, "z"); CollectionAssert.IsSubsetOf(set2,set1); Assert.That(set2, Is.SubsetOf(set1)); } #endregion #region IsNotSubsetOf [Test] public void IsNotSubsetOf() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z", "a"); CollectionAssert.IsNotSubsetOf(set1,set2); Assert.That(set1, Is.Not.SubsetOf(set2)); } [Test] public void IsNotSubsetOf_Fails() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z"); var expectedMessage = " Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotSubsetOfHandlesNull() { var set1 = new SimpleObjectList("x", null, "z"); var set2 = new SimpleObjectList(null, "z", "a"); CollectionAssert.IsNotSubsetOf(set1,set2); } #endregion #region IsOrdered [Test] public void IsOrdered() { var list = new SimpleObjectList("x", "y", "z"); CollectionAssert.IsOrdered(list); } [Test] public void IsOrdered_Fails() { var list = new SimpleObjectList("x", "z", "y"); var expectedMessage = " Expected: collection ordered" + Environment.NewLine + " But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsOrdered_Allows_adjacent_equal_values() { var list = new SimpleObjectList("x", "x", "z"); CollectionAssert.IsOrdered(list); } [Test] public void IsOrdered_Handles_null() { var list = new SimpleObjectList(null, "x", "z"); Assert.That(list, Is.Ordered); } [Test] public void IsOrdered_ContainedTypesMustBeCompatible() { var list = new SimpleObjectList(1, "x"); Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list)); } [Test] public void IsOrdered_TypesMustImplementIComparable() { var list = new SimpleObjectList(new object(), new object()); Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list)); } [Test] public void IsOrdered_Handles_custom_comparison() { var list = new SimpleObjectList(new object(), new object()); CollectionAssert.IsOrdered(list, new AlwaysEqualComparer()); } [Test] public void IsOrdered_Handles_custom_comparison2() { var list = new SimpleObjectList(2, 1); CollectionAssert.IsOrdered(list, new TestComparer()); } #endregion #region Equals [Test] public void EqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions")); } #endregion } }
using System; using System.Globalization; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdFund : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private String Id; private int TransTypesId; private int ActTrans; private int ActNonTrans; private float FundAmt; private float FundAmtCr; private float FundAmtDr; private String FundCurr; private int GetIndexOfStatus (string s) { return (lstStatus.Items.IndexOf (lstStatus.Items.FindByValue(s))); } private int GetIndexOfTTs (string s) { return (lstTT.Items.IndexOf (lstTT.Items.FindByValue(s))); } private int GetIndexOfVisibility (string s) { return (lstVisibility.Items.IndexOf (lstVisibility.Items.FindByValue(s))); } protected void Page_Load(object sender, System.EventArgs e) { Id=Request.Params["Id"]; TransTypesId = 1; lblOrg.Text=(Session["OrgName"]).ToString(); lblFunction.Text=Request.Params["btnAction"] + " Fund"; if (Request.Params["btnAction"].ToString() == "Update") { getFundAmt(); } if (!IsPostBack) { loadFundStatus(); loadVisibility(); btnAction.Text= Request.Params["btnAction"]; txtName.Text=Request.Params["Name"]; lstStatus.SelectedIndex = GetIndexOfStatus (Request.Params["Status"]); lstVisibility.SelectedIndex = GetIndexOfVisibility (Request.Params["Vis"]); lstTT.SelectedIndex = GetIndexOfTTs (Request.Params["TTs"]); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void getFundAmt() { getActs(); getFundAmtCr(); getFundAmtDr(); FundAmt=FundAmtCr - FundAmtDr; getFundCurr(); lblFundAmt.Text=FundAmt.ToString() + " " + FundCurr; } private void getFundAmtCr() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveActBalCr"; cmd.Parameters.Add("@ActsId",SqlDbType.Int); cmd.Parameters["@ActsId"].Value=ActTrans; cmd.Parameters.Add("@SubActsId",SqlDbType.Int); cmd.Parameters["@SubActsId"].Value=Id; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"FundBalCr"); if (ds.Tables["FundBalCr"].Rows.Count == 0) { FundAmtCr=0; } else if (ds.Tables["FundBalCr"].Rows.Count == 1) { if (ds.Tables["FundBalCr"].Rows[0][0].ToString() == "") { FundAmtCr=0; } else { FundAmtCr=float.Parse(ds.Tables["FundBalCr"].Rows[0][0].ToString(), NumberStyles.Any); } } //lblFunction.Text="Acts: " + Acts + " SubActsId: " + Id; } private void getFundAmtDr() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveActBalDr"; cmd.Parameters.Add("@ActsId",SqlDbType.Int); cmd.Parameters["@ActsId"].Value=ActTrans; cmd.Parameters.Add("@SubActsId",SqlDbType.Int); cmd.Parameters["@SubActsId"].Value=Id; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"FundBalDr"); if (ds.Tables["FundBalDr"].Rows.Count == 0) { FundAmtDr=0; } else if (ds.Tables["FundBalDr"].Rows.Count == 1) { if (ds.Tables["FundBalDr"].Rows[0][0].ToString() == "") { FundAmtDr=0; } else { FundAmtDr=float.Parse(ds.Tables["FundBalDr"].Rows[0][0].ToString(), NumberStyles.Any); } } } private void getFundCurr() { FundCurr="US Dollars"; } private void getActs() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveActs"; cmd.Parameters.Add("@TransTypesId",SqlDbType.Int); cmd.Parameters["@TransTypesId"].Value=TransTypesId; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Act"); if (ds.Tables["Act"].Rows.Count == 0) { lblFunction.Text = "No account rules created for this transaction type!"; } else { ActTrans=Int32.Parse(ds.Tables["Act"].Rows[0][0].ToString()); ActNonTrans=Int32.Parse(ds.Tables["Act"].Rows[0][1].ToString()); } } private void loadFundStatus() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveFundStatus"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"FundStatus"); lstStatus.DataSource = ds; lstStatus.DataMember= "FundStatus"; lstStatus.DataTextField = "Name"; lstStatus.DataValueField = "Id"; lstStatus.DataBind(); } private void loadVisibility() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="ams_RetrieveVisibility"; cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=Session["OrgVis"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Visibility"); lstVisibility.DataSource = ds; lstVisibility.DataMember= "Visibility"; lstVisibility.DataTextField = "Name"; lstVisibility.DataValueField = "Id"; lstVisibility.DataBind(); } protected void btnAction_Click(object sender, System.EventArgs e) { if (btnAction.Text == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_UpdateFunds"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Int32.Parse(Id); cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value= txtName.Text; cmd.Parameters.Add ("@Status",SqlDbType.Int); cmd.Parameters["@Status"].Value=lstStatus.SelectedItem.Value; cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } else if (btnAction.Text == "Add") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_AddFund"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value= txtName.Text; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"]; cmd.Parameters.Add ("@Status",SqlDbType.Int); cmd.Parameters["@Status"].Value=lstStatus.SelectedItem.Value; cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } Done(); } private void Done() { Response.Redirect (strURL + Session["CUpdFund"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } protected void btnAct_Click(object sender, System.EventArgs e) { } } }
using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Metadata; namespace AllReady.Migrations { public partial class TenantBecomesOrganization : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Tenant_TenantId", table: "AllReadyTask"); migrationBuilder.DropForeignKey(name: "FK_ApplicationUser_Tenant_TenantId", table: "AspNetUsers"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignSponsors_Tenant_TenantId", table: "CampaignSponsors"); migrationBuilder.DropForeignKey(name: "FK_Skill_Tenant_OwningOrganizationId", table: "Skill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "TenantId", table: "CampaignSponsors"); migrationBuilder.DropColumn(name: "ManagingTenantId", table: "Campaign"); migrationBuilder.DropColumn(name: "TenantId", table: "AspNetUsers"); migrationBuilder.DropColumn(name: "TenantId", table: "AllReadyTask"); migrationBuilder.DropTable("TenantContact"); migrationBuilder.DropTable("Tenant"); migrationBuilder.CreateTable( name: "Organization", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), LocationId = table.Column<int>(nullable: true), LogoUrl = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: false), WebUrl = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Organization", x => x.Id); table.ForeignKey( name: "FK_Organization_Location_LocationId", column: x => x.LocationId, principalTable: "Location", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "OrganizationContact", columns: table => new { OrganizationId = table.Column<int>(nullable: false), ContactId = table.Column<int>(nullable: false), ContactType = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_OrganizationContact", x => new { x.OrganizationId, x.ContactId, x.ContactType }); table.ForeignKey( name: "FK_OrganizationContact_Contact_ContactId", column: x => x.ContactId, principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", column: x => x.OrganizationId, principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.AddColumn<int>( name: "OrganizationId", table: "CampaignSponsors", nullable: true); migrationBuilder.AddColumn<int>( name: "ManagingOrganizationId", table: "Campaign", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "OrganizationId", table: "AspNetUsers", nullable: true); migrationBuilder.AddColumn<int>( name: "OrganizationId", table: "AllReadyTask", nullable: true); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_AllReadyTask_Organization_OrganizationId", table: "AllReadyTask", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ApplicationUser_Organization_OrganizationId", table: "AspNetUsers", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignSponsors_Organization_OrganizationId", table: "CampaignSponsors", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Skill_Organization_OwningOrganizationId", table: "Skill", column: "OwningOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Organization_OrganizationId", table: "AllReadyTask"); migrationBuilder.DropForeignKey(name: "FK_ApplicationUser_Organization_OrganizationId", table: "AspNetUsers"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignSponsors_Organization_OrganizationId", table: "CampaignSponsors"); migrationBuilder.DropForeignKey(name: "FK_Skill_Organization_OwningOrganizationId", table: "Skill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "OrganizationId", table: "CampaignSponsors"); migrationBuilder.DropColumn(name: "ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropColumn(name: "OrganizationId", table: "AspNetUsers"); migrationBuilder.DropColumn(name: "OrganizationId", table: "AllReadyTask"); migrationBuilder.DropTable("OrganizationContact"); migrationBuilder.DropTable("Organization"); migrationBuilder.CreateTable( name: "Tenant", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), LocationId = table.Column<int>(nullable: true), LogoUrl = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: false), WebUrl = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Tenant", x => x.Id); table.ForeignKey( name: "FK_Tenant_Location_LocationId", column: x => x.LocationId, principalTable: "Location", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "TenantContact", columns: table => new { TenantId = table.Column<int>(nullable: false), ContactId = table.Column<int>(nullable: false), ContactType = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_TenantContact", x => new { x.TenantId, x.ContactId, x.ContactType }); table.ForeignKey( name: "FK_TenantContact_Contact_ContactId", column: x => x.ContactId, principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_TenantContact_Tenant_TenantId", column: x => x.TenantId, principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.AddColumn<int>( name: "TenantId", table: "CampaignSponsors", nullable: true); migrationBuilder.AddColumn<int>( name: "ManagingTenantId", table: "Campaign", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "TenantId", table: "AspNetUsers", nullable: true); migrationBuilder.AddColumn<int>( name: "TenantId", table: "AllReadyTask", nullable: true); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_AllReadyTask_Tenant_TenantId", table: "AllReadyTask", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ApplicationUser_Tenant_TenantId", table: "AspNetUsers", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignSponsors_Tenant_TenantId", table: "CampaignSponsors", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Skill_Tenant_OwningOrganizationId", table: "Skill", column: "OwningOrganizationId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
namespace Geocrest.Web.Infrastructure.Providers { #region Using using System; using System.Xml; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration.Provider; using System.Web.Security; using System.Web.Hosting; using System.Web.Management; using System.Security.Permissions; using System.Web; using System.Text; using System.Security.Cryptography; using System.IO; using System.Threading.Tasks; #endregion /// <summary> /// Provides a membership provider implementation based on users stored in an XML file. /// </summary> public class XmlMembershipProvider : MembershipProvider { private Dictionary<string, MembershipUser> _Users; private XmlDocument doc = null; private string _XmlFileName; #region Properties // MembershipProvider Properties /// <summary> /// The name of the application using the custom membership provider. /// </summary> /// <returns>The name of the application using the custom membership provider.</returns> /// <exception cref="T:System.NotSupportedException"> /// </exception> public override string ApplicationName { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Indicates whether the membership provider is configured to allow users to retrieve their passwords. /// </summary> /// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns> public override bool EnablePasswordRetrieval { get { return false; } } /// <summary> /// Indicates whether the membership provider is configured to allow users to reset their passwords. /// </summary> /// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns> public override bool EnablePasswordReset { get { return false; } } /// <summary> /// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out. /// </summary> /// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns> public override int MaxInvalidPasswordAttempts { get { return 5; } } /// <summary> /// Gets the minimum number of special characters that must be present in a valid password. /// </summary> /// <returns>The minimum number of special characters that must be present in a valid password.</returns> public override int MinRequiredNonAlphanumericCharacters { get { return 0; } } /// <summary> /// Gets the minimum length required for a password. /// </summary> /// <returns>The minimum length required for a password. </returns> public override int MinRequiredPasswordLength { get { return 0; } } /// <summary> /// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out. /// </summary> /// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns> /// <exception cref="T:System.NotSupportedException"></exception> public override int PasswordAttemptWindow { get { throw new NotSupportedException(); } } /// <summary> /// Gets a value indicating the format for storing passwords in the membership data store. /// </summary> /// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat" /> values indicating the format for storing passwords in the data store.</returns> public override MembershipPasswordFormat PasswordFormat { get { return MembershipPasswordFormat.Clear; } } /// <summary> /// Gets the regular expression used to evaluate a password. /// </summary> /// <returns>A regular expression used to evaluate a password.</returns> /// <exception cref="T:System.NotSupportedException"></exception> public override string PasswordStrengthRegularExpression { get { throw new NotSupportedException(); } } /// <summary> /// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval. /// </summary> /// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns> public override bool RequiresQuestionAndAnswer { get { return false; } } /// <summary> /// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name. /// </summary> /// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns> public override bool RequiresUniqueEmail { get { return false; } } #endregion #region Supported methods /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">config</exception> /// <exception cref="T:System.Configuration.Provider.ProviderException">Unrecognized attribute: + attr</exception> public override void Initialize(string name, NameValueCollection config) { Throw.IfArgumentNull(config, "config"); if (String.IsNullOrEmpty(name)) name = "XmlMembershipProvider"; if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "XML membership provider"); } base.Initialize(name, config); // Initialize _XmlFileName and make sure the path // is app-relative string path = config["xmlFileName"]; if (String.IsNullOrEmpty(path)) path = "~/App_Data/Users.xml"; string fullyQualifiedPath = ""; if (!VirtualPathUtility.IsAppRelative(path)) _XmlFileName = path; //throw new ArgumentException // ("xmlFileName must be app-relative"); else { fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath != null ? HttpRuntime.AppDomainAppVirtualPath : "/"), path); _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath); } if (string.IsNullOrEmpty(_XmlFileName)) _XmlFileName = path; config.Remove("xmlFileName"); // Make sure file exists FileInfo fi = new FileInfo(_XmlFileName); if (!fi.Exists) { using (StreamWriter sw = new StreamWriter(fi.Create())) { sw.WriteLine("<Users></Users>"); //sw.Close(); } } // Make sure we have permission to read the XML data source and // throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, _XmlFileName); permission.Demand(); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new ProviderException("Unrecognized attribute: " + attr); } } /// <summary> /// Returns true if the username and password match an exsisting user. /// </summary> /// <param name="username">The name of the user to validate.</param> /// <param name="password">The password for the specified user.</param> /// <returns> /// true if the specified username and password are valid; otherwise, false. /// </returns> public override bool ValidateUser(string username, string password) { ReadDataStore(); if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password)) return false; try { // Validate the user name and password MembershipUser user; if (_Users.TryGetValue(username, out user)) { if (user.Comment == Encrypt(password)) // Case-sensitive { user.LastLoginDate = DateTime.Now; UpdateUser(user); return true; } } return false; } catch { return false; } } /// <summary> /// Retrieves a user based on his/hers username. /// the userIsOnline parameter is ignored. /// </summary> /// <param name="username">The name of the user to get information for.</param> /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the specified user's information from the data source. /// </returns> public override MembershipUser GetUser(string username, bool userIsOnline) { ReadDataStore(); if (String.IsNullOrEmpty(username)) return null; // Retrieve the user from the data source MembershipUser user; if (_Users.TryGetValue(username, out user)) return user; return null; } /// <summary> /// Retrieves a collection of all the users. /// This implementation ignores pageIndex and pageSize, /// and it doesn't sort the MembershipUser objects returned. /// </summary> /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex" /> is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection" /> collection that contains a page of <paramref name="pageSize" /><see cref="T:System.Web.Security.MembershipUser" /> objects beginning at the page specified by <paramref name="pageIndex" />. /// </returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { ReadDataStore(); MembershipUserCollection users = new MembershipUserCollection(); foreach (KeyValuePair<string, MembershipUser> pair in _Users) { users.Add(pair.Value); } totalRecords = users.Count; return users; } /// <summary> /// Changes a users password. /// </summary> /// <param name="username">The user to update the password for.</param> /// <param name="oldPassword">The current password for the specified user.</param> /// <param name="newPassword">The new password for the specified user.</param> /// <returns> /// true if the password was updated successfully; otherwise, false. /// </returns> public override bool ChangePassword(string username, string oldPassword, string newPassword) { XmlNodeList nodes = doc.GetElementsByTagName("User"); foreach (XmlNode node in nodes) { if (node["UserName"].InnerText.Equals(username, StringComparison.OrdinalIgnoreCase) || node["Password"].InnerText.Equals(Encrypt(oldPassword), StringComparison.OrdinalIgnoreCase)) { node["Password"].InnerText = Encrypt(newPassword); doc.Save(_XmlFileName); return true; } } ReadDataStore(); return false; } /// <summary> /// Creates the user with the specified properties. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="email">The email.</param> /// <param name="isApproved">if set to <c>true</c> is approved.</param> /// <param name="providerUserKey">The provider user key.</param> /// <param name="passwordQuestion">The password question.</param> /// <param name="passwordAnswer">The password answer.</param> /// <returns> /// Returns an instance of <see cref="T:System.Web.Security.MembershipUser"/>. /// </returns> public static MembershipUser CreateUser(string username, string password, string email, bool isApproved = true, object providerUserKey = null, string passwordQuestion = "", string passwordAnswer="") { XmlMembershipProvider xml = (XmlMembershipProvider)Membership.Provider; MembershipCreateStatus status; return xml.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey,out status); } /// <summary> /// Creates a new user store in the XML file /// </summary> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus" /> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the information for the newly created user. /// </returns> /// <exception cref="System.Web.Security.MembershipCreateUserException">User already exists</exception> public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { var user = this.GetUser(username, false); if (user != null) throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName); XmlNode xmlUserRoot = doc.CreateElement("User"); XmlNode xmlUserName = doc.CreateElement("UserName"); XmlNode xmlPassword = doc.CreateElement("Password"); XmlNode xmlEmail = doc.CreateElement("Email"); XmlNode xmlLastLoginTime = doc.CreateElement("LastLoginTime"); xmlUserName.InnerText = username; xmlPassword.InnerText = Encrypt(password); xmlEmail.InnerText = email; xmlLastLoginTime.InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); xmlUserRoot.AppendChild(xmlUserName); xmlUserRoot.AppendChild(xmlPassword); xmlUserRoot.AppendChild(xmlEmail); xmlUserRoot.AppendChild(xmlLastLoginTime); doc.SelectSingleNode("Users").AppendChild(xmlUserRoot); doc.Save(_XmlFileName); status = MembershipCreateStatus.Success; user = new MembershipUser(Name, username, username, email, passwordQuestion, Encrypt(password), isApproved, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.MaxValue); ReadDataStore(); return user; } /// <summary> /// Deletes the user from the XML file and /// removes him/her from the internal cache. /// </summary> /// <param name="username">The name of the user to delete.</param> /// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param> /// <returns> /// true if the user was successfully deleted; otherwise, false. /// </returns> public override bool DeleteUser(string username, bool deleteAllRelatedData) { if (deleteAllRelatedData) Roles.RemoveUserFromRoles(username,Roles.GetRolesForUser(username)); foreach (XmlNode node in doc.GetElementsByTagName("User")) { if (node.ChildNodes[0].InnerText.Equals(username, StringComparison.OrdinalIgnoreCase)) { var users = doc.SelectSingleNode("Users"); users.RemoveChild(node); doc.Save(_XmlFileName); _Users.Remove(username); ReadDataStore(); return true; } } ReadDataStore(); return false; } /// <summary> /// Get a user based on the username parameter. /// the userIsOnline parameter is ignored. /// </summary> /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param> /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the specified user's information from the data source. /// </returns> public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { ReadDataStore(); foreach (XmlNode node in doc.SelectNodes("//User")) { if (node.ChildNodes[0].InnerText.Equals(providerUserKey.ToString(), StringComparison.OrdinalIgnoreCase)) { string userName = node.ChildNodes[0].InnerText; string password = node.ChildNodes[1].InnerText; string email = node.ChildNodes[2].InnerText; DateTime lastLoginTime = DateTime.Parse(node.ChildNodes[3].InnerText); return new MembershipUser(Name, providerUserKey.ToString(), providerUserKey, email, string.Empty, password, true, false, DateTime.Now, lastLoginTime, DateTime.Now, DateTime.Now, DateTime.MaxValue); } } return default(MembershipUser); } /// <summary> /// Retrieves a username based on a matching email. /// </summary> /// <param name="email">The e-mail address to search for.</param> /// <returns> /// The user name associated with the specified e-mail address. If no match is found, return null. /// </returns> public override string GetUserNameByEmail(string email) { ReadDataStore(); foreach (XmlNode node in doc.GetElementsByTagName("User")) { if (node.ChildNodes[2].InnerText.Equals(email.Trim(), StringComparison.OrdinalIgnoreCase)) { return node.ChildNodes[0].InnerText; } } return null; } /// <summary> /// Updates a user. The username will not be changed. /// </summary> /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser" /> object that represents the user to update and the updated information for the user.</param> public override void UpdateUser(MembershipUser user) { foreach (XmlNode node in doc.GetElementsByTagName("User")) { if (node.ChildNodes[0].InnerText.Equals(user.UserName, StringComparison.OrdinalIgnoreCase)) { //if (user.Comment.Length > 30) //{ // node.ChildNodes[1].InnerText = Encrypt(user.Comment); //} node.ChildNodes[2].InnerText = user.Email; node.ChildNodes[3].InnerText = user.LastLoginDate.ToString("yyyy-MM-dd HH:mm:ss"); doc.Save(_XmlFileName); _Users[user.UserName] = user; } } ReadDataStore(); } #endregion #region Helper methods /// <summary> /// Builds the internal cache of users. /// </summary> private void ReadDataStore() { lock (this) { _Users = new Dictionary<string, MembershipUser>(16, StringComparer.InvariantCultureIgnoreCase); this.doc = new XmlDocument(); doc.Load(_XmlFileName); XmlNodeList nodes = doc.GetElementsByTagName("User"); foreach (XmlNode node in nodes) { MembershipUser user = new MembershipUser( Name, // Provider name node["UserName"].InnerText, // Username node["UserName"].InnerText, // providerUserKey node["Email"].InnerText, // Email String.Empty, // passwordQuestion node["Password"].InnerText, // Comment true, // isApproved false, // isLockedOut DateTime.Now, // creationDate DateTime.Parse(node["LastLoginTime"].InnerText), // lastLoginDate DateTime.Now, // lastActivityDate DateTime.Now, // lastPasswordChangedDate new DateTime(1980, 1, 1) // lastLockoutDate ); _Users.Add(user.UserName, user); } } } /// <summary> /// Encrypts a string using the SHA256 algorithm. /// </summary> /// <param name="plainMessage">The string to encrypt.</param> private static string Encrypt(string plainMessage) { byte[] data = Encoding.UTF8.GetBytes(plainMessage); using (HashAlgorithm sha = new SHA256Managed()) { byte[] encryptedBytes = sha.TransformFinalBlock(data, 0, data.Length); string hash = Convert.ToBase64String(sha.Hash); return hash; } } #endregion #region Unsupported methods /// <summary> /// Resets a user's password to a new, automatically generated password. /// </summary> /// <param name="username">The user to reset the password for.</param> /// <param name="answer">The password answer for the specified user.</param> /// <returns> /// The new password for the specified user. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override string ResetPassword(string username, string answer) { throw new NotSupportedException(); } /// <summary> /// Clears a lock so that the membership user can be validated. /// </summary> /// <param name="userName">The membership user whose lock status you want to clear.</param> /// <returns> /// true if the membership user was successfully unlocked; otherwise, false. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override bool UnlockUser(string userName) { throw new NotSupportedException(); } /// <summary> /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match. /// </summary> /// <param name="emailToMatch">The e-mail address to search for.</param> /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex" /> is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection" /> collection that contains a page of <paramref name="pageSize" /><see cref="T:System.Web.Security.MembershipUser" /> objects beginning at the page specified by <paramref name="pageIndex" />. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotSupportedException(); } /// <summary> /// Gets a collection of membership users where the user name contains the specified user name to match. /// </summary> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex" /> is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection" /> collection that contains a page of <paramref name="pageSize" /><see cref="T:System.Web.Security.MembershipUser" /> objects beginning at the page specified by <paramref name="pageIndex" />. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotSupportedException(); } /// <summary> /// Gets the number of users currently accessing the application. /// </summary> /// <returns> /// The number of users currently accessing the application. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override int GetNumberOfUsersOnline() { throw new NotSupportedException(); } /// <summary> /// Processes a request to update the password question and answer for a membership user. /// </summary> /// <param name="username">The user to change the password question and answer for.</param> /// <param name="password">The password for the specified user.</param> /// <param name="newPasswordQuestion">The new password question for the specified user.</param> /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> /// <returns> /// true if the password question and answer are updated successfully; otherwise, false. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotSupportedException(); } /// <summary> /// Gets the password for the specified user name from the data source. /// </summary> /// <param name="username">The user to retrieve the password for.</param> /// <param name="answer">The password answer for the user.</param> /// <returns> /// The password for the specified user name. /// </returns> /// <exception cref="T:System.NotSupportedException"></exception> public override string GetPassword(string username, string answer) { throw new NotSupportedException(); } #endregion } }
// This file was automatically generated by the PetaPoco T4 Template // Do not make changes directly to this file - edit the template instead // // The following connection settings were used to generate this file // // Connection String Name: `default` // Provider: `System.Data.SqlClient` // Connection String: `Data Source=.\t;Initial Catalog=da;uid=sa;pwd=123456` // Schema: `` // Include Views: `False` using System; using System.Collections.Generic; using System.Linq; using System.Web; using PetaPoco; namespace ProjectManager.Models { public partial class defaultDB : Database { public defaultDB() : base("default") { CommonConstruct(); } public defaultDB(string connectionStringName) : base(connectionStringName) { CommonConstruct(); } partial void CommonConstruct(); public interface IFactory { defaultDB GetInstance(); } public static IFactory Factory { get; set; } public static defaultDB GetInstance() { if (_instance!=null) return _instance; if (Factory!=null) return Factory.GetInstance(); else return new defaultDB(); } [ThreadStatic] static defaultDB _instance; public override void OnBeginTransaction() { if (_instance==null) _instance=this; } public override void OnEndTransaction() { if (_instance==this) _instance=null; } public class Record<T> where T:new() { public static defaultDB repo { get { return defaultDB.GetInstance(); } } public bool IsNew() { return repo.IsNew(this); } public object Insert() { return repo.Insert(this); } public void Save() { repo.Save(this); } public int Update() { return repo.Update(this); } public int Update(IEnumerable<string> columns) { return repo.Update(this, columns); } public static int Update(string sql, params object[] args) { return repo.Update<T>(sql, args); } public static int Update(Sql sql) { return repo.Update<T>(sql); } public int Delete() { return repo.Delete(this); } public static int Delete(string sql, params object[] args) { return repo.Delete<T>(sql, args); } public static int Delete(Sql sql) { return repo.Delete<T>(sql); } public static int Delete(object primaryKey) { return repo.Delete<T>(primaryKey); } public static bool Exists(object primaryKey) { return repo.Exists<T>(primaryKey); } public static bool Exists(string sql, params object[] args) { return repo.Exists<T>(sql, args); } public static T SingleOrDefault(object primaryKey) { return repo.SingleOrDefault<T>(primaryKey); } public static T SingleOrDefault(string sql, params object[] args) { return repo.SingleOrDefault<T>(sql, args); } public static T SingleOrDefault(Sql sql) { return repo.SingleOrDefault<T>(sql); } public static T FirstOrDefault(string sql, params object[] args) { return repo.FirstOrDefault<T>(sql, args); } public static T FirstOrDefault(Sql sql) { return repo.FirstOrDefault<T>(sql); } public static T Single(object primaryKey) { return repo.Single<T>(primaryKey); } public static T Single(string sql, params object[] args) { return repo.Single<T>(sql, args); } public static T Single(Sql sql) { return repo.Single<T>(sql); } public static T First(string sql, params object[] args) { return repo.First<T>(sql, args); } public static T First(Sql sql) { return repo.First<T>(sql); } public static List<T> Fetch(string sql, params object[] args) { return repo.Fetch<T>(sql, args); } public static List<T> Fetch(Sql sql) { return repo.Fetch<T>(sql); } public static List<T> Fetch(long page, long itemsPerPage, string sql, params object[] args) { return repo.Fetch<T>(page, itemsPerPage, sql, args); } public static List<T> Fetch(long page, long itemsPerPage, Sql sql) { return repo.Fetch<T>(page, itemsPerPage, sql); } public static List<T> SkipTake(long skip, long take, string sql, params object[] args) { return repo.SkipTake<T>(skip, take, sql, args); } public static List<T> SkipTake(long skip, long take, Sql sql) { return repo.SkipTake<T>(skip, take, sql); } public static Page<T> Page(long page, long itemsPerPage, string sql, params object[] args) { return repo.Page<T>(page, itemsPerPage, sql, args); } public static Page<T> Page(long page, long itemsPerPage, Sql sql) { return repo.Page<T>(page, itemsPerPage, sql); } public static IEnumerable<T> Query(string sql, params object[] args) { return repo.Query<T>(sql, args); } public static IEnumerable<T> Query(Sql sql) { return repo.Query<T>(sql); } } } [TableName("Pro_Project")] [PrimaryKey("ID")] [ExplicitColumns] public partial class ProjectModel : defaultDB.Record<ProjectModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column] public string Description { get; set; } [Column] public string Roles { get; set; } [Column] public int Version { get; set; } } [TableName("Sys_Config")] [ExplicitColumns] public partial class ConfigModel : defaultDB.Record<ConfigModel> { [Column("Config_Key")] public string ConfigKey { get; set; } [Column("Config_Value")] public string ConfigValue { get; set; } [Column("Config_Type")] public string ConfigType { get; set; } } [TableName("Pro_Organization")] [PrimaryKey("ID")] [ExplicitColumns] public partial class OrganizationModel : defaultDB.Record<OrganizationModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column("Parent_ID")] public int ParentID { get; set; } [Column("Tree_Flag")] public string TreeFlag { get; set; } [Column("Child_Flag")] public int? ChildFlag { get; set; } } [TableName("Pro_ToDo")] [PrimaryKey("ID", autoIncrement=false)] [ExplicitColumns] public partial class ToDoModel : defaultDB.Record<ToDoModel> { [Column] public int ID { get; set; } [Column] public string Title { get; set; } [Column] public string Description { get; set; } [Column("Create_Man")] public int? CreateMan { get; set; } [Column("Create_Time")] public DateTime? CreateTime { get; set; } [Column("Remind_Time")] public DateTime? RemindTime { get; set; } [Column("Group_ID")] public int? GroupID { get; set; } } [TableName("Pro_ToDo_Group")] [ExplicitColumns] public partial class ToDoGroupModel : defaultDB.Record<ToDoGroupModel> { [Column] public int? ID { get; set; } [Column] public string Name { get; set; } [Column("Create_Man")] public int? CreateMan { get; set; } [Column("Create_Time")] public DateTime? CreateTime { get; set; } } [TableName("Pro_Requirements")] [PrimaryKey("ID")] [ExplicitColumns] public partial class RequirementModel : defaultDB.Record<RequirementModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column("Module_Name")] public string ModuleName { get; set; } [Column("Area_Name")] public string AreaName { get; set; } [Column] public string Roles { get; set; } [Column("Data_Source")] public string DataSource { get; set; } [Column] public int Version { get; set; } [Column] public string Description { get; set; } [Column("Project_ID")] public int ProjectID { get; set; } [Column] public string Premise { get; set; } } [TableName("Pro_Attr")] [PrimaryKey("ID")] [ExplicitColumns] public partial class AttrModel : defaultDB.Record<AttrModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column] public string Type { get; set; } [Column] public int? Sort { get; set; } } [TableName("Pro_User")] [PrimaryKey("ID")] [ExplicitColumns] public partial class UserModel : defaultDB.Record<UserModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column] public string Code { get; set; } [Column] public string Pwd { get; set; } [Column] public int Salt { get; set; } [Column] public string Email { get; set; } [Column] public string Phone { get; set; } [Column] public int QQ { get; set; } [Column("Del_Flag")] public int DelFlag { get; set; } [Column] public string Job { get; set; } [Column] public string Position { get; set; } } [TableName("Pro_User_Role")] [PrimaryKey("ID")] [ExplicitColumns] public partial class UserRoleModel : defaultDB.Record<UserRoleModel> { [Column] public int ID { get; set; } [Column("User_ID")] public int UserID { get; set; } [Column("Role_ID")] public int RoleID { get; set; } } [TableName("Pro_Role")] [PrimaryKey("ID")] [ExplicitColumns] public partial class RoleModel : defaultDB.Record<RoleModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column] public string Remark { get; set; } } [TableName("Pro_Group")] [PrimaryKey("ID")] [ExplicitColumns] public partial class GroupModel : defaultDB.Record<GroupModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column] public int SortNo { get; set; } } [TableName("Pro_Access")] [PrimaryKey("ID")] [ExplicitColumns] public partial class AccessModel : defaultDB.Record<AccessModel> { [Column] public int ID { get; set; } [Column("Role_ID")] public int RoleID { get; set; } [Column("Node_ID")] public int NodeID { get; set; } } [TableName("Pro_Node")] [PrimaryKey("ID")] [ExplicitColumns] public partial class NodeModel : defaultDB.Record<NodeModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column] public int Pid { get; set; } [Column("Node_Level")] public int NodeLevel { get; set; } [Column] public string Link { get; set; } [Column("Group_ID")] public int GroupID { get; set; } [Column] public int SortNo { get; set; } } [TableName("Pro_Area")] [PrimaryKey("ID")] [ExplicitColumns] public partial class AreaModel : defaultDB.Record<AreaModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column("Project_ID")] public int? ProjectID { get; set; } } [TableName("Pro_Module")] [PrimaryKey("ID")] [ExplicitColumns] public partial class ModuleModel : defaultDB.Record<ModuleModel> { [Column] public int ID { get; set; } [Column] public string Name { get; set; } [Column("Project_ID")] public int ProjectID { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Dfm { using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Dfm.MarkdownValidators; using Microsoft.DocAsCode.MarkdownLite; using Microsoft.DocAsCode.Plugins; public class DfmEngineBuilder : GfmEngineBuilder { private readonly string _baseDir; private IReadOnlyList<string> _fallbackFolders; public DfmEngineBuilder(Options options, string baseDir = null, string templateDir = null, IReadOnlyList<string> fallbackFolders = null) : this(options, baseDir, templateDir, fallbackFolders, null) { } public DfmEngineBuilder(Options options, string baseDir, string templateDir, IReadOnlyList<string> fallbackFolders, ICompositionContainer container) : base(options) { _baseDir = baseDir ?? string.Empty; _fallbackFolders = fallbackFolders ?? new List<string>(); var inlineRules = InlineRules.ToList(); // xref auto link must be before MarkdownAutoLinkInlineRule var index = inlineRules.FindIndex(s => s is MarkdownAutoLinkInlineRule); if (index < 0) { throw new ArgumentException("MarkdownAutoLinkInlineRule should exist!"); } inlineRules.Insert(index, new DfmXrefAutoLinkInlineRule()); index = inlineRules.FindLastIndex(s => s is MarkdownLinkInlineRule); if (index < 0) { throw new ArgumentException("MarkdownLinkInlineRule should exist!"); } inlineRules.Insert(index + 1, new DfmXrefShortcutInlineRule()); inlineRules.Insert(index + 1, new DfmEmailInlineRule()); inlineRules.Insert(index + 1, new DfmFencesInlineRule()); // xref link inline rule must be before MarkdownLinkInlineRule inlineRules.Insert(index, new DfmIncludeInlineRule()); Replace<MarkdownTextInlineRule, DfmTextInlineRule>(inlineRules); var blockRules = BlockRules.ToList(); index = blockRules.FindLastIndex(s => s is MarkdownCodeBlockRule); if (index < 0) { throw new ArgumentException("MarkdownNewLineBlockRule should exist!"); } blockRules.InsertRange( index + 1, new IMarkdownRule[] { new DfmIncludeBlockRule(), new DfmVideoBlockRule(), new DfmYamlHeaderBlockRule(), new DfmSectionBlockRule(), new DfmFencesBlockRule(), new DfmNoteBlockRule() }); Replace<MarkdownBlockquoteBlockRule, DfmBlockquoteBlockRule>(blockRules); Replace<MarkdownTableBlockRule, DfmTableBlockRule>(blockRules); Replace<MarkdownNpTableBlockRule, DfmNpTableBlockRule>(blockRules); InlineRules = inlineRules.ToImmutableList(); BlockRules = blockRules.ToImmutableList(); Rewriter = InitMarkdownStyle(container, baseDir, templateDir); TokenAggregators = ImmutableList.Create<IMarkdownTokenAggregator>( new HeadingIdAggregator(), new TabGroupAggregator()); } private static void Replace<TSource, TReplacement>(List<IMarkdownRule> blockRules) where TSource : IMarkdownRule where TReplacement : IMarkdownRule, new() { var index = blockRules.FindIndex(item => item is TSource); if (index < 0) { throw new ArgumentException($"{typeof(TSource).Name} should exist!"); } blockRules[index] = new TReplacement(); } private static Func<IMarkdownRewriteEngine, DfmTabGroupBlockToken, IMarkdownToken> GetTabGroupIdRewriter() { var dict = new Dictionary<string, int>(); var tabSelectionInfo = new List<string[]>(); var selectedTabIds = new HashSet<string>(); return (IMarkdownRewriteEngine engine, DfmTabGroupBlockToken token) => { var newToken = RewriteActiveAndVisible( RewriteGroupId(token, dict), tabSelectionInfo); if (token == newToken) { return null; } return newToken; }; } private static DfmTabGroupBlockToken RewriteGroupId(DfmTabGroupBlockToken token, Dictionary<string, int> dict) { var groupId = token.Id; while (true) { if (!dict.TryGetValue(groupId, out int index)) { dict.Add(groupId, 1); break; } else { dict[groupId]++; groupId = groupId + "-" + index.ToString(); } } if (token.Id == groupId) { return token; } return new DfmTabGroupBlockToken(token.Rule, token.Context, groupId, token.Items, token.ActiveTabIndex, token.SourceInfo); } private static DfmTabGroupBlockToken RewriteActiveAndVisible(DfmTabGroupBlockToken token, List<string[]> tabSelectionInfo) { var items = token.Items.ToList(); int firstVisibleTab = ApplyTabVisible(tabSelectionInfo, items); var idAndCountList = GetTabIdAndCountList(items).ToList(); if (idAndCountList.Any(g => g.Item2 > 1)) { Logger.LogWarning($"Duplicate tab id: {string.Join(",", idAndCountList.Where(g => g.Item2 > 1))}.", line: token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.DuplicateTabId); } var active = GetTabActive(token, tabSelectionInfo, items, firstVisibleTab, idAndCountList); return new DfmTabGroupBlockToken(token.Rule, token.Context, token.Id, items.ToImmutableArray(), active, token.SourceInfo); } private static int ApplyTabVisible(List<string[]> tabSelectionInfo, List<DfmTabItemBlockToken> items) { int firstVisibleTab = -1; for (int i = 0; i < items.Count; i++) { var tab = items[i]; var visible = string.IsNullOrEmpty(tab.Condition) || tabSelectionInfo.Any(t => t[0] == tab.Condition); if (visible && firstVisibleTab == -1) { firstVisibleTab = i; } if (tab.Visible != visible) { items[i] = new DfmTabItemBlockToken(tab.Rule, tab.Context, tab.Id, tab.Condition, tab.Title, tab.Content, visible, tab.SourceInfo); } } return firstVisibleTab; } private static IEnumerable<Tuple<string, int>> GetTabIdAndCountList(List<DfmTabItemBlockToken> items) => from tab in items where tab.Visible from id in tab.Id.Split('+') group id by id into g select Tuple.Create(g.Key, g.Count()); private static int GetTabActive(DfmTabGroupBlockToken token, List<string[]> tabSelectionInfo, List<DfmTabItemBlockToken> items, int firstVisibleTab, List<Tuple<string, int>> idAndCountList) { int active = -1; bool hasDifferentSet = false; foreach (var info in tabSelectionInfo) { var set = info.Intersect(from pair in idAndCountList select pair.Item1).ToList(); if (set.Count > 0) { if (set.Count == info.Length && set.Count == idAndCountList.Count) { active = FindActiveIndex(items, info); break; } else { hasDifferentSet = true; active = FindActiveIndex(items, info); if (active != -1) { break; } } } } if (hasDifferentSet) { Logger.LogWarning("Tab group with different tab id set.", line: token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.DifferentTabIdSet); } if (active == -1) { if (firstVisibleTab != -1) { active = firstVisibleTab; tabSelectionInfo.Add((from pair in idAndCountList select pair.Item1).ToArray()); } else { active = 0; Logger.LogWarning("All tabs are hidden in the tab group.", file: token.SourceInfo.File, line: token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.NoVisibleTab); } } return active; } private static int FindActiveIndex(List<DfmTabItemBlockToken> items, string[] info) { for (int i = 0; i < items.Count; i++) { var item = items[i]; if (!item.Visible) { continue; } if (Array.IndexOf(item.Id.Split('+'), info[0]) != -1) { return i; } } return -1; } private static IMarkdownTokenRewriter InitMarkdownStyle(ICompositionContainer container, string baseDir, string templateDir) { try { return MarkdownValidatorBuilder.Create(container, baseDir, templateDir).CreateRewriter(); } catch (Exception ex) { Logger.LogWarning($"Fail to init markdown style, details:{Environment.NewLine}{ex.ToString()}"); } return null; } public DfmEngine CreateDfmEngine(object renderer) { return new DfmEngine( CreateParseContext().SetBaseFolder(_baseDir ?? string.Empty).SetFallbackFolders(_fallbackFolders), MarkdownTokenRewriterFactory.Composite( MarkdownTokenRewriterFactory.FromLambda(GetTabGroupIdRewriter()), Rewriter), renderer, Options) { TokenTreeValidator = TokenTreeValidator, TokenAggregators = TokenAggregators, }; } public override IMarkdownEngine CreateEngine(object renderer) { return CreateDfmEngine(renderer); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ using System; using System.IdentityModel.Selectors; namespace System.IdentityModel.Tokens { /// <summary> /// SecurityKeyElement provides delayed resolution of security keys by resolving the SecurityKeyIdentifierClause or SecurityKeyIdentifier /// only when cryptographic functions are needed. This allows a key clause or identifier that is never used by an application /// to be serialized and deserialzied on and off the wire without issue. /// </summary> public class SecurityKeyElement : SecurityKey { SecurityKey _securityKey; object _keyLock; SecurityTokenResolver _securityTokenResolver; SecurityKeyIdentifier _securityKeyIdentifier; /// <summary> /// Constructor to use when working with SecurityKeyIdentifierClauses /// </summary> /// <param name="securityKeyIdentifierClause">SecurityKeyIdentifierClause that represents a SecuriytKey</param> /// <param name="securityTokenResolver">SecurityTokenResolver that can be resolved to a SecurityKey</param> /// <exception cref="ArgumentNullException">Thrown if the 'clause' is null</exception> public SecurityKeyElement(SecurityKeyIdentifierClause securityKeyIdentifierClause, SecurityTokenResolver securityTokenResolver) { if (securityKeyIdentifierClause == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityKeyIdentifierClause"); } Initialize(new SecurityKeyIdentifier(securityKeyIdentifierClause), securityTokenResolver); } /// <summary> /// Constructor to use when working with SecurityKeyIdentifiers /// </summary> /// <param name="securityKeyIdentifier">SecurityKeyIdentifier that represents a SecuriytKey</param> /// <param name="securityTokenResolver">SecurityTokenResolver that can be resolved to a SecurityKey</param> /// <exception cref="ArgumentNullException">Thrown if the 'securityKeyIdentifier' is null</exception> public SecurityKeyElement(SecurityKeyIdentifier securityKeyIdentifier, SecurityTokenResolver securityTokenResolver) { if (securityKeyIdentifier == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityKeyIdentifier"); } Initialize(securityKeyIdentifier, securityTokenResolver); } void Initialize(SecurityKeyIdentifier securityKeyIdentifier, SecurityTokenResolver securityTokenResolver) { _keyLock = new object(); _securityKeyIdentifier = securityKeyIdentifier; _securityTokenResolver = securityTokenResolver; } /// <summary> /// Decrypts a key using the specified algorithm. /// </summary> /// <param name="algorithm">Algorithm to use when decrypting the key.</param> /// <param name="keyData">Bytes representing the encrypted key.</param> /// <returns>Decrypted bytes.</returns> public override byte[] DecryptKey(string algorithm, byte[] keyData) { if (_securityKey == null) { ResolveKey(); } return _securityKey.DecryptKey(algorithm, keyData); } /// <summary> /// Encrypts a key using the specified algorithm. /// </summary> /// <param name="algorithm">Algorithm to use when encrypting the key.</param> /// <param name="keyData">Bytes representing the key.</param> /// <returns>Encrypted bytes.</returns> public override byte[] EncryptKey(string algorithm, byte[] keyData) { if (_securityKey == null) { ResolveKey(); } return _securityKey.EncryptKey(algorithm, keyData); } /// <summary> /// Answers question: is the algorithm Asymmetric. /// </summary> /// <param name="algorithm">Algorithm to check.</param> /// <returns>True if algorithm will be processed by runtime as Asymmetric.</returns> public override bool IsAsymmetricAlgorithm(string algorithm) { // Copied from System.IdentityModel.CryptoHelper // no need to ResolveKey switch (algorithm) { case SecurityAlgorithms.DsaSha1Signature: case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: return true; default: return false; } } /// <summary> /// Answers question: is the algorithm is supported by this key. /// </summary> /// <param name="algorithm">Algorithm to check.</param> /// <returns>True if algorithm is supported by this key.</returns> public override bool IsSupportedAlgorithm(string algorithm) { if (_securityKey == null) { ResolveKey(); } return _securityKey.IsSupportedAlgorithm(algorithm); } /// <summary> /// Answers question: is the algorithm Symmetric. /// </summary> /// <param name="algorithm">Algorithm to check.</param> /// <returns>True if algorithm will be processed by runtime as Symmetric.</returns> public override bool IsSymmetricAlgorithm(string algorithm) { // Copied from System.IdentityModel.CryptoHelper // no need to ResolveKey. switch (algorithm) { case SecurityAlgorithms.DsaSha1Signature: case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: return false; case SecurityAlgorithms.HmacSha1Signature: case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.TripleDesEncryption: case SecurityAlgorithms.Aes128KeyWrap: case SecurityAlgorithms.Aes192KeyWrap: case SecurityAlgorithms.Aes256KeyWrap: case SecurityAlgorithms.TripleDesKeyWrap: case SecurityAlgorithms.Psha1KeyDerivation: case SecurityAlgorithms.Psha1KeyDerivationDec2005: return true; default: return false; } } /// <summary> /// Gets the key size in bits. /// </summary> /// <returns>Key size in bits.</returns> public override int KeySize { get { if (_securityKey == null) { ResolveKey(); } return _securityKey.KeySize; } } /// <summary> /// Attempts to resolve the _securityKeyIdentifier into a securityKey. If successful, the private _securityKey is set. /// Uses the tokenresolver that was passed in, it may be the case a keyIdentifier can /// generate a securityKey. A RSA key can generate a key with just the public part. /// </summary> /// <returns>void</returns> void ResolveKey() { if (_securityKeyIdentifier == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ski"); } if (_securityKey == null) { lock (_keyLock) { if (_securityKey == null) { if (_securityTokenResolver != null) { for (int i = 0; i < _securityKeyIdentifier.Count; ++i) { if (_securityTokenResolver.TryResolveSecurityKey(_securityKeyIdentifier[i], out _securityKey)) { return; } } } // most likely a public key, do this last if (_securityKeyIdentifier.CanCreateKey) { _securityKey = _securityKeyIdentifier.CreateKey(); return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelper( new SecurityTokenException(SR.GetString(SR.ID2080, _securityTokenResolver == null ? "null" : _securityTokenResolver.ToString(), _securityKeyIdentifier == null ? "null" : _securityKeyIdentifier.ToString())), System.Diagnostics.TraceEventType.Error); } } } } } }
// *********************************************************************** // Copyright (c) 2009-2015 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.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData.TestCaseSourceAttributeFixture; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { [TestFixture] public class TestCaseSourceTests { [Test, TestCaseSource("StaticProperty")] public void SourceCanBeStaticProperty(string source) { Assert.AreEqual("StaticProperty", source); } static IEnumerable StaticProperty { get { return new object[] { new object[] { "StaticProperty" } }; } } [Test] public void SourceUsingInstancePropertyIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstancePropertyAsSource"); Assert.AreEqual(result.Children[0].ResultState, ResultState.NotRunnable); } [Test, TestCaseSource("StaticMethod")] public void SourceCanBeStaticMethod(string source) { Assert.AreEqual("StaticMethod", source); } static IEnumerable StaticMethod() { return new object[] { new object[] { "StaticMethod" } }; } [Test] public void SourceUsingInstanceMethodIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceMethodAsSource"); Assert.AreEqual(result.Children[0].ResultState, ResultState.NotRunnable); } IEnumerable InstanceMethod() { return new object[] { new object[] { "InstanceMethod" } }; } [Test, TestCaseSource("StaticField")] public void SourceCanBeStaticField(string source) { Assert.AreEqual("StaticField", source); } static object[] StaticField = { new object[] { "StaticField" } }; [Test] public void SourceUsingInstanceFieldIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceFieldAsSource"); Assert.AreEqual(result.Children[0].ResultState, ResultState.NotRunnable); } [Test, TestCaseSource(typeof(DataSourceClass))] public void SourceCanBeInstanceOfIEnumerable(string source) { Assert.AreEqual("DataSourceClass", source); } class DataSourceClass : IEnumerable { public DataSourceClass() { } public IEnumerator GetEnumerator() { yield return "DataSourceClass"; } } [Test, TestCaseSource("MyData")] public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q) { Assert.AreEqual(q, n / d); } [TestCaseSource("MyData")] public void TestAttributeIsOptional(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("MyIntData")] public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("EvenNumbers")] public void SourceMayReturnSinglePrimitiveArgumentAlone(int n) { Assert.AreEqual(0, n % 2); } [Test, TestCaseSource("Params")] public int SourceMayReturnArgumentsAsParamSet(int n, int d) { return n / d; } [Test] [TestCaseSource("MyData")] [TestCaseSource("MoreData", Category="Extra")] [TestCase(12, 2, 6)] public void TestMayUseMultipleSourceAttributes(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("FourArgs")] public void TestWithFourArguments(int n, int d, int q, int r) { Assert.AreEqual(q, n / d); Assert.AreEqual(r, n % d); } [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheData")] public void SourceMayBeInAnotherClass(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), "TestCases")] public int SourceMayBeInAnotherClassWithReturn(int n, int d) { return n / d; } [Test] public void IgnoreTakesPrecedenceOverExpectedException() { ITestResult result = TestBuilder.RunParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodCallsIgnore").Children[0]; Assert.AreEqual(ResultState.Ignored, result.ResultState); Assert.AreEqual("Ignore this", result.Message); } [Test] public void CanIgnoreIndividualTestCases() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithIgnoredTestCases"); Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!")); } [Test] public void CanMarkIndividualTestCasesExplicit() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithExplicitTestCases"); Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing")); } [Test] public void HandlesExceptionInTestCaseSource() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithSourceThrowingException").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("System.Exception : my message", result.Message); } [TestCaseSource("exception_source"), Explicit("Used for GUI tests")] public void HandlesExceptionInTestCaseSource_GuiDisplay(string lhs, string rhs) { Assert.AreEqual(lhs, rhs); } static object[] testCases = { new TestCaseData( new string[] { "A" }, new string[] { "B" }) }; [Test, TestCaseSource("testCases")] public void MethodTakingTwoStringArrays(string[] a, string[] b) { Assert.That(a, Is.TypeOf(typeof(string[]))); Assert.That(b, Is.TypeOf(typeof(string[]))); } #region Sources used by the tests static object[] MyData = new object[] { new object[] { 12, 3, 4 }, new object[] { 12, 4, 3 }, new object[] { 12, 6, 2 } }; static object[] MyIntData = new object[] { new int[] { 12, 3, 4 }, new int[] { 12, 4, 3 }, new int[] { 12, 6, 2 } }; static object[] FourArgs = new object[] { new TestCaseData( 12, 3, 4, 0 ), new TestCaseData( 12, 4, 3, 0 ), new TestCaseData( 12, 5, 2, 2 ) }; static int[] EvenNumbers = new int[] { 2, 4, 6, 8 }; static object[] MoreData = new object[] { new object[] { 12, 1, 12 }, new object[] { 12, 2, 6 } }; static object[] Params = new object[] { new TestCaseData(24, 3).Returns(8), new TestCaseData(24, 2).Returns(12) }; private class DivideDataProvider { public static IEnumerable HereIsTheData { get { //yield return new TestCaseData(0, 0, 0) // .SetName("ThisOneShouldThrow") // .SetDescription("Demonstrates use of ExpectedException") // .SetCategory("Junk") // .SetProperty("MyProp", "zip") // .Throws(typeof(System.DivideByZeroException)); yield return new object[] { 100, 20, 5 }; yield return new object[] { 100, 4, 25 }; } } } public class DivideDataProviderWithReturnValue { public static IEnumerable TestCases { get { return new object[] { new TestCaseData(12, 3).Returns(4).SetName("TC1"), new TestCaseData(12, 2).Returns(6).SetName("TC2"), new TestCaseData(12, 4).Returns(3).SetName("TC3") }; } } } private static IEnumerable exception_source { get { yield return new TestCaseData("a", "a"); yield return new TestCaseData("b", "b"); throw new System.Exception("my message"); } } #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. */ using System; using Document = Lucene.Net.Documents.Document; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using Term = Lucene.Net.Index.Term; namespace Lucene.Net.Search { /// <summary>An abstract base class for search implementations. /// Implements the main search methods. /// /// <p>Note that you can only access Hits from a Searcher as long as it is /// not yet closed, otherwise an IOException will be thrown. /// </summary> public abstract class Searcher : Lucene.Net.Search.Searchable { public Searcher() { InitBlock(); } private void InitBlock() { similarity = Similarity.GetDefault(); } /// <summary>Returns the documents matching <code>query</code>. </summary> /// <throws> BooleanQuery.TooManyClauses </throws> /// [System.Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int) instead.")] public Hits Search(Query query) { return Search(query, (Filter) null); } /// <summary>Returns the documents matching <code>query</code> and /// <code>filter</code>. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> [System.Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int) instead.")] public virtual Hits Search(Query query, Filter filter) { return new Hits(this, query, filter); } /// <summary>Returns documents matching <code>query</code> sorted by /// <code>sort</code>. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> [System.Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int, Sort) instead.")] public virtual Hits Search(Query query, Sort sort) { return new Hits(this, query, null, sort); } /// <summary>Returns documents matching <code>query</code> and <code>filter</code>, /// sorted by <code>sort</code>. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> [System.Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int, Sort) instead.")] public virtual Hits Search(Query query, Filter filter, Sort sort) { return new Hits(this, query, filter, sort); } /// <summary>Search implementation with arbitrary sorting. Finds /// the top <code>n</code> hits for <code>query</code>, applying /// <code>filter</code> if non-null, and sorting the hits by the criteria in /// <code>sort</code>. /// /// <p>Applications should usually call {@link /// Searcher#Search(Query,Filter,Sort)} instead. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> public virtual TopFieldDocs Search(Query query, Filter filter, int n, Sort sort) { return Search(CreateWeight(query), filter, n, sort); } /// <summary>Lower-level search API. /// /// <p>{@link HitCollector#Collect(int,float)} is called for every matching document. /// /// <p>Applications should only use this if they need <i>all</i> of the /// matching documents. The high-level search API ({@link /// Searcher#Search(Query)}) is usually more efficient, as it skips /// non-high-scoring hits. /// <p>Note: The <code>score</code> passed to this method is a raw score. /// In other words, the score will not necessarily be a float whose value is /// between 0 and 1. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> public virtual void Search(Query query, HitCollector results) { Search(query, (Filter) null, results); } /// <summary>Lower-level search API. /// /// <p>{@link HitCollector#Collect(int,float)} is called for every matching document. /// <br>HitCollector-based access to remote indexes is discouraged. /// /// <p>Applications should only use this if they need <i>all</i> of the /// matching documents. The high-level search API ({@link /// Searcher#Search(Query, Filter, int)}) is usually more efficient, as it skips /// non-high-scoring hits. /// /// </summary> /// <param name="query">to match documents /// </param> /// <param name="filter">if non-null, used to permit documents to be collected /// </param> /// <param name="results">to receive hits /// </param> /// <throws> BooleanQuery.TooManyClauses </throws> public virtual void Search(Query query, Filter filter, HitCollector results) { Search(CreateWeight(query), filter, results); } /// <summary>Finds the top <code>n</code> /// hits for <code>query</code>, applying <code>filter</code> if non-null. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> public virtual TopDocs Search(Query query, Filter filter, int n) { return Search(CreateWeight(query), filter, n); } /// <summary>Finds the top <code>n</code> /// hits for <code>query</code>, applying <code>filter</code> if non-null. /// </summary> /// <throws> BooleanQuery.TooManyClauses </throws> public virtual TopDocs Search(Query query, int n) { return Search(CreateWeight(query), null, n); } /// <summary>Returns an Explanation that describes how <code>doc</code> scored against /// <code>query</code>. /// /// <p>This is intended to be used in developing Similarity implementations, /// and, for good performance, should not be displayed with every hit. /// Computing an explanation is as expensive as executing the query over the /// entire index. /// </summary> public virtual Explanation Explain(Query query, int doc) { return Explain(CreateWeight(query), doc); } /// <summary>The Similarity implementation used by this searcher. </summary> private Similarity similarity; /// <summary>Expert: Set the Similarity implementation used by this Searcher. /// /// </summary> /// <seealso cref="Similarity#SetDefault(Similarity)"> /// </seealso> public virtual void SetSimilarity(Similarity similarity) { this.similarity = similarity; } /// <summary>Expert: Return the Similarity implementation used by this Searcher. /// /// <p>This defaults to the current value of {@link Similarity#GetDefault()}. /// </summary> public virtual Similarity GetSimilarity() { return this.similarity; } /// <summary> creates a weight for <code>query</code></summary> /// <returns> new weight /// </returns> protected internal virtual Weight CreateWeight(Query query) { return query.Weight(this); } // inherit javadoc public virtual int[] DocFreqs(Term[] terms) { int[] result = new int[terms.Length]; for (int i = 0; i < terms.Length; i++) { result[i] = DocFreq(terms[i]); } return result; } /* The following abstract methods were added as a workaround for GCJ bug #15411. * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=15411 */ abstract public void Search(Weight weight, Filter filter, HitCollector results); abstract public void Close(); abstract public int DocFreq(Term term); abstract public int MaxDoc(); abstract public TopDocs Search(Weight weight, Filter filter, int n); abstract public Document Doc(int i); abstract public Query Rewrite(Query query); abstract public Explanation Explain(Weight weight, int doc); abstract public TopFieldDocs Search(Weight weight, Filter filter, int n, Sort sort); /* End patch for GCJ bug #15411. */ public abstract Lucene.Net.Documents.Document Doc(int param1, Lucene.Net.Documents.FieldSelector param2); } }
// // EngineBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Eric Maupin <ermau@xamarin.com> // // Copyright (c) 2011-2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Reflection; using System.IO; using Xwt.Drawing; using System.Collections.Generic; namespace Xwt.Backends { public abstract class ToolkitEngineBackend { Dictionary<Type,Type> backendTypes; Dictionary<Type,Type> backendTypesByFrontend; Toolkit toolkit; bool isGuest; /// <summary> /// Initialize the specified toolkit. /// </summary> /// <param name="toolkit">Toolkit to initialize.</param> /// <param name="isGuest">If set to <c>true</c> the toolkit will be initialized as guest of another toolkit.</param> internal void Initialize (Toolkit toolkit, bool isGuest) { this.toolkit = toolkit; this.isGuest = isGuest; if (backendTypes == null) { backendTypes = new Dictionary<Type, Type> (); backendTypesByFrontend = new Dictionary<Type, Type> (); InitializeBackends (); } InitializeApplication (); } /// <summary> /// Gets the toolkit engine backend. /// </summary> /// <returns>The toolkit backend.</returns> /// <typeparam name="T">The Type of the toolkit backend.</typeparam> public static T GetToolkitBackend<T> () where T : ToolkitEngineBackend { return (T)Toolkit.GetToolkitBackend (typeof (T)); } /// <summary> /// Gets the application context. /// </summary> /// <value>The application context.</value> public ApplicationContext ApplicationContext { get { return toolkit.Context; } } /// <summary> /// Gets a value indicating whether this toolkit is running as a guest of another toolkit /// </summary> /// <remarks> /// A toolkit is a guest toolkit when it is loaded after the main toolkit of an application /// </remarks> public bool IsGuest { get { return isGuest; } } /// <summary> /// Initializes the application. /// </summary> public virtual void InitializeApplication () { } /// <summary> /// Initializes the widget registry used by the application. /// </summary> /// <remarks> /// Don't do any toolkit initialization there, do them in InitializeApplication. /// Override to register the backend classes, by calling RegisterBackend() methods. /// </remarks> public virtual void InitializeBackends () { } /// <summary> /// Runs the main GUI loop /// </summary> public abstract void RunApplication (); /// <summary> /// Exits the main GUI loop /// </summary> public abstract void ExitApplication (); /// <summary> /// Releases all resource used by the <see cref="Xwt.Backends.ToolkitEngineBackend"/> object. /// </summary> public virtual void Dispose () { } /// <summary> /// Asynchronously invokes <paramref name="action"/> on the engine UI thread. /// </summary> /// <param name="action">The action to invoke.</param> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> public abstract void InvokeAsync (Action action); /// <summary> /// Synchronously invokes <paramref name="action"/> on the engine UI thread. /// </summary> /// <param name="action">The action to invoke.</param> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> public abstract void Invoke (Action action); /// <summary> /// Begins invoking <paramref name="action"/> on a timer period of <paramref name="timeSpan"/>. /// </summary> /// <param name="action">The function to invoke. Returning <c>false</c> stops the timer.</param> /// <param name="timeSpan">The period before the initial invoke and between subsequent invokes.</param> /// <returns>An identifying object that can be used to cancel the timer with <seealso cref="CancelTimerInvoke"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> /// <seealso cref="CancelTimerInvoke"/> public abstract object TimerInvoke (Func<bool> action, TimeSpan timeSpan); /// <summary> /// Cancels an invoke timer started from <see cref="TimerInvoke"/>. /// </summary> /// <param name="id">The unique object returned from <see cref="TimerInvoke"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception> public abstract void CancelTimerInvoke (object id); /// <summary> /// Gets a reference to the native widget wrapped by an XWT widget /// </summary> /// <returns> /// The native widget. /// </returns> /// <param name='w'> /// A widget /// </param> public abstract object GetNativeWidget (Widget w); /// <summary> /// Gets a reference to the image object wrapped by an XWT Image /// </summary> /// <returns> /// The native image. /// </returns> /// <param name='image'> /// An image. /// </param> public virtual object GetNativeImage (Image image) { return Toolkit.GetBackend (image); } /// <summary> /// Dispatches pending events in the UI event queue /// </summary> public abstract void DispatchPendingEvents (); /// <summary> /// Gets the backend for a native window. /// </summary> /// <returns> /// The backend for the window. /// </returns> /// <param name='nativeWindow'> /// A native window reference. /// </param> public abstract IWindowFrameBackend GetBackendForWindow (object nativeWindow); /// <summary> /// Gets a native window reference from an Xwt window. /// </summary> /// <returns> The native window object. </returns> /// <param name='window'> The Xwt window. </param> public virtual object GetNativeWindow (WindowFrame window) { if (window == null) return null; return GetNativeWindow (window.GetBackend () as IWindowFrameBackend); } /// <summary> /// Gets a native window reference from an Xwt window backend. /// </summary> /// <returns> The native window object. </returns> /// <param name='backend'> The Xwt window backend. </param> public abstract object GetNativeWindow (IWindowFrameBackend backend); /// <summary> /// Gets the native parent window of a widget /// </summary> /// <returns> /// The native parent window. /// </returns> /// <param name='w'> /// A widget /// </param> /// <remarks> /// This method is used by XWT to get the window of a widget, when the widget is /// embedded in a native application /// </remarks> public virtual object GetNativeParentWindow (Widget w) { return null; } /// <summary> /// Gets the backend for a native drawing context. /// </summary> /// <returns>The backend for context.</returns> /// <param name="nativeContext">The native context.</param> public virtual object GetBackendForContext (object nativeWidget, object nativeContext) { return nativeContext; } /// <summary> /// Gets the backend for a native image. /// </summary> /// <returns>The image backend .</returns> /// <param name="nativeImage">The native image.</param> public virtual object GetBackendForImage (object nativeImage) { return nativeImage; } /// <summary> /// Gets a value indicating whether this <see cref="ToolkitEngineBackend" /> handles size negotiation on its own /// </summary> /// <value> /// <c>true</c> if the engine backend handles size negotiation; otherwise, <c>false</c>. /// </value> public virtual bool HandlesSizeNegotiation { get { return false; } } void CheckInitialized () { if (backendTypes == null) throw new InvalidOperationException ("XWT toolkit not initialized"); } /// <summary> /// Creates a backend for a frontend. /// </summary> /// <returns>The backend for the specified frontend.</returns> /// <param name="frontendType">The Frontend type.</param> internal IBackend CreateBackendForFrontend (Type frontendType) { CheckInitialized (); Type bt = null; if (!backendTypesByFrontend.TryGetValue (frontendType, out bt)) { var attr = (BackendTypeAttribute) Attribute.GetCustomAttribute (frontendType, typeof(BackendTypeAttribute), true); if (attr == null || attr.Type == null) throw new InvalidOperationException ("Backend type not specified for type: " + frontendType); if (!typeof(IBackend).IsAssignableFrom (attr.Type)) throw new InvalidOperationException ("Backend type for frontend '" + frontendType + "' is not a IBackend implementation"); bt = GetBackendImplementationType (attr.Type); backendTypesByFrontend [frontendType] = bt; } if (bt == null) return null; return (IBackend) Activator.CreateInstance (bt); } /// <summary> /// Creates the backend. /// </summary> /// <returns>The backend.</returns> /// <param name="backendType">The Backend type.</param> internal object CreateBackend (Type backendType) { CheckInitialized (); Type bt = GetBackendImplementationType (backendType); if (bt == null) return null; var res = Activator.CreateInstance (bt); if (!backendType.IsInstanceOfType (res)) throw new InvalidOperationException ("Invalid backend type. Expected '" + backendType + "' found '" + res.GetType () + "'"); if (res is BackendHandler) ((BackendHandler)res).Initialize (toolkit); return res; } /// <summary> /// Gets the type that implements the provided backend interface /// </summary> /// <returns>The backend implementation type.</returns> /// <param name="backendType">Backend interface type.</param> protected virtual Type GetBackendImplementationType (Type backendType) { Type bt; backendTypes.TryGetValue (backendType, out bt); return bt; } /// <summary> /// Creates the backend. /// </summary> /// <returns>The backend.</returns> /// <typeparam name="T">The Backend type.</typeparam> internal T CreateBackend<T> () { return (T) CreateBackend (typeof(T)); } /// <summary> /// Registers a backend for an Xwt backend interface. /// </summary> /// <typeparam name="Backend">The backend Type</typeparam> /// <typeparam name="Implementation">The Xwt interface implemented by the backend</typeparam> public void RegisterBackend<Backend, Implementation> () where Implementation: Backend { CheckInitialized (); backendTypes [typeof(Backend)] = typeof(Implementation); } /// <summary> /// Creates the Xwt frontend for a backend. /// </summary> /// <returns>The Xwt frontend.</returns> /// <param name="backend">The backend.</param> /// <typeparam name="T">The frontend type.</typeparam> public T CreateFrontend<T> (object backend) { return (T) Activator.CreateInstance (typeof(T), backend); } /// <summary> /// Registers a callback to be invoked just before the execution returns to the main loop /// </summary> /// <param name='action'> /// Callback to execute /// </param> /// <remarks> /// The default implementation does the invocation using InvokeAsync. /// </remarks> public virtual void InvokeBeforeMainLoop (Action action) { InvokeAsync (action); } /// <summary> /// Determines whether a widget has a native parent widget /// </summary> /// <returns><c>true</c> if the widget has native parent; otherwise, <c>false</c>.</returns> /// <param name="w">The widget.</param> /// <remarks>This funciton is used to determine if a widget is a child of another non-XWT widget /// </remarks> public abstract bool HasNativeParent (Widget w); /// <summary> /// Renders a widget into a bitmap /// </summary> /// <param name="w">A widget</param> /// <returns>An image backend</returns> public virtual object RenderWidget (Widget w) { throw new NotSupportedException (); } /// <summary> /// Renders an image at the provided native context /// </summary> /// <param name="nativeContext">Native context.</param> /// <param name="img">Image.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> public virtual void RenderImage (object nativeWidget, object nativeContext, ImageDescription img, double x, double y) { } /// <summary> /// Gets the bounds of a native widget in screen coordinates. /// </summary> /// <returns>The screen bounds relative to <see cref="P:Xwt.Desktop.Bounds"/>.</returns> /// <param name="nativeWidget">The native widget.</param> /// <exception cref="NotSupportedException">This toolkit does not support this operation.</exception> /// <exception cref="InvalidOperationException"><paramref name="nativeWidget"/> does not belong to this toolkit.</exception> public virtual Rectangle GetScreenBounds (object nativeWidget) { throw new NotSupportedException(); } /// <summary> /// Gets the information about Xwt features supported by the toolkit. /// </summary> /// <value>The supported features.</value> public virtual ToolkitFeatures SupportedFeatures { get { return ToolkitFeatures.All; } } } }
using System; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; namespace CommandGen { public class VkCommandParser { IVkEntityInspector mInspector; public VkCommandParser (IVkEntityInspector inspector) { mInspector = inspector; } void ParseNativeInterface (XElement top, VkCommandInfo result) { var function = new VkNativeInterface (); function.Name = result.Name; function.ReturnType = result.CsReturnType; int index = 0; foreach (var param in top.Elements ("param")) { var arg = new VkFunctionArgument { Index = index }; var tokens = param.Value.Split (new[] { ' ', '[', ']' }, StringSplitOptions.RemoveEmptyEntries); arg.IsFixedArray = false; if (tokens.Length == 2) { // usually instance arg.ArgumentCppType = tokens [0]; arg.IsConst = false; // or int } else if (tokens.Length == 3) { // possible const pointer arg.IsConst = (tokens [0] == "const"); arg.ArgumentCppType = tokens [1]; } else if (tokens.Length == 4) { // const float array arg.IsConst = (tokens [0] == "const"); arg.ArgumentCppType = tokens [1]; arg.ArrayConstant = tokens [3]; arg.IsFixedArray = true; } arg.IsPointer = arg.ArgumentCppType.IndexOf ('*') >= 0; arg.Name = param.Element ("name").Value; arg.BaseCppType = param.Element ("type").Value; arg.BaseCsType = mInspector.GetTypeCsName (arg.BaseCppType, "type"); XAttribute optionalAttr = param.Attribute ("optional"); arg.IsOptional = optionalAttr != null && optionalAttr.Value == "true"; arg.ByReference = optionalAttr != null && optionalAttr.Value == "false,true"; VkStructInfo structFound; arg.IsStruct = mInspector.Structs.TryGetValue(arg.BaseCsType, out structFound); XAttribute lengthAttr = param.Attribute ("len"); if (lengthAttr != null) { var lengths = lengthAttr.Value.Split (',').Where (s => s != "null-terminated").ToArray (); if (lengths.Length != 1) { //throw new NotImplementedException(string.Format("param.len != 1 ({0} found)", lengths.Length)); arg.LengthVariable = null; } else { arg.LengthVariable = lengths[0]; } } function.Arguments.Add (arg); arg.IsNullableIntPtr = arg.IsOptional && arg.IsPointer && !arg.IsFixedArray && arg.LengthVariable == null; // DETERMINE CSHARP TYPE if (arg.ArgumentCppType == "char*") { arg.ArgumentCsType = "string"; } else if (arg.ArgumentCppType == "void*") { arg.ArgumentCsType = "IntPtr"; } else if (arg.ArgumentCppType == "void**") { arg.ArgumentCsType = "IntPtr"; } else { VkHandleInfo found; if (mInspector.Handles.TryGetValue(arg.BaseCsType, out found)) { arg.ArgumentCsType = found.csType; } else if (arg.IsNullableIntPtr) { // REQUIRES MARSHALLING FOR NULLS IN ALLOCATOR arg.ArgumentCsType = "IntPtr"; } else { arg.ArgumentCsType = arg.BaseCsType; } } if (structFound != null && structFound.returnedonly) arg.UseOut = false; else arg.UseOut = !arg.IsConst && arg.IsPointer; arg.IsBlittable = mInspector.BlittableTypes.Contains(arg.ArgumentCsType); ++index; } // USE POINTER / unsafe ONLY IF // ALL ARGUMENTS ARE BLITTABLE // && >= 1 ARGUMENTS // && >= 1 BLITTABLE STRUCT && NOT OPTIONAL POINTER bool useUnsafe = function.Arguments.Count > 0; uint noOfBlittableStructs = 0; foreach (var arg in function.Arguments) { if (!arg.IsBlittable) { useUnsafe = false; } if (arg.IsStruct && arg.IsBlittable && !arg.IsNullableIntPtr) { noOfBlittableStructs++; } } function.UseUnsafe = useUnsafe && noOfBlittableStructs > 0; // Add [In, Out] attribute to struct array variables if (!function.UseUnsafe) { foreach (var arg in function.Arguments) { if (arg.LengthVariable != null && arg.IsStruct && !arg.IsBlittable) { // SINGULAR MARSHALLED STRUCT ARRAY INSTANCES arg.Attribute = "[In, Out]"; } else if (arg.IsFixedArray && !arg.IsStruct && arg.IsBlittable) { // PRETTY MUCH FOR BLENDCONSTANTS arg.Attribute = string.Format("[MarshalAs(UnmanagedType.LPArray, SizeConst = {0})]", arg.ArrayConstant); } else if (arg.IsStruct && !arg.IsBlittable && !arg.IsNullableIntPtr) { // SINGULAR MARSHALLED STRUCT INSTANCES arg.Attribute = "[In, Out]"; } //else //{ // // Add attribute // VkStructInfo readOnlyStruct; // if (!arg.IsOptional && mInspector.Structs.TryGetValue(arg.BaseCsType, out readOnlyStruct) && readOnlyStruct.returnedonly) // arg.Attribute = "[In, Out]"; //} } } result.NativeFunction = function; } void ParseMethodSignature (XElement top, VkCommandInfo result) { var signature = new VkMethodSignature (); signature.Name = (result.Name.StartsWith ("vk", StringComparison.InvariantCulture)) ? result.Name.Substring (2) : result.Name; signature.ReturnType = result.CsReturnType; var arguments = new Dictionary<string, VkFunctionArgument> (); foreach (var arg in result.NativeFunction.Arguments) { arguments.Add (arg.Name, arg); } // FILTER OUT VALUES FOR SIGNATURE foreach (var arg in result.NativeFunction.Arguments) { // object reference if (mInspector.Handles.ContainsKey(arg.BaseCsType) && ! arg.IsPointer) { if (arg.Index == 0) { result.FirstInstance = arg; arguments.Remove(arg.Name); } } VkFunctionArgument localLength; if (arg.LengthVariable != null && arguments.TryGetValue (arg.LengthVariable, out localLength)) { result.LocalVariables.Add (localLength); arguments.Remove (arg.LengthVariable); } } signature.Parameters = (from arg in arguments.Values orderby arg.Index ascending select new VkMethodParameter{ Name = arg.Name, Source = arg }).ToList (); foreach (var param in signature.Parameters) { param.BaseCsType = param.Source.BaseCsType; param.ArgumentCsType = param.Source.ArgumentCsType; param.UseOut = param.Source.UseOut; param.IsFixedArray = param.Source.IsFixedArray; param.IsArrayParameter = !param.Source.IsConst && param.Source.LengthVariable != null; param.IsNullableType = param.Source.IsPointer && param.Source.IsOptional; param.UseRef = param.Source.UseOut && param.Source.IsBlittable && !param.IsArrayParameter; } result.MethodSignature = signature; } void ParseFunctionCalls (XElement top, VkCommandInfo result) { //throw new NotImplementedException (); int noOfOuts = 0; int noOfArguments = result.NativeFunction.Arguments.Count; for (int i = 0; i < noOfArguments; ++i) { var arg = result.NativeFunction.Arguments [i]; if (arg.UseOut) { ++noOfOuts; } } if (result.LocalVariables.Count > 0) { foreach (var local in result.LocalVariables) { var letVar = new VkVariableDeclaration{ Source = local }; result.Lines.Add (letVar); } var fetch = new VkFunctionCall{ Call = result.NativeFunction }; result.Calls.Add (fetch); // method call result.Lines.Add (fetch); if (result.NativeFunction.ReturnType != "void") { var errorCheck = new VkReturnTypeCheck{ReturnType=result.NativeFunction.ReturnType}; result.Lines.Add (errorCheck); } foreach (var arg in result.NativeFunction.Arguments) { var item = new VkCallArgument{Source = arg }; item.IsNull = (arg.UseOut && arg.LengthVariable != null); fetch.Arguments.Add (item); } } foreach (var param in result.MethodSignature.Parameters) { if (param.UseOut) { var letVar = new VkVariableDeclaration{ Source = param.Source }; result.Lines.Add (letVar); } } var body = new VkFunctionCall{ Call = result.NativeFunction }; result.Calls.Add (body); foreach (var arg in result.NativeFunction.Arguments) { var item = new VkCallArgument{Source = arg }; item.IsNull = (arg.UseOut && arg.LengthVariable != null); body.Arguments.Add (item); } result.Lines.Add (body); } public bool Parse (XElement top, out VkCommandInfo info) { var protoElem = top.Element ("proto"); if (protoElem != null) { var result = new VkCommandInfo(); result.Name = protoElem.Element("name").Value; result.CppReturnType = protoElem.Element("type").Value; result.CsReturnType = mInspector.GetTypeCsName(result.CppReturnType, "type"); ParseNativeInterface(top, result); ParseMethodSignature(top, result); ParseFunctionCalls(top, result); info = result; return true; } else { info = null; return false; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using FileDocument = Lucene.Net.Demo.FileDocument; using Document = Lucene.Net.Documents.Document; using Directory = Lucene.Net.Store.Directory; using FSDirectory = Lucene.Net.Store.FSDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { /// <summary>JUnit adaptation of an older test case DocTest. /// /// </summary> /// <version> $Id: TestDoc.java 780770 2009-06-01 18:34:10Z uschindler $ /// </version> [TestFixture] public class TestDoc:LuceneTestCase { /// <summary>Main for running test case by itself. </summary> [STAThread] public static void Main(System.String[] args) { // TestRunner.run(new TestSuite(typeof(TestDoc))); // {{Aroush-2.9}} how is this done in NUnit? } private System.IO.FileInfo workDir; private System.IO.FileInfo indexDir; private System.Collections.ArrayList files; /// <summary>Set the test case. This test case needs /// a few text files created in the current working directory. /// </summary> [SetUp] public override void SetUp() { base.SetUp(); workDir = new System.IO.FileInfo(System.IO.Path.Combine(SupportClass.AppSettings.Get("tempDir", ""), "TestDoc")); System.IO.Directory.CreateDirectory(workDir.FullName); indexDir = new System.IO.FileInfo(System.IO.Path.Combine(workDir.FullName, "testIndex")); System.IO.Directory.CreateDirectory(indexDir.FullName); Directory directory = FSDirectory.Open(indexDir); directory.Close(); files = new System.Collections.ArrayList(); files.Add(CreateOutput("test.txt", "This is the first test file")); files.Add(CreateOutput("test2.txt", "This is the second test file")); } private System.IO.FileInfo CreateOutput(System.String name, System.String text) { System.IO.StreamWriter fw = null; System.IO.StreamWriter pw = null; try { System.IO.FileInfo f = new System.IO.FileInfo(System.IO.Path.Combine(workDir.FullName, name)); bool tmpBool; if (System.IO.File.Exists(f.FullName)) tmpBool = true; else tmpBool = System.IO.Directory.Exists(f.FullName); if (tmpBool) { bool tmpBool2; if (System.IO.File.Exists(f.FullName)) { System.IO.File.Delete(f.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(f.FullName)) { System.IO.Directory.Delete(f.FullName); tmpBool2 = true; } else tmpBool2 = false; bool generatedAux = tmpBool2; } fw = new System.IO.StreamWriter(f.FullName, false, System.Text.Encoding.Default); pw = new System.IO.StreamWriter(fw.BaseStream, fw.Encoding); pw.WriteLine(text); return f; } finally { if (pw != null) { pw.Close(); } } } /// <summary>This test executes a number of merges and compares the contents of /// the segments created when using compound file or not using one. /// /// TODO: the original test used to print the segment contents to System.out /// for visual validation. To have the same effect, a new method /// checkSegment(String name, ...) should be created that would /// assert various things about the segment. /// </summary> [Test] public virtual void TestIndexAndMerge() { System.IO.MemoryStream sw = new System.IO.MemoryStream(); System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(sw); Directory directory = FSDirectory.Open(indexDir); IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); SegmentInfo si1 = IndexDoc(writer, "test.txt"); PrintSegment(out_Renamed, si1); SegmentInfo si2 = IndexDoc(writer, "test2.txt"); PrintSegment(out_Renamed, si2); writer.Close(); SegmentInfo siMerge = Merge(si1, si2, "merge", false); PrintSegment(out_Renamed, siMerge); SegmentInfo siMerge2 = Merge(si1, si2, "merge2", false); PrintSegment(out_Renamed, siMerge2); SegmentInfo siMerge3 = Merge(siMerge, siMerge2, "merge3", false); PrintSegment(out_Renamed, siMerge3); directory.Close(); out_Renamed.Close(); sw.Close(); System.String multiFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray()); //System.out.println(multiFileOutput); sw = new System.IO.MemoryStream(); out_Renamed = new System.IO.StreamWriter(sw); directory = FSDirectory.Open(indexDir); writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); si1 = IndexDoc(writer, "test.txt"); PrintSegment(out_Renamed, si1); si2 = IndexDoc(writer, "test2.txt"); PrintSegment(out_Renamed, si2); writer.Close(); siMerge = Merge(si1, si2, "merge", true); PrintSegment(out_Renamed, siMerge); siMerge2 = Merge(si1, si2, "merge2", true); PrintSegment(out_Renamed, siMerge2); siMerge3 = Merge(siMerge, siMerge2, "merge3", true); PrintSegment(out_Renamed, siMerge3); directory.Close(); out_Renamed.Close(); sw.Close(); System.String singleFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray()); Assert.AreEqual(multiFileOutput, singleFileOutput); } private SegmentInfo IndexDoc(IndexWriter writer, System.String fileName) { System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(workDir.FullName, fileName)); Document doc = FileDocument.Document(file); writer.AddDocument(doc); writer.Flush(); return writer.NewestSegment(); } private SegmentInfo Merge(SegmentInfo si1, SegmentInfo si2, System.String merged, bool useCompoundFile) { SegmentReader r1 = SegmentReader.Get(si1); SegmentReader r2 = SegmentReader.Get(si2); SegmentMerger merger = new SegmentMerger(si1.dir, merged); merger.Add(r1); merger.Add(r2); merger.Merge(); merger.CloseReaders(); if (useCompoundFile) { System.Collections.Generic.ICollection<string> filesToDelete = merger.CreateCompoundFile(merged + ".cfs"); for (System.Collections.IEnumerator iter = filesToDelete.GetEnumerator(); iter.MoveNext(); ) { si1.dir.DeleteFile((System.String) iter.Current); } } return new SegmentInfo(merged, si1.docCount + si2.docCount, si1.dir, useCompoundFile, true); } private void PrintSegment(System.IO.StreamWriter out_Renamed, SegmentInfo si) { SegmentReader reader = SegmentReader.Get(si); for (int i = 0; i < reader.NumDocs(); i++) { out_Renamed.WriteLine(reader.Document(i)); } TermEnum tis = reader.Terms(); while (tis.Next()) { out_Renamed.Write(tis.Term()); out_Renamed.WriteLine(" DF=" + tis.DocFreq()); TermPositions positions = reader.TermPositions(tis.Term()); try { while (positions.Next()) { out_Renamed.Write(" doc=" + positions.Doc()); out_Renamed.Write(" TF=" + positions.Freq()); out_Renamed.Write(" pos="); out_Renamed.Write(positions.NextPosition()); for (int j = 1; j < positions.Freq(); j++) out_Renamed.Write("," + positions.NextPosition()); out_Renamed.WriteLine(""); } } finally { positions.Close(); } } tis.Close(); reader.Close(); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Generators; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Styling; using Avalonia.VisualTree; namespace Avalonia.Controls.Primitives { /// <summary> /// An <see cref="ItemsControl"/> that maintains a selection. /// </summary> /// <remarks> /// <para> /// <see cref="SelectingItemsControl"/> provides a base class for <see cref="ItemsControl"/>s /// that maintain a selection (single or multiple). By default only its /// <see cref="SelectedIndex"/> and <see cref="SelectedItem"/> properties are visible; the /// current multiple selection <see cref="SelectedItems"/> together with the /// <see cref="SelectionMode"/> properties are protected, however a derived class can expose /// these if it wishes to support multiple selection. /// </para> /// <para> /// <see cref="SelectingItemsControl"/> maintains a selection respecting the current /// <see cref="SelectionMode"/> but it does not react to user input; this must be handled in a /// derived class. It does, however, respond to <see cref="IsSelectedChangedEvent"/> events /// from items and updates the selection accordingly. /// </para> /// </remarks> public class SelectingItemsControl : ItemsControl { /// <summary> /// Defines the <see cref="AutoScrollToSelectedItem"/> property. /// </summary> public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty = AvaloniaProperty.Register<SelectingItemsControl, bool>( nameof(AutoScrollToSelectedItem), defaultValue: true); /// <summary> /// Defines the <see cref="SelectedIndex"/> property. /// </summary> public static readonly DirectProperty<SelectingItemsControl, int> SelectedIndexProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, int>( nameof(SelectedIndex), o => o.SelectedIndex, (o, v) => o.SelectedIndex = v, unsetValue: -1); /// <summary> /// Defines the <see cref="SelectedItem"/> property. /// </summary> public static readonly DirectProperty<SelectingItemsControl, object> SelectedItemProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, object>( nameof(SelectedItem), o => o.SelectedItem, (o, v) => o.SelectedItem = v, defaultBindingMode: BindingMode.TwoWay); /// <summary> /// Defines the <see cref="SelectedItems"/> property. /// </summary> protected static readonly DirectProperty<SelectingItemsControl, IList> SelectedItemsProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, IList>( nameof(SelectedItems), o => o.SelectedItems, (o, v) => o.SelectedItems = v); /// <summary> /// Defines the <see cref="SelectionMode"/> property. /// </summary> protected static readonly StyledProperty<SelectionMode> SelectionModeProperty = AvaloniaProperty.Register<SelectingItemsControl, SelectionMode>( nameof(SelectionMode)); /// <summary> /// Event that should be raised by items that implement <see cref="ISelectable"/> to /// notify the parent <see cref="SelectingItemsControl"/> that their selection state /// has changed. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent = RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>( "IsSelectedChanged", RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="SelectionChanged"/> event. /// </summary> public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = RoutedEvent.Register<SelectingItemsControl, SelectionChangedEventArgs>( "SelectionChanged", RoutingStrategies.Bubble); private static readonly IList Empty = new object[0]; private int _selectedIndex = -1; private object _selectedItem; private IList _selectedItems; private bool _ignoreContainerSelectionChanged; private bool _syncingSelectedItems; private int _updateCount; private int _updateSelectedIndex; private IList _updateSelectedItems; /// <summary> /// Initializes static members of the <see cref="SelectingItemsControl"/> class. /// </summary> static SelectingItemsControl() { IsSelectedChangedEvent.AddClassHandler<SelectingItemsControl>(x => x.ContainerSelectionChanged); } /// <summary> /// Occurs when the control's selection changes. /// </summary> public event EventHandler<SelectionChangedEventArgs> SelectionChanged { add { AddHandler(SelectionChangedEvent, value); } remove { RemoveHandler(SelectionChangedEvent, value); } } /// <summary> /// Gets or sets a value indicating whether to automatically scroll to newly selected items. /// </summary> public bool AutoScrollToSelectedItem { get { return GetValue(AutoScrollToSelectedItemProperty); } set { SetValue(AutoScrollToSelectedItemProperty, value); } } /// <summary> /// Gets or sets the index of the selected item. /// </summary> public int SelectedIndex { get { return _selectedIndex; } set { if (_updateCount == 0) { SetAndRaise(SelectedIndexProperty, ref _selectedIndex, (int val, ref int backing, Action<Action> notifyWrapper) => { var old = backing; var effective = (val >= 0 && val < Items?.Cast<object>().Count()) ? val : -1; if (old != effective) { backing = effective; notifyWrapper(() => RaisePropertyChanged( SelectedIndexProperty, old, effective, BindingPriority.LocalValue)); SelectedItem = ElementAt(Items, effective); } }, value); } else { _updateSelectedIndex = value; _updateSelectedItems = null; } } } /// <summary> /// Gets or sets the selected item. /// </summary> public object SelectedItem { get { return _selectedItem; } set { if (_updateCount == 0) { SetAndRaise(SelectedItemProperty, ref _selectedItem, (object val, ref object backing, Action<Action> notifyWrapper) => { var old = backing; var index = IndexOf(Items, val); var effective = index != -1 ? val : null; if (!object.Equals(effective, old)) { backing = effective; notifyWrapper(() => RaisePropertyChanged( SelectedItemProperty, old, effective, BindingPriority.LocalValue)); SelectedIndex = index; if (effective != null) { if (SelectedItems.Count != 1 || SelectedItems[0] != effective) { _syncingSelectedItems = true; SelectedItems.Clear(); SelectedItems.Add(effective); _syncingSelectedItems = false; } } else if (SelectedItems.Count > 0) { SelectedItems.Clear(); } } }, value); } else { _updateSelectedItems = new AvaloniaList<object>(value); _updateSelectedIndex = int.MinValue; } } } /// <summary> /// Gets the selected items. /// </summary> protected IList SelectedItems { get { if (_selectedItems == null) { _selectedItems = new AvaloniaList<object>(); SubscribeToSelectedItems(); } return _selectedItems; } set { if (value?.IsFixedSize == true || value?.IsReadOnly == true) { throw new NotSupportedException( "Cannot use a fixed size or read-only collection as SelectedItems."); } UnsubscribeFromSelectedItems(); _selectedItems = value ?? new AvaloniaList<object>(); SubscribeToSelectedItems(); } } /// <summary> /// Gets or sets the selection mode. /// </summary> protected SelectionMode SelectionMode { get { return GetValue(SelectionModeProperty); } set { SetValue(SelectionModeProperty, value); } } /// <summary> /// Gets a value indicating whether <see cref="SelectionMode.AlwaysSelected"/> is set. /// </summary> protected bool AlwaysSelected => (SelectionMode & SelectionMode.AlwaysSelected) != 0; /// <inheritdoc/> public override void BeginInit() { base.BeginInit(); ++_updateCount; _updateSelectedIndex = int.MinValue; } /// <inheritdoc/> public override void EndInit() { if (--_updateCount == 0) { UpdateFinished(); } base.EndInit(); } /// <summary> /// Scrolls the specified item into view. /// </summary> /// <param name="item">The item.</param> public void ScrollIntoView(object item) => Presenter?.ScrollIntoView(item); /// <summary> /// Tries to get the container that was the source of an event. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <returns>The container or null if the event did not originate in a container.</returns> protected IControl GetContainerFromEventSource(IInteractive eventSource) { var item = ((IVisual)eventSource).GetSelfAndVisualAncestors() .OfType<IControl>() .FirstOrDefault(x => x.LogicalParent == this && ItemContainerGenerator?.IndexFromContainer(x) != -1); return item; } /// <inheritdoc/> protected override void ItemsChanged(AvaloniaPropertyChangedEventArgs e) { base.ItemsChanged(e); if (_updateCount == 0) { if (SelectedIndex != -1) { SelectedIndex = IndexOf((IEnumerable)e.NewValue, SelectedItem); } else if (AlwaysSelected && Items != null && Items.Cast<object>().Any()) { SelectedIndex = 0; } } } /// <inheritdoc/> protected override void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { base.ItemsCollectionChanged(sender, e); switch (e.Action) { case NotifyCollectionChangedAction.Add: if (AlwaysSelected && SelectedIndex == -1) { SelectedIndex = 0; } break; case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: var selectedIndex = SelectedIndex; if (selectedIndex >= e.OldStartingIndex && selectedIndex < e.OldStartingIndex + e.OldItems.Count) { if (!AlwaysSelected) { selectedIndex = SelectedIndex = -1; } else { LostSelection(); } } var items = Items?.Cast<object>(); if (selectedIndex >= items.Count()) { selectedIndex = SelectedIndex = items.Count() - 1; } break; case NotifyCollectionChangedAction.Reset: SelectedIndex = IndexOf(Items, SelectedItem); break; } } /// <inheritdoc/> protected override void OnContainersMaterialized(ItemContainerEventArgs e) { base.OnContainersMaterialized(e); var selectedIndex = SelectedIndex; var selectedContainer = e.Containers .FirstOrDefault(x => (x.ContainerControl as ISelectable)?.IsSelected == true); if (selectedContainer != null) { SelectedIndex = selectedContainer.Index; } else if (selectedIndex >= e.StartingIndex && selectedIndex < e.StartingIndex + e.Containers.Count) { var container = e.Containers[selectedIndex - e.StartingIndex]; if (container.ContainerControl != null) { MarkContainerSelected(container.ContainerControl, true); } } } /// <inheritdoc/> protected override void OnContainersDematerialized(ItemContainerEventArgs e) { base.OnContainersDematerialized(e); var panel = (InputElement)Presenter.Panel; if (panel != null) { foreach (var container in e.Containers) { if (KeyboardNavigation.GetTabOnceActiveElement(panel) == container.ContainerControl) { KeyboardNavigation.SetTabOnceActiveElement(panel, null); break; } } } } protected override void OnContainersRecycled(ItemContainerEventArgs e) { foreach (var i in e.Containers) { if (i.ContainerControl != null && i.Item != null) { var ms = MemberSelector; bool selected = ms == null ? SelectedItems.Contains(i.Item) : SelectedItems.OfType<object>().Any(v => Equals(ms.Select(v), i.Item)); MarkContainerSelected(i.ContainerControl, selected); } } } /// <inheritdoc/> protected override void OnDataContextBeginUpdate() { base.OnDataContextBeginUpdate(); ++_updateCount; } /// <inheritdoc/> protected override void OnDataContextEndUpdate() { base.OnDataContextEndUpdate(); if (--_updateCount == 0) { UpdateFinished(); } } /// <summary> /// Moves the selection in the specified direction relative to the current selection. /// </summary> /// <param name="direction">The direction to move.</param> /// <param name="wrap">Whether to wrap when the selection reaches the first or last item.</param> /// <returns>True if the selection was moved; otherwise false.</returns> protected bool MoveSelection(NavigationDirection direction, bool wrap) { var from = SelectedIndex != -1 ? ItemContainerGenerator.ContainerFromIndex(SelectedIndex) : null; return MoveSelection(from, direction, wrap); } /// <summary> /// Moves the selection in the specified direction relative to the specified container. /// </summary> /// <param name="from">The container which serves as a starting point for the movement.</param> /// <param name="direction">The direction to move.</param> /// <param name="wrap">Whether to wrap when the selection reaches the first or last item.</param> /// <returns>True if the selection was moved; otherwise false.</returns> protected bool MoveSelection(IControl from, NavigationDirection direction, bool wrap) { if (Presenter?.Panel is INavigableContainer container && GetNextControl(container, direction, from, wrap) is IControl next) { var index = ItemContainerGenerator.IndexFromContainer(next); if (index != -1) { SelectedIndex = index; return true; } } return false; } /// <summary> /// Updates the selection for an item based on user interaction. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="select">Whether the item should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( int index, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { if (index != -1) { if (select) { var mode = SelectionMode; var toggle = toggleModifier || (mode & SelectionMode.Toggle) != 0; var multi = (mode & SelectionMode.Multiple) != 0; var range = multi && SelectedIndex != -1 && rangeModifier; if (!toggle && !range) { SelectedIndex = index; } else if (multi && range) { SynchronizeItems( SelectedItems, GetRange(Items, SelectedIndex, index)); } else { var item = ElementAt(Items, index); var i = SelectedItems.IndexOf(item); if (i != -1 && (!AlwaysSelected || SelectedItems.Count > 1)) { SelectedItems.Remove(item); } else { if (multi) { SelectedItems.Add(item); } else { SelectedIndex = index; } } } if (Presenter?.Panel != null) { var container = ItemContainerGenerator.ContainerFromIndex(index); KeyboardNavigation.SetTabOnceActiveElement( (InputElement)Presenter.Panel, container); } } else { LostSelection(); } } } /// <summary> /// Updates the selection for a container based on user interaction. /// </summary> /// <param name="container">The container.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( IControl container, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { var index = ItemContainerGenerator?.IndexFromContainer(container) ?? -1; if (index != -1) { UpdateSelection(index, select, rangeModifier, toggleModifier); } } /// <summary> /// Updates the selection based on an event that may have originated in a container that /// belongs to the control. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> /// <returns> /// True if the event originated from a container that belongs to the control; otherwise /// false. /// </returns> protected bool UpdateSelectionFromEventSource( IInteractive eventSource, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { var container = GetContainerFromEventSource(eventSource); if (container != null) { UpdateSelection(container, select, rangeModifier, toggleModifier); return true; } return false; } /// <summary> /// Gets a range of items from an IEnumerable. /// </summary> /// <param name="items">The items.</param> /// <param name="first">The index of the first item.</param> /// <param name="last">The index of the last item.</param> /// <returns>The items.</returns> private static IEnumerable<object> GetRange(IEnumerable items, int first, int last) { var list = (items as IList) ?? items.Cast<object>().ToList(); int step = first > last ? -1 : 1; for (int i = first; i != last; i += step) { yield return list[i]; } yield return list[last]; } /// <summary> /// Makes a list of objects equal another. /// </summary> /// <param name="items">The items collection.</param> /// <param name="desired">The desired items.</param> private static void SynchronizeItems(IList items, IEnumerable<object> desired) { int index = 0; foreach (var i in desired) { if (index < items.Count) { if (items[index] != i) { items[index] = i; } } else { items.Add(i); } ++index; } while (index < items.Count) { items.RemoveAt(items.Count - 1); } } /// <summary> /// Called when a container raises the <see cref="IsSelectedChangedEvent"/>. /// </summary> /// <param name="e">The event.</param> private void ContainerSelectionChanged(RoutedEventArgs e) { if (!_ignoreContainerSelectionChanged) { var control = e.Source as IControl; var selectable = e.Source as ISelectable; if (control != null && selectable != null && control.LogicalParent == this && ItemContainerGenerator?.IndexFromContainer(control) != -1) { UpdateSelection(control, selectable.IsSelected); } } if (e.Source != this) { e.Handled = true; } } /// <summary> /// Called when the currently selected item is lost and the selection must be changed /// depending on the <see cref="SelectionMode"/> property. /// </summary> private void LostSelection() { var items = Items?.Cast<object>(); if (items != null && AlwaysSelected) { var index = Math.Min(SelectedIndex, items.Count() - 1); if (index > -1) { SelectedItem = items.ElementAt(index); return; } } SelectedIndex = -1; } /// <summary> /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="container">The container.</param> /// <param name="selected">Whether the control is selected</param> /// <returns>The previous selection state.</returns> private bool MarkContainerSelected(IControl container, bool selected) { try { var selectable = container as ISelectable; bool result; _ignoreContainerSelectionChanged = true; if (selectable != null) { result = selectable.IsSelected; selectable.IsSelected = selected; } else { result = container.Classes.Contains(":selected"); ((IPseudoClasses)container.Classes).Set(":selected", selected); } return result; } finally { _ignoreContainerSelectionChanged = false; } } /// <summary> /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="selected">Whether the item should be selected or deselected.</param> private void MarkItemSelected(int index, bool selected) { var container = ItemContainerGenerator?.ContainerFromIndex(index); if (container != null) { MarkContainerSelected(container, selected); } } /// <summary> /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="item">The item.</param> /// <param name="selected">Whether the item should be selected or deselected.</param> private void MarkItemSelected(object item, bool selected) { var index = IndexOf(Items, item); if (index != -1) { MarkItemSelected(index, selected); } } /// <summary> /// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { var generator = ItemContainerGenerator; IList added = null; IList removed = null; switch (e.Action) { case NotifyCollectionChangedAction.Add: SelectedItemsAdded(e.NewItems.Cast<object>().ToList()); if (AutoScrollToSelectedItem) { ScrollIntoView(e.NewItems[0]); } added = e.NewItems; break; case NotifyCollectionChangedAction.Remove: if (SelectedItems.Count == 0) { if (!_syncingSelectedItems) { SelectedIndex = -1; } } foreach (var item in e.OldItems) { MarkItemSelected(item, false); } removed = e.OldItems; break; case NotifyCollectionChangedAction.Reset: if (generator != null) { removed = new List<object>(); foreach (var item in generator.Containers) { if (item?.ContainerControl != null) { if (MarkContainerSelected(item.ContainerControl, false)) { removed.Add(item.Item); } } } } if (SelectedItems.Count > 0) { _selectedItem = null; SelectedItemsAdded(SelectedItems); added = SelectedItems; } else if (!_syncingSelectedItems) { SelectedIndex = -1; } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems) { MarkItemSelected(item, false); } foreach (var item in e.NewItems) { MarkItemSelected(item, true); } if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems) { var oldItem = SelectedItem; var oldIndex = SelectedIndex; var item = SelectedItems[0]; var index = IndexOf(Items, item); _selectedIndex = index; _selectedItem = item; RaisePropertyChanged(SelectedIndexProperty, oldIndex, index, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, oldItem, item, BindingPriority.LocalValue); } added = e.NewItems; removed = e.OldItems; break; } if (added?.Count > 0 || removed?.Count > 0) { var changed = new SelectionChangedEventArgs( SelectionChangedEvent, added ?? Empty, removed ?? Empty); RaiseEvent(changed); } } /// <summary> /// Called when items are added to the <see cref="SelectedItems"/> collection. /// </summary> /// <param name="items">The added items.</param> private void SelectedItemsAdded(IList items) { if (items.Count > 0) { foreach (var item in items) { MarkItemSelected(item, true); } if (SelectedItem == null && !_syncingSelectedItems) { var index = IndexOf(Items, items[0]); if (index != -1) { _selectedItem = items[0]; _selectedIndex = index; RaisePropertyChanged(SelectedIndexProperty, -1, index, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, null, items[0], BindingPriority.LocalValue); } } } } /// <summary> /// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void SubscribeToSelectedItems() { var incc = _selectedItems as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged += SelectedItemsCollectionChanged; } SelectedItemsCollectionChanged( _selectedItems, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void UnsubscribeFromSelectedItems() { var incc = _selectedItems as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged -= SelectedItemsCollectionChanged; } } private void UpdateFinished() { if (_updateSelectedIndex != int.MinValue) { SelectedIndex = _updateSelectedIndex; } else if (_updateSelectedItems != null) { SelectedItems = _updateSelectedItems; } } } }
using System; using System.Collections.Generic; using System.Text; namespace Hydra.Framework.Mapping.Geometries { // // ********************************************************************** /// <summary> /// A LinearRing is a LineString that is both closed and simple. /// </summary> // ********************************************************************** // public class LinearRing : LineString { #region Constructors // // ********************************************************************** /// <summary> /// Initializes an instance of a LinearRing from a set of vertices /// </summary> /// <param name="vertices">The vertices.</param> // ********************************************************************** // public LinearRing(List<Point> vertices) : base(vertices) { } // // ********************************************************************** /// <summary> /// Initializes an instance of a LinearRing /// </summary> // ********************************************************************** // public LinearRing() : base() { } #endregion #region Properties // // ********************************************************************** /// <summary> /// Returns the area of the LinearRing /// </summary> /// <value>The area.</value> // ********************************************************************** // public double Area { get { if (this.Vertices.Count < 3) return 0; double sum = 0; double ax = this.Vertices[0].X; double ay = this.Vertices[0].Y; for (int i = 1; i < this.Vertices.Count - 1; i++) { double bx = this.Vertices[i].X; double by = this.Vertices[i].Y; double cx = this.Vertices[i + 1].X; double cy = this.Vertices[i + 1].Y; sum += ax * by - ay * bx + ay * cx - ax * cy + bx * cy - cx * by; } return Math.Abs(-sum / 2); } } #endregion #region Public Methods // // ********************************************************************** /// <summary> /// Tests whether a ring is oriented counter-clockwise. /// </summary> /// <returns> /// Returns true if ring is oriented counter-clockwise. /// </returns> // ********************************************************************** // public bool IsCCW() { Point hip; Point p; Point prev; Point next; int hii, i; int nPts = this.Vertices.Count; // // check that this is a valid ring - if not, simply return a dummy value // if (nPts < 4) return false; // // algorithm to check if a Ring is stored in CCW order // find highest point // hip = this.Vertices[0]; hii = 0; for (i = 1; i < nPts; i++) { p = this.Vertices[i]; if (p.Y > hip.Y) { hip = p; hii = i; } } // // find points on either side of highest // int iPrev = hii - 1; if (iPrev < 0) iPrev = nPts - 2; int iNext = hii + 1; if (iNext >= nPts) iNext = 1; prev = this.Vertices[iPrev]; next = this.Vertices[iNext]; // // translate so that hip is at the origin. // This will not affect the area calculation, and will avoid // finite-accuracy errors (i.e very small vectors with very large coordinates) // This also simplifies the discriminant calculation. // double prev2x = prev.X - hip.X; double prev2y = prev.Y - hip.Y; double next2x = next.X - hip.X; double next2y = next.Y - hip.Y; // // compute cross-product of vectors hip->next and hip->prev // (e.g. area of parallelogram they enclose) // double disc = next2x * prev2y - next2y * prev2x; // // If disc is exactly 0, lines are collinear. There are two possible cases: // (1) the lines lie along the x axis in opposite directions // (2) the line lie on top of one another // (2) should never happen, so we're going to ignore it! // (Might want to assert this) // (1) is handled by checking if next is left of prev ==> CCW // if (disc == 0.0) { // // poly is CCW if prev x is right of next x // return (prev.X > next.X); } else { // // if area is positive, points are ordered CCW // return (disc > 0.0); } } // // ********************************************************************** /// <summary> /// Returns true of the Point 'p' is within the instance of this ring /// </summary> /// <param name="p">The p.</param> /// <returns> /// <c>true</c> if [is point within] [the specified p]; otherwise, <c>false</c>. /// </returns> // ********************************************************************** // public bool IsPointWithin(Point p) { bool c = false; for (int i = 0; i < this.Vertices.Count; i++) { for (int j = i + 1; j < this.Vertices.Count - 1; j++) { if ((((this.Vertices[i].Y <= p.Y) && (p.Y < this.Vertices[j].Y)) || ((this.Vertices[j].Y <= p.Y) && (p.Y < this.Vertices[i].Y))) && (p.X < (this.Vertices[j].X - this.Vertices[i].X) * (p.Y - this.Vertices[i].Y) / (this.Vertices[j].Y - this.Vertices[i].Y) + this.Vertices[i].X)) { c = !c; } } } return c; } #endregion #region ICloneable Implementation // // ********************************************************************** /// <summary> /// Return a copy of this geometry /// </summary> /// <returns>Copy of AbstractGeometry</returns> // ********************************************************************** // public new LinearRing Clone() { LinearRing l = new LinearRing(); for (int i = 0; i < this.Vertices.Count; i++) l.Vertices.Add(this.Vertices[i].Clone()); return l; } #endregion } }
using System; using System.Threading.Tasks; using EasyNetQ.Consumer; using EasyNetQ.FluentConfiguration; using EasyNetQ.Producer; using EasyNetQ.Topology; using System.Linq; using EasyNetQ.Internals; namespace EasyNetQ { public class RabbitBus : IBus { private readonly IConventions conventions; private readonly IAdvancedBus advancedBus; private readonly IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy; private readonly IMessageDeliveryModeStrategy messageDeliveryModeStrategy; private readonly IRpc rpc; private readonly ISendReceive sendReceive; private readonly ConnectionConfiguration connectionConfiguration; public RabbitBus( IConventions conventions, IAdvancedBus advancedBus, IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy, IMessageDeliveryModeStrategy messageDeliveryModeStrategy, IRpc rpc, ISendReceive sendReceive, ConnectionConfiguration connectionConfiguration) { Preconditions.CheckNotNull(conventions, "conventions"); Preconditions.CheckNotNull(advancedBus, "advancedBus"); Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "publishExchangeDeclareStrategy"); Preconditions.CheckNotNull(rpc, "rpc"); Preconditions.CheckNotNull(sendReceive, "sendReceive"); Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration"); this.conventions = conventions; this.advancedBus = advancedBus; this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy; this.messageDeliveryModeStrategy = messageDeliveryModeStrategy; this.rpc = rpc; this.sendReceive = sendReceive; this.connectionConfiguration = connectionConfiguration; } public virtual void Publish<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); Publish(message, conventions.TopicNamingConvention(typeof(T))); } public virtual void Publish<T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); Publish(message, c => c.WithTopic(topic)); } public virtual void Publish<T>(T message, Action<IPublishConfiguration> configure) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); var configuration = new PublishConfiguration(conventions.TopicNamingConvention(typeof(T))); configure(configuration); var messageType = typeof(T); var easyNetQMessage = new Message<T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; if (configuration.Priority != null) easyNetQMessage.Properties.Priority = configuration.Priority.Value; if (configuration.Expires != null) easyNetQMessage.Properties.Expiration = configuration.Expires.ToString(); var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, messageType, ExchangeType.Topic); advancedBus.Publish(exchange, configuration.Topic, false, easyNetQMessage); } public virtual Task PublishAsync<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); return PublishAsync(message, conventions.TopicNamingConvention(typeof(T))); } public virtual Task PublishAsync<T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); return PublishAsync(message, c => c.WithTopic(topic)); } public virtual async Task PublishAsync<T>(T message, Action<IPublishConfiguration> configure) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); var configuration = new PublishConfiguration(conventions.TopicNamingConvention(typeof(T))); configure(configuration); var messageType = typeof(T); var easyNetQMessage = new Message<T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; if (configuration.Priority != null) easyNetQMessage.Properties.Priority = configuration.Priority.Value; if (configuration.Expires != null) easyNetQMessage.Properties.Expiration = configuration.Expires.ToString(); var exchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false); await advancedBus.PublishAsync(exchange, configuration.Topic, false, easyNetQMessage).ConfigureAwait(false); } public virtual ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class { return Subscribe(subscriptionId, onMessage, x => { }); } public virtual ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure) where T : class { Preconditions.CheckNotNull(subscriptionId, "subscriptionId"); Preconditions.CheckNotNull(onMessage, "onMessage"); Preconditions.CheckNotNull(configure, "configure"); return SubscribeAsync<T>(subscriptionId, msg => TaskHelpers.ExecuteSynchronously(() => onMessage(msg)), configure); } public virtual ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class { return SubscribeAsync(subscriptionId, onMessage, x => { }); } public virtual ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure) where T : class { Preconditions.CheckNotNull(subscriptionId, "subscriptionId"); Preconditions.CheckNotNull(onMessage, "onMessage"); Preconditions.CheckNotNull(configure, "configure"); var configuration = new SubscriptionConfiguration(connectionConfiguration.PrefetchCount); configure(configuration); var queueName = conventions.QueueNamingConvention(typeof(T), subscriptionId); var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var queue = advancedBus.QueueDeclare(queueName, autoDelete: configuration.AutoDelete, expires: configuration.Expires, maxPriority: configuration.MaxPriority); var exchange = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic); foreach (var topic in configuration.Topics.DefaultIfEmpty("#")) { advancedBus.Bind(exchange, queue, topic); } var consumerCancellation = advancedBus.Consume<T>( queue, (message, messageReceivedInfo) => onMessage(message.Body), x => { x.WithPriority(configuration.Priority) .WithCancelOnHaFailover(configuration.CancelOnHaFailover) .WithPrefetchCount(configuration.PrefetchCount); if (configuration.IsExclusive) { x.AsExclusive(); } }); return new SubscriptionResult(exchange, queue, consumerCancellation); } public virtual TResponse Request<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); var task = RequestAsync<TRequest, TResponse>(request); task.Wait(); return task.Result; } public virtual Task<TResponse> RequestAsync<TResponse>(string endpoint, object request, TimeSpan timeout) where TResponse : class { Preconditions.CheckNotNull(request, "request"); return rpc.Request<TResponse>(endpoint, request, timeout); } public virtual Task<TResponse> RequestAsync<TResponse>(string endpoint, object request, TimeSpan timeout, string topic) where TResponse : class { Preconditions.CheckNotNull(request, "request"); return rpc.Request<TResponse>(endpoint, request, timeout, topic); } public virtual Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); return rpc.Request<TRequest, TResponse>(request); } public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); Func<TRequest, Task<TResponse>> taskResponder = request => Task<TResponse>.Factory.StartNew(_ => responder(request), null); return RespondAsync(taskResponder); } public IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class { Func<TRequest, Task<TResponse>> taskResponder = request => Task<TResponse>.Factory.StartNew(_ => responder(request), null); return RespondAsync(taskResponder, configure); } public IDisposable Respond<TRequest, TResponse>(string endpoint, Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure = null) where TRequest : class where TResponse : class { Func<TRequest, Task<TResponse>> taskResponder = request => Task<TResponse>.Factory.StartNew(_ => responder(request), null); return RespondAsync(endpoint, taskResponder, configure); } public virtual IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder) where TRequest : class where TResponse : class { return RespondAsync(endpoint, responder, c => { }); } public virtual IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class { return rpc.Respond(endpoint, responder, configure); } public virtual IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder, string topic) where TRequest : class where TResponse : class { return rpc.Respond(endpoint, responder, topic, c => { }); } public virtual IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder, string subscriptionId, Action<ISubscriptionConfiguration> configure) where TRequest : class where TResponse : class { return rpc.Respond(endpoint, responder, subscriptionId, configure); } public virtual IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder) where TRequest : class where TResponse : class { return RespondAsync(responder, c => { }); } public IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); Preconditions.CheckNotNull(configure, "configure"); return rpc.Respond(responder, configure); } public virtual void Send<T>(string queue, T message) where T : class { sendReceive.Send(queue, message); } public virtual Task SendAsync<T>(string queue, T message) where T : class { return sendReceive.SendAsync(queue, message); } public virtual IDisposable Receive<T>(string queue, Action<T> onMessage) where T : class { return sendReceive.Receive(queue, onMessage); } public virtual IDisposable Receive<T>(string queue, Action<T> onMessage, Action<IConsumerConfiguration> configure) where T : class { return sendReceive.Receive(queue, onMessage, configure); } public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage) where T : class { return sendReceive.Receive(queue, onMessage); } public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage, Action<IConsumerConfiguration> configure) where T : class { return sendReceive.Receive(queue, onMessage, configure); } public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers) { return sendReceive.Receive(queue, addHandlers); } public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers, Action<IConsumerConfiguration> configure) { return sendReceive.Receive(queue, addHandlers, configure); } public virtual bool IsConnected { get { return advancedBus.IsConnected; } } public virtual IAdvancedBus Advanced { get { return advancedBus; } } public virtual void Dispose() { advancedBus.Dispose(); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using AonWeb.FluentHttp.Handlers; using AonWeb.FluentHttp.Handlers.Caching; namespace AonWeb.FluentHttp { public static class AdvancedHttpBuilderExtensions { public static IAdvancedHttpBuilder WithContentEncoding(this IAdvancedHttpBuilder builder, Encoding encoding) { if (encoding == null) return builder; builder.WithConfiguration(s => s.ContentEncoding = encoding); builder.WithAcceptCharSet(encoding); return builder; } public static IAdvancedHttpBuilder WithHeadersConfiguration(this IAdvancedHttpBuilder builder, Action<HttpRequestHeaders> configuration) { return builder.WithClientConfiguration(c => c.WithHeadersConfiguration(configuration)); } public static IAdvancedHttpBuilder WithHeader(this IAdvancedHttpBuilder builder, string name, string value) { return builder.WithClientConfiguration(c => c.WithHeader(name, value)); } public static IAdvancedHttpBuilder WithHeader(this IAdvancedHttpBuilder builder, string name, IEnumerable<string> values) { return builder.WithClientConfiguration(c => c.WithHeader(name, values)); } public static IAdvancedHttpBuilder WithAppendHeader(this IAdvancedHttpBuilder builder, string name, string value) { return builder.WithClientConfiguration(c => c.WithAppendHeader(name, value)); } public static IAdvancedHttpBuilder WithAppendHeader(this IAdvancedHttpBuilder builder, string name, IEnumerable<string> values) { return builder.WithClientConfiguration(c => c.WithAppendHeader(name, values)); } public static IAdvancedHttpBuilder WithMediaType(this IAdvancedHttpBuilder builder, string mediaType) { if (mediaType == null) return builder; builder.WithConfiguration(s => s.MediaType = mediaType); builder.WithAcceptHeaderValue(mediaType); return builder; } public static IAdvancedHttpBuilder WithAcceptHeaderValue(this IAdvancedHttpBuilder builder, string mediaType) { return builder.WithHeadersConfiguration(h => h.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType))); } public static IAdvancedHttpBuilder WithAcceptCharSet(this IAdvancedHttpBuilder builder, Encoding encoding) { return builder.WithAcceptCharSet(encoding.WebName); } public static IAdvancedHttpBuilder WithAcceptCharSet(this IAdvancedHttpBuilder builder, string charSet) { return builder.WithHeadersConfiguration(h => h.AcceptCharset.Add(new StringWithQualityHeaderValue(charSet))); } public static IAdvancedHttpBuilder WithAutoDecompression(this IAdvancedHttpBuilder builder, bool enabled = true) { builder.WithConfiguration(s => s.AutoDecompression = enabled); return builder.WithDecompressionMethods(enabled ? DecompressionMethods.GZip | DecompressionMethods.Deflate : DecompressionMethods.None); } public static IAdvancedHttpBuilder WithDecompressionMethods(this IAdvancedHttpBuilder builder, DecompressionMethods options) { return builder.WithClientConfiguration(c => c.WithDecompressionMethods(options)); } public static IAdvancedHttpBuilder WithClientCertificateOptions(this IAdvancedHttpBuilder builder, ClientCertificateOption options) { return builder.WithClientConfiguration(c => c.WithClientCertificateOptions(options)); } public static IAdvancedHttpBuilder WithCheckCertificateRevocationList(this IAdvancedHttpBuilder builder, bool check) { return builder.WithClientConfiguration(c => c.WithCheckCertificateRevocationList(check)); } public static IAdvancedHttpBuilder WithClientCertificates(this IAdvancedHttpBuilder builder, IEnumerable<X509Certificate> certificates) { return builder.WithClientConfiguration(c => c.WithClientCertificates(certificates)); } public static IAdvancedHttpBuilder WithClientCertificates(this IAdvancedHttpBuilder builder, X509Certificate certificate) { return builder.WithClientConfiguration(c => c.WithClientCertificates(certificate)); } public static IAdvancedHttpBuilder WithUseCookies(this IAdvancedHttpBuilder builder) { return builder.WithClientConfiguration(c => c.WithUseCookies()); } public static IAdvancedHttpBuilder WithUseCookies(this IAdvancedHttpBuilder builder, CookieContainer container) { return builder.WithClientConfiguration(c => c.WithUseCookies(container)); } public static IAdvancedHttpBuilder WithCredentials(this IAdvancedHttpBuilder builder, ICredentials credentials) { return builder.WithClientConfiguration(c => c.WithCredentials(credentials)); } public static IAdvancedHttpBuilder WithTimeout(this IAdvancedHttpBuilder builder, TimeSpan? timeout) { return builder.WithClientConfiguration(c => c.WithTimeout(timeout)); } public static IAdvancedHttpBuilder WithNoCache(this IAdvancedHttpBuilder builder, bool nocache = true) { return builder.WithClientConfiguration(c => c.WithNoCache(nocache)); } public static IAdvancedHttpBuilder WithCaching(this IAdvancedHttpBuilder builder, bool enabled = true) { return builder.WithOptionalHandlerConfiguration<HttpCacheConfigurationHandler>(c => c.Enabled = enabled); } public static IAdvancedHttpBuilder WithSuppressCancellationExceptions(this IAdvancedHttpBuilder builder, bool suppress = true) { builder.WithConfiguration(s => s.SuppressCancellationErrors = suppress); return builder; } public static IAdvancedHttpBuilder WithRetryConfiguration(this IAdvancedHttpBuilder builder, Action<RetryHandler> configuration) { return builder.WithHandlerConfiguration(configuration); } public static IAdvancedHttpBuilder WithRedirectConfiguration(this IAdvancedHttpBuilder builder, Action<RedirectHandler> configuration) { return builder.WithHandlerConfiguration(configuration); } public static IAdvancedHttpBuilder WithAutoFollowConfiguration(this IAdvancedHttpBuilder builder, Action<FollowLocationHandler> configuration) { return builder.WithHandlerConfiguration(configuration); } public static IAdvancedHttpBuilder WithHandler(this IAdvancedHttpBuilder builder, IHttpHandler httpHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithHandler(httpHandler)); return builder; } public static IAdvancedHttpBuilder WithHandlerConfiguration<THandler>(this IAdvancedHttpBuilder builder, Action<THandler> configure) where THandler : class, IHttpHandler { builder.WithConfiguration(s => s.HandlerRegister.WithConfiguration(configure)); return builder; } public static IAdvancedHttpBuilder WithOptionalHandlerConfiguration<THandler>(this IAdvancedHttpBuilder builder, Action<THandler> configure) where THandler : class, IHttpHandler { builder.WithConfiguration(s => s.HandlerRegister.WithConfiguration(configure, false)); return builder; } public static IAdvancedHttpBuilder WithSuccessfulResponseValidator(this IAdvancedHttpBuilder builder, Func<HttpResponseMessage, bool> validator) { if (validator == null) throw new ArgumentNullException(nameof(validator)); builder.WithConfiguration(s => s.ResponseValidator.Add(new ResponseValidatorFunc(validator))); return builder; } public static IAdvancedHttpBuilder WithExceptionFactory(this IAdvancedHttpBuilder builder, Func<HttpResponseMessage, HttpRequestMessage, Exception> factory) { builder.WithConfiguration(s => s.ExceptionFactory = factory); return builder; } public static IAdvancedHttpBuilder WithContextItem(this IAdvancedHttpBuilder builder, string key, object value) { builder.WithConfiguration(s => s.Items[key] = value); return builder; } public static IAdvancedHttpBuilder OnSending(this IAdvancedHttpBuilder builder, Action<HttpSendingContext> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithSendingHandler(handler)); return builder; } public static IAdvancedHttpBuilder OnSending(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<HttpSendingContext> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithSendingHandler(priority, handler)); return builder; } public static IAdvancedHttpBuilder OnSendingAsync(this IAdvancedHttpBuilder builder, Func<HttpSendingContext, Task> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncSendingHandler(handler)); return builder; } public static IAdvancedHttpBuilder OnSendingAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<HttpSendingContext, Task> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncSendingHandler(priority, handler)); return builder; } public static IAdvancedHttpBuilder OnSent(this IAdvancedHttpBuilder builder, Action<HttpSentContext> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithSentHandler(handler)); return builder; } public static IAdvancedHttpBuilder OnSent(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<HttpSentContext> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithSentHandler(priority, handler)); return builder; } public static IAdvancedHttpBuilder OnSentAsync(this IAdvancedHttpBuilder builder, Func<HttpSentContext, Task> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncSentHandler(handler)); return builder; } public static IAdvancedHttpBuilder OnSentAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<HttpSentContext, Task> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncSentHandler(priority, handler)); return builder; } public static IAdvancedHttpBuilder OnException(this IAdvancedHttpBuilder builder, Action<HttpExceptionContext> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithExceptionHandler(handler)); return builder; } public static IAdvancedHttpBuilder OnException(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<HttpExceptionContext> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithExceptionHandler(priority, handler)); return builder; } public static IAdvancedHttpBuilder OnExceptionAsync(this IAdvancedHttpBuilder builder, Func<HttpExceptionContext, Task> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncExceptionHandler(handler)); return builder; } public static IAdvancedHttpBuilder OnExceptionAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<HttpExceptionContext, Task> handler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncExceptionHandler(priority, handler)); return builder; } #region Caching Events #region Hit public static IAdvancedHttpBuilder OnCacheHit(this IAdvancedHttpBuilder builder, Action<CacheHitContext<HttpResponseMessage>> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithHitHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheHit(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<CacheHitContext<HttpResponseMessage>> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithHitHandler(priority, cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheHitAsync(this IAdvancedHttpBuilder builder, Func<CacheHitContext<HttpResponseMessage>, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncHitHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheHitAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<CacheHitContext<HttpResponseMessage>, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncHitHandler(priority, cacheHandler)); return builder; } #endregion #region Miss public static IAdvancedHttpBuilder OnCacheMiss(this IAdvancedHttpBuilder builder, Action<CacheMissContext<HttpResponseMessage>> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithMissHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheMiss(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<CacheMissContext<HttpResponseMessage>> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithMissHandler(priority, cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheMissAsync(this IAdvancedHttpBuilder builder, Func<CacheMissContext<HttpResponseMessage>, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncMissHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheMissAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<CacheMissContext<HttpResponseMessage>, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncMissHandler(priority, cacheHandler)); return builder; } #endregion #region Store public static IAdvancedHttpBuilder OnCacheStore(this IAdvancedHttpBuilder builder, Action<CacheStoreContext<HttpResponseMessage>> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithStoreHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheStore(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<CacheStoreContext<HttpResponseMessage>> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithStoreHandler(priority, cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheStoreAsync(this IAdvancedHttpBuilder builder, Func<CacheStoreContext<HttpResponseMessage>, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncStoreHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheStoreAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<CacheStoreContext<HttpResponseMessage>, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncStoreHandler(priority, cacheHandler)); return builder; } #endregion #region Expiring public static IAdvancedHttpBuilder OnCacheExpiring(this IAdvancedHttpBuilder builder, Action<CacheExpiringContext> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithExpiringHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheExpiring(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<CacheExpiringContext> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithExpiringHandler(priority, cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheExpiringAsync(this IAdvancedHttpBuilder builder, Func<CacheExpiringContext, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncExpiringHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheExpiringAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<CacheExpiringContext, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncExpiringHandler(priority, cacheHandler)); return builder; } #endregion #region Expired public static IAdvancedHttpBuilder OnCacheExpired(this IAdvancedHttpBuilder builder, Action<CacheExpiredContext> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithExpiredHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheExpired(this IAdvancedHttpBuilder builder, HandlerPriority priority, Action<CacheExpiredContext> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithExpiredHandler(priority, cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheExpiredAsync(this IAdvancedHttpBuilder builder, Func<CacheExpiredContext, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncExpiredHandler(cacheHandler)); return builder; } public static IAdvancedHttpBuilder OnCacheExpiredAsync(this IAdvancedHttpBuilder builder, HandlerPriority priority, Func<CacheExpiredContext, Task> cacheHandler) { builder.WithConfiguration(s => s.HandlerRegister.WithAsyncExpiredHandler(priority, cacheHandler)); return builder; } #endregion #endregion } }
#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.Threading; using Grpc.Core.Internal; namespace Grpc.Core { /// <summary> /// Options for calls made by client. /// </summary> public struct CallOptions { Metadata? headers; DateTime? deadline; CancellationToken cancellationToken; WriteOptions? writeOptions; ContextPropagationToken? propagationToken; CallCredentials? credentials; CallFlags flags; /// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata? headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions? writeOptions = null, ContextPropagationToken? propagationToken = null, CallCredentials? credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; this.flags = default(CallFlags); } /// <summary> /// Headers to send at the beginning of the call. /// </summary> public Metadata? Headers { get { return headers; } } /// <summary> /// Call deadline. /// </summary> public DateTime? Deadline { get { return deadline; } } /// <summary> /// Token that can be used for cancelling the call on the client side. /// Cancelling the token will request cancellation /// of the remote call. Best effort will be made to deliver the cancellation /// notification to the server and interaction of the call with the server side /// will be terminated. Unless the call finishes before the cancellation could /// happen (there is an inherent race), /// the call will finish with <c>StatusCode.Cancelled</c> status. /// </summary> public CancellationToken CancellationToken { get { return cancellationToken; } } /// <summary> /// Write options that will be used for this call. /// </summary> public WriteOptions? WriteOptions { get { return this.writeOptions; } } /// <summary> /// Token for propagating parent call context. /// </summary> public ContextPropagationToken? PropagationToken { get { return this.propagationToken; } } /// <summary> /// Credentials to use for this call. /// </summary> public CallCredentials? Credentials { get { return this.credentials; } } /// <summary> /// If <c>true</c> and channel is in <c>ChannelState.TransientFailure</c>, the call will attempt waiting for the channel to recover /// instead of failing immediately (which is the default "FailFast" semantics). /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public bool IsWaitForReady { get { return (this.flags & CallFlags.WaitForReady) == CallFlags.WaitForReady; } } /// <summary> /// Flags to use for this call. /// </summary> internal CallFlags Flags { get { return this.flags; } } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Headers</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="headers">The headers.</param> public CallOptions WithHeaders(Metadata headers) { var newOptions = this; newOptions.headers = headers; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Deadline</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="deadline">The deadline.</param> public CallOptions WithDeadline(DateTime deadline) { var newOptions = this; newOptions.deadline = deadline; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>CancellationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> public CallOptions WithCancellationToken(CancellationToken cancellationToken) { var newOptions = this; newOptions.cancellationToken = cancellationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>WriteOptions</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="writeOptions">The write options.</param> public CallOptions WithWriteOptions(WriteOptions writeOptions) { var newOptions = this; newOptions.writeOptions = writeOptions; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>PropagationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="propagationToken">The context propagation token.</param> public CallOptions WithPropagationToken(ContextPropagationToken propagationToken) { var newOptions = this; newOptions.propagationToken = propagationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Credentials</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="credentials">The call credentials.</param> public CallOptions WithCredentials(CallCredentials credentials) { var newOptions = this; newOptions.credentials = credentials; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with "WaitForReady" semantics enabled/disabled. /// <see cref="IsWaitForReady"/>. /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public CallOptions WithWaitForReady(bool waitForReady = true) { if (waitForReady) { return WithFlags(this.flags | CallFlags.WaitForReady); } return WithFlags(this.flags & ~CallFlags.WaitForReady); } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Flags</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="flags">The call flags.</param> internal CallOptions WithFlags(CallFlags flags) { var newOptions = this; newOptions.flags = flags; return newOptions; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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.Net; using System.Threading; using log4net; using OpenSim.Framework; using OpenMetaverse; using OpenMetaverse.Packets; using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket; namespace OpenSim.Region.ClientStack.LindenUDP { #region Delegates /// <summary> /// Fired when updated networking stats are produced for this client /// </summary> /// <param name="inPackets">Number of incoming packets received since this /// event was last fired</param> /// <param name="outPackets">Number of outgoing packets sent since this /// event was last fired</param> /// <param name="unAckedBytes">Current total number of bytes in packets we /// are waiting on ACKs for</param> public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes); /// <summary> /// Fired when the queue for one or more packet categories is empty. This /// event can be hooked to put more data on the empty queues /// </summary> /// <param name="category">Categories of the packet queues that are empty</param> public delegate void QueueEmpty(ThrottleOutPacketTypeFlags categories); #endregion Delegates /// <summary> /// Tracks state for a client UDP connection and provides client-specific methods /// </summary> public sealed class LLUDPClient { // TODO: Make this a config setting /// <summary>Percentage of the task throttle category that is allocated to avatar and prim /// state updates</summary> const float STATE_TASK_PERCENTAGE = 0.8f; /// <summary> /// 4 MB maximum outbound queue per avatar after this amount is reached non-reliable packets will /// be dropped /// </summary> const int MAX_TOTAL_QUEUE_SIZE = 4 * 1024 * 1024; private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary>The number of packet categories to throttle on. If a throttle category is added /// or removed, this number must also change</summary> public const int THROTTLE_CATEGORY_COUNT = 8; /// <summary>Fired when updated networking stats are produced for this client</summary> public event PacketStats OnPacketStats; /// <summary>Fired when the queue for a packet category is empty. This event can be /// hooked to put more data on the empty queue</summary> public event QueueEmpty OnQueueEmpty; /// <summary>AgentID for this client</summary> public readonly UUID AgentID; /// <summary>The remote address of the connected client</summary> public readonly IPEndPoint RemoteEndPoint; /// <summary>Circuit code that this client is connected on</summary> public readonly uint CircuitCode; /// <summary>Sequence numbers of packets we've received (for duplicate checking)</summary> public readonly IncomingPacketHistoryCollection PacketArchive = new IncomingPacketHistoryCollection(384); /// <summary>Packets we have sent that need to be ACKed by the client</summary> public readonly UnackedPacketCollection NeedAcks; /// <summary>ACKs that are queued up, waiting to be sent to the client</summary> public readonly OpenSim.Framework.LocklessQueue<uint> PendingAcks = new OpenSim.Framework.LocklessQueue<uint>(); /// <summary>Current packet sequence number</summary> public int CurrentSequence; /// <summary>Current ping sequence number</summary> public byte CurrentPingSequence; /// <summary>True when this connection is alive, otherwise false</summary> public bool IsConnected = true; /// <summary>True when this connection is paused, otherwise false</summary> public bool IsPaused; /// <summary>Environment.TickCount when the last packet was received for this client</summary> public int TickLastPacketReceived; /// <summary>Smoothed round-trip time. A smoothed average of the round-trip time for sending a /// reliable packet to the client and receiving an ACK</summary> public float SRTT; /// <summary>Round-trip time variance. Measures the consistency of round-trip times</summary> public float RTTVAR; /// <summary>Retransmission timeout. Packets that have not been acknowledged in this number of /// milliseconds or longer will be resent</summary> /// <remarks>Calculated from <seealso cref="SRTT"/> and <seealso cref="RTTVAR"/> using the /// guidelines in RFC 2988</remarks> public int RTO; /// <summary>Number of bytes received since the last acknowledgement was sent out. This is used /// to loosely follow the TCP delayed ACK algorithm in RFC 1122 (4.2.3.2)</summary> public int BytesSinceLastACK; /// <summary>Number of packets received from this client</summary> public int PacketsReceived; /// <summary>Number of packets sent to this client</summary> public int PacketsSent; /// <summary>Total byte count of unacked packets sent to this client</summary> public int UnackedBytes; /// <summary>Total number of received packets that we have reported to the OnPacketStats event(s)</summary> private int m_packetsReceivedReported; /// <summary>Total number of sent packets that we have reported to the OnPacketStats event(s)</summary> private int m_packetsSentReported; /// <summary>Holds the Environment.TickCount value of when the next OnQueueEmpty can be fired</summary> private int m_nextOnQueueEmpty = 1; /// <summary>Throttle bucket for this agent's connection</summary> private readonly TokenBucket m_throttle; /// <summary>Throttle buckets for each packet category</summary> private readonly TokenBucket[] m_throttleCategories; /// <summary>Outgoing queues for throttled packets</summary> private readonly OpenSim.Framework.LocklessQueue<OutgoingPacket>[] m_packetOutboxes = new OpenSim.Framework.LocklessQueue<OutgoingPacket>[THROTTLE_CATEGORY_COUNT]; /// <summary>A container that can hold one packet for each outbox, used to store /// dequeued packets that are being held for throttling</summary> private readonly OutgoingPacket[] m_nextPackets = new OutgoingPacket[THROTTLE_CATEGORY_COUNT]; /// <summary>A reference to the LLUDPServer that is managing this client</summary> private readonly LLUDPServer m_udpServer; /// <summary>Caches packed throttle information</summary> private UnpackedThrottles m_unpackedThrottles; private int m_defaultRTO = 3000; private int m_maxRTO = 60000; /// <summary> /// The current size of all packets on the outbound queue /// </summary> private int _currentOutboundQueueSize = 0; /// <summary> /// Records the last time an adjustment was made to the packet throttles /// </summary> private DateTime _lastDynamicThrottleAdjustment = DateTime.Now; /// <summary> /// The minmum amount of time to wait to report repeated dropped packets in seconds /// </summary> const int MIN_DROP_REPORT_INTERVAL = 60; /// <summary> /// The last time a packet drop was reported to the console /// </summary> private DateTime _lastDropReport = DateTime.Now; private object _dropReportLock = new object(); /// <summary> /// Random number generator to select random streams to start sending data on /// during the dequeue phase /// </summary> private Random _rand = new Random(); /// <summary> /// keeps tract of what buckets were empty on the last dequeue to inform /// the throttle adjustment code /// </summary> private List<int> _emptyBucketHints = new List<int>(); /// <summary> /// The current size of our queue /// </summary> public int OutboundQueueSize { get { return _currentOutboundQueueSize; } } /// <summary> /// Default constructor /// </summary> /// <param name="server">Reference to the UDP server this client is connected to</param> /// <param name="rates">Default throttling rates and maximum throttle limits</param> /// <param name="parentThrottle">Parent HTB (hierarchical token bucket) /// that the child throttles will be governed by</param> /// <param name="circuitCode">Circuit code for this connection</param> /// <param name="agentID">AgentID for the connected agent</param> /// <param name="remoteEndPoint">Remote endpoint for this connection</param> public LLUDPClient(LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO) { AgentID = agentID; RemoteEndPoint = remoteEndPoint; CircuitCode = circuitCode; m_udpServer = server; if (defaultRTO != 0) m_defaultRTO = defaultRTO; if (maxRTO != 0) m_maxRTO = maxRTO; // Create a token bucket throttle for this client that has the scene token bucket as a parent m_throttle = new TokenBucket(parentThrottle, rates.TotalLimit, rates.Total); // Create an array of token buckets for this clients different throttle categories m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT]; for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { ThrottleOutPacketType type = (ThrottleOutPacketType)i; // Initialize the packet outboxes, where packets sit while they are waiting for tokens m_packetOutboxes[i] = new OpenSim.Framework.LocklessQueue<OutgoingPacket>(); // Initialize the token buckets that control the throttling for each category m_throttleCategories[i] = new TokenBucket(m_throttle, rates.GetLimit(type), rates.GetRate(type)); } // Default the retransmission timeout to three seconds RTO = m_defaultRTO; // Initialize this to a sane value to prevent early disconnects TickLastPacketReceived = Environment.TickCount & Int32.MaxValue; NeedAcks = new UnackedPacketCollection(server.ByteBufferPool); } /// <summary> /// Shuts down this client connection /// </summary> public void Shutdown() { IsConnected = false; for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { m_packetOutboxes[i].Clear(); m_nextPackets[i] = null; } OnPacketStats = null; OnQueueEmpty = null; } /// <summary> /// Modifies the UDP throttles /// </summary> /// <param name="info">New throttling values</param> public void SetClientInfo(ClientInfo info) { // TODO: Allowing throttles to be manually set from this function seems like a reasonable // idea. On the other hand, letting external code manipulate our ACK accounting is not // going to happen throw new NotImplementedException(); } public string GetStats() { // TODO: ??? return string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } public void SendPacketStats() { PacketStats callback = OnPacketStats; if (callback != null) { int newPacketsReceived = PacketsReceived - m_packetsReceivedReported; int newPacketsSent = PacketsSent - m_packetsSentReported; callback(newPacketsReceived, newPacketsSent, UnackedBytes); m_packetsReceivedReported += newPacketsReceived; m_packetsSentReported += newPacketsSent; } } public bool SetThrottles(byte[] throttleData) { byte[] adjData; int pos = 0; if (!BitConverter.IsLittleEndian) { byte[] newData = new byte[7 * 4]; Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4); for (int i = 0; i < 7; i++) Array.Reverse(newData, i * 4, 4); adjData = newData; } else { adjData = throttleData; } // 0.125f converts from bits to bytes int resend = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int land = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int wind = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int cloud = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int task = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); int totalKbps = ((resend + land + wind + cloud + task + texture + asset)/1024)*8; // save this original value for below // State is a subcategory of task that we allocate a percentage to int state = (int)((float)task * STATE_TASK_PERCENTAGE); task -= state; //subtract 33% from the total to make up for LL's 50% hack resend = (int)(resend * 0.6667); land = (int)(land * 0.6667); wind = (int)(wind * 0.6667); cloud = (int)(cloud * 0.6667); task = (int)(task * 0.6667); texture = (int)(texture * 0.6667); asset = (int)(asset * 0.6667); state = (int)(state * 0.6667); // Make sure none of the throttles are set below our packet MTU, // otherwise a throttle could become permanently clogged resend = Math.Max(resend, LLUDPServer.MTU); land = Math.Max(land, LLUDPServer.MTU); wind = Math.Max(wind, LLUDPServer.MTU); cloud = Math.Max(cloud, LLUDPServer.MTU); task = Math.Max(task, LLUDPServer.MTU); texture = Math.Max(texture, LLUDPServer.MTU); asset = Math.Max(asset, LLUDPServer.MTU); state = Math.Max(state, LLUDPServer.MTU); int total = resend + land + wind + cloud + task + texture + asset + state; //m_log.InfoFormat("[LLUDP] Client {0} throttle {1}", AgentID, total); //m_log.DebugFormat("[LLUDPCLIENT]: {0} is setting throttles. Resend={1}, Land={2}, Wind={3}, Cloud={4}, Task={5}, Texture={6}, Asset={7}, State={8}, Total={9}", // AgentID, resend, land, wind, cloud, task, texture, asset, state, total); // Update the token buckets with new throttle values TokenBucket bucket; bool throttleChanged = (m_throttle.DripRate != m_throttle.NormalizedDripRate(total)); // if (throttleChanged) m_log.InfoFormat("[LLUDPCLIENT]: Viewer agent bandwidth throttle request for {0} to {1} kbps.", this.AgentID, totalKbps); bucket = m_throttle; bucket.DripRate = total; bucket.MaxBurst = total; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend]; bucket.DripRate = resend; bucket.MaxBurst = resend; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land]; bucket.DripRate = land; bucket.MaxBurst = land; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind]; bucket.DripRate = wind; bucket.MaxBurst = wind; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud]; bucket.DripRate = cloud; bucket.MaxBurst = cloud; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset]; bucket.DripRate = asset; bucket.MaxBurst = asset; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task]; bucket.DripRate = task + state; bucket.MaxBurst = task + state; bucket = m_throttleCategories[(int)ThrottleOutPacketType.State]; bucket.DripRate = state; bucket.MaxBurst = state; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture]; bucket.DripRate = texture; bucket.MaxBurst = texture; // Reset the packed throttles cached data m_unpackedThrottles = null; return throttleChanged; } internal UnpackedThrottles GetThrottlesUnpacked() { UnpackedThrottles throttles = m_unpackedThrottles; if (throttles == null) { float[] fthrottles = new float[THROTTLE_CATEGORY_COUNT - 1]; int i = 0; fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate; fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate; fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate; fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate; fthrottles[i++] = (float)(m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate + m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate); fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate; fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate; throttles = new UnpackedThrottles(fthrottles); m_unpackedThrottles = throttles; } return throttles; } public void TestReportPacketDrop(OutgoingPacket packet) { lock (_dropReportLock) { if (DateTime.Now - _lastDropReport > TimeSpan.FromSeconds(MIN_DROP_REPORT_INTERVAL)) { _lastDropReport = DateTime.Now; m_log.WarnFormat("[LLUDP] Packets are being dropped for {0} due to overfilled outbound queue, last packet type {1}", AgentID, packet.Type); } } } public void TestReportPacketShouldDrop(OutgoingPacket packet) { lock (_dropReportLock) { if (DateTime.Now - _lastDropReport > TimeSpan.FromSeconds(MIN_DROP_REPORT_INTERVAL)) { _lastDropReport = DateTime.Now; m_log.WarnFormat("[LLUDP] Packet should've been dropped for {0} due to overfilled outbound queue, but was reliable. Last packet type {1}", AgentID, packet.Type); } } } public void TestReportCriticalPacketDrop(OutgoingPacket packet) { lock (_dropReportLock) { if (DateTime.Now - _lastDropReport > TimeSpan.FromSeconds(MIN_DROP_REPORT_INTERVAL)) { _lastDropReport = DateTime.Now; m_log.WarnFormat("[LLUDP] Reliable packets are being dropped for {0} due to overfilled outbound queue. Last packet type {1}", AgentID, packet.Type); } } } public bool EnqueueOutgoing(OutgoingPacket packet) { int category = (int)packet.Category; if (category >= 0 && category < m_packetOutboxes.Length) { OpenSim.Framework.LocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category]; TokenBucket bucket = m_throttleCategories[category]; // Not enough tokens in the bucket, queue this packet //check the queue //Dont drop resends this can mess up the buffer pool as well as make the connection situation much worse if (_currentOutboundQueueSize > MAX_TOTAL_QUEUE_SIZE && (packet.Buffer[0] & Helpers.MSG_RESENT) == 0) { //queue already has too much data in it.. //can we drop this packet? byte flags = packet.Buffer[0]; bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0; if (!isReliable && packet.Type != PacketType.PacketAck && packet.Type != PacketType.CompletePingCheck) { //packet is unreliable and will be dropped this.TestReportPacketDrop(packet); packet.DecRef(m_udpServer.ByteBufferPool); } else { if (_currentOutboundQueueSize < MAX_TOTAL_QUEUE_SIZE * 1.5) { this.TestReportPacketShouldDrop(packet); Interlocked.Add(ref _currentOutboundQueueSize, packet.DataSize); packet.AddRef(); queue.Enqueue(packet); } else { //this connection is in a pretty critical state and probably will never catch up. //drop all packets until we start to catch up. This includes acks which will disconnect //the client eventually anyways this.TestReportCriticalPacketDrop(packet); packet.DecRef(m_udpServer.ByteBufferPool); } } } else { Interlocked.Add(ref _currentOutboundQueueSize, packet.DataSize); packet.AddRef(); queue.Enqueue(packet); } return true; } else { // We don't have a token bucket for this category, so it will not be queued return false; } } /// <summary> /// Loops through all of the packet queues for this client and tries to send /// any outgoing packets, obeying the throttling bucket limits /// </summary> /// <remarks>This function is only called from a synchronous loop in the /// UDPServer so we don't need to bother making this thread safe</remarks> /// <returns>True if any packets were sent, otherwise false</returns> public bool DequeueOutgoing() { OutgoingPacket packet; OpenSim.Framework.LocklessQueue<OutgoingPacket> queue; TokenBucket bucket; bool packetSent = false; ThrottleOutPacketTypeFlags emptyCategories = 0; //string queueDebugOutput = String.Empty; // Serious debug business int randStart = _rand.Next(7); for (int j = 0; j < THROTTLE_CATEGORY_COUNT; j++) { int i = (j + randStart) % THROTTLE_CATEGORY_COUNT; bucket = m_throttleCategories[i]; //queueDebugOutput += m_packetOutboxes[i].Count + " "; // Serious debug business if (m_nextPackets[i] != null) { // This bucket was empty the last time we tried to send a packet, // leaving a dequeued packet still waiting to be sent out. Try to // send it again OutgoingPacket nextPacket = m_nextPackets[i]; if (bucket.RemoveTokens(nextPacket.DataSize)) { // Send the packet Interlocked.Add(ref _currentOutboundQueueSize, -nextPacket.DataSize); m_udpServer.SendPacketFinal(nextPacket); nextPacket.DecRef(m_udpServer.ByteBufferPool); m_nextPackets[i] = null; packetSent = true; this.PacketsSent++; } } else { // No dequeued packet waiting to be sent, try to pull one off // this queue queue = m_packetOutboxes[i]; if (queue.Dequeue(out packet)) { // A packet was pulled off the queue. See if we have // enough tokens in the bucket to send it out if (bucket.RemoveTokens(packet.DataSize)) { // Send the packet Interlocked.Add(ref _currentOutboundQueueSize, -packet.DataSize); m_udpServer.SendPacketFinal(packet); packet.DecRef(m_udpServer.ByteBufferPool); packetSent = true; this.PacketsSent++; } else { // Save the dequeued packet for the next iteration m_nextPackets[i] = packet; _emptyBucketHints.Add(i); } // If the queue is empty after this dequeue, fire the queue // empty callback now so it has a chance to fill before we // get back here if (queue.Count == 0) emptyCategories |= CategoryToFlag(i); } else { // No packets in this queue. Fire the queue empty callback // if it has not been called recently emptyCategories |= CategoryToFlag(i); } } } if (emptyCategories != 0) BeginFireQueueEmpty(emptyCategories); //m_log.Info("[LLUDPCLIENT]: Queues: " + queueDebugOutput); // Serious debug business return packetSent; } /// <summary> /// Called when an ACK packet is received and a round-trip time for a /// packet is calculated. This is used to calculate the smoothed /// round-trip time, round trip time variance, and finally the /// retransmission timeout /// </summary> /// <param name="r">Round-trip time of a single packet and its /// acknowledgement</param> public void UpdateRoundTrip(float r) { const float ALPHA = 0.125f; const float BETA = 0.25f; const float K = 4.0f; if (RTTVAR == 0.0f) { // First RTT measurement SRTT = r; RTTVAR = r * 0.5f; } else { // Subsequence RTT measurement RTTVAR = (1.0f - BETA) * RTTVAR + BETA * Math.Abs(SRTT - r); SRTT = (1.0f - ALPHA) * SRTT + ALPHA * r; } int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR)); // Clamp the retransmission timeout to manageable values rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO); RTO = rto; //m_log.Debug("[LLUDPCLIENT]: Setting agent " + this.Agent.FullName + "'s RTO to " + RTO + "ms with an RTTVAR of " + // RTTVAR + " based on new RTT of " + r + "ms"); } /// <summary> /// Exponential backoff of the retransmission timeout, per section 5.5 /// of RFC 2988 /// </summary> public void BackoffRTO() { // Reset SRTT and RTTVAR, we assume they are bogus since things // didn't work out and we're backing off the timeout SRTT = 0.0f; RTTVAR = 0.0f; // Double the retransmission timeout RTO = Math.Min(RTO * 2, m_maxRTO); } /// <summary> /// Does an early check to see if this queue empty callback is already /// running, then asynchronously firing the event /// </summary> /// <param name="throttleIndex">Throttle category to fire the callback /// for</param> private void BeginFireQueueEmpty(ThrottleOutPacketTypeFlags categories) { if (m_nextOnQueueEmpty != 0 && (Environment.TickCount & Int32.MaxValue) >= m_nextOnQueueEmpty) { // Use a value of 0 to signal that FireQueueEmpty is running m_nextOnQueueEmpty = 0; // Asynchronously run the callback Util.FireAndForget(FireQueueEmpty, categories); } } /// <summary> /// Fires the OnQueueEmpty callback and sets the minimum time that it /// can be called again /// </summary> /// <param name="o">Throttle categories to fire the callback for, /// stored as an object to match the WaitCallback delegate /// signature</param> private void FireQueueEmpty(object o) { const int MIN_CALLBACK_MS = 30; ThrottleOutPacketTypeFlags categories = (ThrottleOutPacketTypeFlags)o; QueueEmpty callback = OnQueueEmpty; int start = Environment.TickCount & Int32.MaxValue; if (callback != null) { try { callback(categories); } catch (Exception e) { m_log.Error("[LLUDPCLIENT]: OnQueueEmpty(" + categories + ") threw an exception: " + e.Message, e); } } m_nextOnQueueEmpty = start + MIN_CALLBACK_MS; if (m_nextOnQueueEmpty == 0) m_nextOnQueueEmpty = 1; } /// <summary> /// Converts a <seealso cref="ThrottleOutPacketType"/> integer to a /// flag value /// </summary> /// <param name="i">Throttle category to convert</param> /// <returns>Flag representation of the throttle category</returns> private static ThrottleOutPacketTypeFlags CategoryToFlag(int i) { ThrottleOutPacketType category = (ThrottleOutPacketType)i; /* * Land = 1, /// <summary>Wind data</summary> Wind = 2, /// <summary>Cloud data</summary> Cloud = 3, /// <summary>Any packets that do not fit into the other throttles</summary> Task = 4, /// <summary>Texture assets</summary> Texture = 5, /// <summary>Non-texture assets</summary> Asset = 6, /// <summary>Avatar and primitive data</summary> /// <remarks>This is a sub-category of Task</remarks> State = 7, */ switch (category) { case ThrottleOutPacketType.Land: return ThrottleOutPacketTypeFlags.Land; case ThrottleOutPacketType.Wind: return ThrottleOutPacketTypeFlags.Wind; case ThrottleOutPacketType.Cloud: return ThrottleOutPacketTypeFlags.Cloud; case ThrottleOutPacketType.Task: return ThrottleOutPacketTypeFlags.Task; case ThrottleOutPacketType.Texture: return ThrottleOutPacketTypeFlags.Texture; case ThrottleOutPacketType.Asset: return ThrottleOutPacketTypeFlags.Asset; case ThrottleOutPacketType.State: return ThrottleOutPacketTypeFlags.State; default: return 0; } } /// <summary> /// if we have any leftover bandwidth, check for queues that have packets still in them /// and equally distribute remaining bandwidth among queues /// </summary> /// <returns>True if a dynamic adjustment was made, false if not</returns> public bool PerformDynamicThrottleAdjustment() { //return false; if (m_throttle.Content == 0 || _emptyBucketHints.Count == 0) { _emptyBucketHints.Clear(); return false; } int addnlAmount = m_throttle.Content / _emptyBucketHints.Count; foreach (int i in _emptyBucketHints) { m_throttleCategories[i].SpareBurst = addnlAmount; } _emptyBucketHints.Clear(); return true; } } }
// // 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.Providers { using System; using PackageManagement.Internal.Api; using PackageManagement.Internal.Utility.Plugin; public interface IPackageProvider : IProvider { /// <summary> /// Returns the name of the Provider. /// </summary> /// <remarks> /// May be implemented as a property: <code>string PackageProviderName { get; } </code> /// </remarks> /// <returns>the name of the package provider</returns> /// <remarks> /// PowerShellMetaProvider notes: /// - may use Get-PackageProviderName as the function name /// </remarks> [Required] string GetPackageProviderName(); /// <summary> /// This is called when the user is adding (or updating) a package source /// If this PROVIDER doesn't support user-defined package sources, remove this method. /// </summary> /// <param name="name"> /// The name of the package source. If this parameter is null or empty the PROVIDER should use the /// location as the name (if the PROVIDER actually stores names of package sources) /// </param> /// <param name="location"> /// The location (ie, directory, URL, etc) of the package source. If this is null or empty, the /// PROVIDER should use the name as the location (if valid) /// </param> /// <param name="trusted"> /// A boolean indicating that the user trusts this package source. Packages returned from this source /// should be marked as 'trusted' /// </param> /// <param name="requestObject"> /// An object passed in from the CORE that contains functions that can be used to interact with /// the CORE and HOST /// </param> /// <remarks> /// Make 'trusted' a dynamic parameter. /// PowerShellMetaProvider notes: /// - may use 'Add-PackageSource' as the function name. /// - $request object is not passed as a parameter, but inserted as a variable before the call. /// - Values can be returned using Write-Object for objects returned from the New-PackageSource function /// </remarks> #if NEW_SIGNATURES void AddPackageSource(string name, string location, IRequest requestObject); #endif #if !REMOVE_DEPRECATED_FUNCTIONS void AddPackageSource(string name, string location, bool trusted, IRequest requestObject); #endif /// <summary> /// Resolves and returns package sources. /// /// Expected behavior: /// If request.Sources is null or empty, the provider should return the list of registered sources. /// Otherwise, the provider should return package sources that match the strings in the request.Sources /// collection. If the string doesn't match a registered source (either by name or by location) and the /// string can be construed as a package source (ie, passing in a valid URL to a provider that uses URLs /// for their package sources), then the provider should return a package source for that URL, but marked /// as 'unregistered' (and 'untrusted') /// </summary> /// <returns> /// Data is returned using the request.YieldPackageSource(...) function. /// </returns> /// <param name="requestObject">The request context passed to the provider.</param> /// <remarks> /// PowerShellMetaProvider notes: /// - may use Resolve-PackageSource as the function name /// - $request object is not passed as a parameter, but inserted as a variable before the New-PackageSource call. /// - Values can be returned using Write-Object for objects returned from the function /// </remarks> void ResolvePackageSources(IRequest requestObject); /// <summary> /// Removes a registered package source. /// /// Matching of the package source should be done on via the name or location against the specified string. /// </summary> /// <param name="source"> the name or location of the source to be removed.</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <remarks> /// PowerShellMetaProvider notes: /// - may use 'Remove-PackageSource' as the function name. /// - request object is not passed as a parameter, but inserted as a variable before the call. /// </remarks> void RemovePackageSource(string source, IRequest requestObject); /// <summary> /// Finds packages given a set of criteria. /// /// If request.Sources is null or empty, the provider should use all the registered sources specified. /// /// If the provider doesn't support package sources, and the request.Sources isn't null or empty, /// the provider should return nothing and exit immediately. /// /// If request.Sources contains one or more elements, the repository should scope the search to just repositories /// that match sources (either by name or location) in the list of specified strings. /// </summary> /// <param name="name">matches against the name of a package. If this is null or empty, should return all matching packages.</param> /// <param name="requiredVersion">an exact version of the package to match. If this is specified, minimum and maximum should be ignored.</param> /// <param name="minimumVersion">the minimum version of the package to match. If requiredVersion is specified, this should be ignored.</param> /// <param name="maximumVersion">the maximum version of the package to match. If requiredVersion is specified, this should be ignored.</param> /// <param name="id">the batch id. If the provider supports batch searches, and this is non-zero, /// the provider should queue up the search to be executed when CompleteFind is called</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <returns> /// Returns Software Identities thru the use of request.YieldSoftwareIdentity(), and extended data via: /// AddMetadata(...) -- adds key/value pairs to an element /// AddMeta(...) -- adds a new Meta element child to an element /// AddEntity(...) -- adds a new Entity to an element /// AddLink(...) -- adds a new Link to a SoftwareIdentity /// AddDependency(...) -- adds a new 'requires' Link to a SoftwareIdentity /// AddPayload(...) -- adds a Payload (or returns the existing one) to a SoftwareIdentity /// AddEvidence(...) -- adds an Evidence (or returns the existing one) to a SoftwareIdentity /// AddDirectory(...) -- adds a Directory to a Payload, Evidence or Directory /// AddFile(...) -- adds a File to a Payload, Evidence or Directory /// AddProcess(...) -- adds a Process to a Payload or Evidence /// AddResource(...) -- adds a Resource to a Payload or Evidence /// </returns> /// <remarks> /// PowerShellMetaProvider notes: /// - may use 'Find-Package' as the function name. /// - If the provider supports batch operations, the name should be a string array /// - Values can be returned using Write-Object for objects returned from the New-SoftwareIdentity function /// </remarks> #if NEW_SIGNATURES void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, IRequest requestObject); void FindPackage(string[] names, string requiredVersion, string minimumVersion, string maximumVersion, IRequest requestObject); #endif #if !REMOVE_DEPRECATED_FUNCTIONS void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion,int id, IRequest requestObject); #endif /// <summary> /// Returns SoftwareIdentities given a local filename. /// </summary> /// <param name="filePath">the full path to the file to evaluate as a package</param> /// <param name="id">the batch id. If the provider supports batch searches, and this is non-zero, /// the provider should queue up the search to be executed when CompleteFind is called</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <returns> /// Returns Software Identities thru the use of request.YieldSoftwareIdentity(), and extended data via: /// AddMetadata(...) -- adds key/value pairs to an element /// AddMeta(...) -- adds a new Meta element child to an element /// AddEntity(...) -- adds a new Entity to an element /// AddLink(...) -- adds a new Link to a SoftwareIdentity /// AddDependency(...) -- adds a new 'requires' Link to a SoftwareIdentity /// AddPayload(...) -- adds a Payload (or returns the existing one) to a SoftwareIdentity /// AddEvidence(...) -- adds an Evidence (or returns the existing one) to a SoftwareIdentity /// AddDirectory(...) -- adds a Directory to a Payload, Evidence or Directory /// AddFile(...) -- adds a File to a Payload, Evidence or Directory /// AddProcess(...) -- adds a Process to a Payload or Evidence /// AddResource(...) -- adds a Resource to a Payload or Evidence /// </returns> /// <remarks> /// PowerShellMetaProvider notes: /// - may use 'Find-PackageByFile' as the function name. /// - If the provider supports batch operations, the file parameter should be a string array /// - Values can be returned using Write-Object for objects returned from the New-SoftwareIdentity function /// </remarks> #if NEW_SIGNATURES void FindPackageByFile(string filePath, IRequest requestObject); void FindPackageByFile(string[] filePaths, IRequest requestObject); #endif #if !REMOVE_DEPRECATED_FUNCTIONS void FindPackageByFile(string filePath, int id, IRequest requestObject); #endif /// <summary> /// Returns SoftwareIdentities given a URI. /// </summary> /// <param name="uri">the URI to search for packages</param> /// <param name="id">the batch id. If the provider supports batch searches, and this is non-zero, /// the provider should queue up the search to be executed when CompleteFind is called</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <returns> /// Returns Software Identities thru the use of request.YieldSoftwareIdentity(), and extended data via: /// AddMetadata(...) -- adds key/value pairs to an element /// AddMeta(...) -- adds a new Meta element child to an element /// AddEntity(...) -- adds a new Entity to an element /// AddLink(...) -- adds a new Link to a SoftwareIdentity /// AddDependency(...) -- adds a new 'requires' Link to a SoftwareIdentity /// AddPayload(...) -- adds a Payload (or returns the existing one) to a SoftwareIdentity /// AddEvidence(...) -- adds an Evidence (or returns the existing one) to a SoftwareIdentity /// AddDirectory(...) -- adds a Directory to a Payload, Evidence or Directory /// AddFile(...) -- adds a File to a Payload, Evidence or Directory /// AddProcess(...) -- adds a Process to a Payload or Evidence /// AddResource(...) -- adds a Resource to a Payload or Evidence /// </returns> /// <remarks> /// PowerShellMetaProvider notes: /// - may use 'Find-PackageByUri' as the function name. /// - If the provider supports batch operations, the uri parameter should be an array /// - Values can be returned using Write-Object for objects returned from the New-SoftwareIdentity function /// </remarks> #if NEW_SIGNATURES void FindPackageByUri(Uri uri, IRequest requestObject); void FindPackageByUri(Uri[] uris, IRequest requestObject); #endif #if !REMOVE_DEPRECATED_FUNCTIONS void FindPackageByUri(Uri uri, int id, IRequest requestObject); #endif /// <summary> /// Returns Software Identities for installed packages /// </summary> /// <param name="name">matches against the name of a package. If this is null or empty, should return all matching packages.</param> /// <param name="requiredVersion">an exact version of the package to match. If this is specified, minimum and maximum should be ignored.</param> /// <param name="minimumVersion">the minimum version of the package to match. If requiredVersion is specified, this should be ignored.</param> /// <param name="maximumVersion">the maximum version of the package to match. If requiredVersion is specified, this should be ignored.</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <returns> /// Returns Software Identities thru the use of request.YieldSoftwareIdentity(), and extended data via: /// AddMetadata(...) -- adds key/value pairs to an element /// AddMeta(...) -- adds a new Meta element child to an element /// AddEntity(...) -- adds a new Entity to an element /// AddLink(...) -- adds a new Link to a SoftwareIdentity /// AddDependency(...) -- adds a new 'requires' Link to a SoftwareIdentity /// AddPayload(...) -- adds a Payload (or returns the existing one) to a SoftwareIdentity /// AddEvidence(...) -- adds an Evidence (or returns the existing one) to a SoftwareIdentity /// AddDirectory(...) -- adds a Directory to a Payload, Evidence or Directory /// AddFile(...) -- adds a File to a Payload, Evidence or Directory /// AddProcess(...) -- adds a Process to a Payload or Evidence /// AddResource(...) -- adds a Resource to a Payload or Evidence /// </returns> /// <remarks> /// PowerShellMetaProvider notes: /// - may use 'Get-InstalledPackage' as the function name. /// - Values can be returned using Write-Object for objects returned from the New-SoftwareIdentity function /// </remarks> void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, IRequest requestObject); /// <summary> /// If supported, this should download a package file to the location provided. /// </summary> /// <param name="fastPath"></param> /// <param name="location"></param> /// <param name="requestObject">The request context passed to the provider.</param> /// <remarks> /// PowerShellMetaProvider notes: /// - may use 'Download-Package' as the function name. /// </remarks> void DownloadPackage(string fastPath, string location, IRequest requestObject); /// <summary> /// (not currently used) /// Will be used to allow packages to return full details on demand, rather than at find/get time. /// </summary> /// <param name="fastPath">the round-tripped (from FindPackageXXX or GetInstalledPackages ) identity of the package</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <remarks> /// PowerShellMetaProvider notes: /// - May use 'Get-PackageDetail' as the function name. /// </remarks> void GetPackageDetails(string fastPath, IRequest requestObject); /// <summary> /// Installs a package. /// </summary> /// <param name="fastPath">the round-tripped (from FindPackageXXX) identity of the package to be installed</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <returns> /// Returns Software Identities thru the use of request.YieldSoftwareIdentity(), and extended data via: /// AddMetadata(...) -- adds key/value pairs to an element /// AddMeta(...) -- adds a new Meta element child to an element /// AddEntity(...) -- adds a new Entity to an element /// AddLink(...) -- adds a new Link to a SoftwareIdentity /// AddDependency(...) -- adds a new 'requires' Link to a SoftwareIdentity /// AddPayload(...) -- adds a Payload (or returns the existing one) to a SoftwareIdentity /// AddEvidence(...) -- adds an Evidence (or returns the existing one) to a SoftwareIdentity /// AddDirectory(...) -- adds a Directory to a Payload, Evidence or Directory /// AddFile(...) -- adds a File to a Payload, Evidence or Directory /// AddProcess(...) -- adds a Process to a Payload or Evidence /// AddResource(...) -- adds a Resource to a Payload or Evidence /// </returns> /// <remarks> /// PowerShellMetaProvider notes: /// - May use 'Install-Package' as the function name. /// </remarks> void InstallPackage(string fastPath, IRequest requestObject); /// <summary> /// Uninstalls a package. /// </summary> /// <param name="fastPath">the round-tripped (from GetInstalledPackages) identity of the package to be uninstalled</param> /// <param name="requestObject">The request context passed to the provider.</param> /// <returns> /// Returns Software Identities thru the use of request.YieldSoftwareIdentity(), and extended data via: /// AddMetadata(...) -- adds key/value pairs to an element /// AddMeta(...) -- adds a new Meta element child to an element /// AddEntity(...) -- adds a new Entity to an element /// AddLink(...) -- adds a new Link to a SoftwareIdentity /// AddDependency(...) -- adds a new 'requires' Link to a SoftwareIdentity /// AddPayload(...) -- adds a Payload (or returns the existing one) to a SoftwareIdentity /// AddEvidence(...) -- adds an Evidence (or returns the existing one) to a SoftwareIdentity /// AddDirectory(...) -- adds a Directory to a Payload, Evidence or Directory /// AddFile(...) -- adds a File to a Payload, Evidence or Directory /// AddProcess(...) -- adds a Process to a Payload or Evidence /// AddResource(...) -- adds a Resource to a Payload or Evidence /// </returns> /// <remarks> /// PowerShellMetaProvider notes: /// - May use 'Uninstall-Package' as the function name. /// </remarks> void UninstallPackage(string fastPath, IRequest requestObject); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Types; using System.Numerics; using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Operations { public static partial class DoubleOps { private static Regex _fromHexRegex; [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls) { if (cls == TypeCache.Double) return 0.0; return cls.CreateInstance(context); } [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls, object x) { object value = null; if (x is string) { value = ParseFloat((string)x); } else if (x is Extensible<string>) { if (!PythonTypeOps.TryInvokeUnaryOperator(context, x, "__float__", out value)) { value = ParseFloat(((Extensible<string>)x).Value); } } else if (x is char) { value = ParseFloat(ScriptingRuntimeHelpers.CharToString((char)x)); } else if (x is Complex) { throw PythonOps.TypeError("can't convert complex to float; use abs(z)"); } else { object d = PythonOps.CallWithContext(context, PythonOps.GetBoundAttr(context, x, "__float__")); if (d is double) { value = d; } else if (d is Extensible<double>) { value = ((Extensible<double>)d).Value; } else { throw PythonOps.TypeError("__float__ returned non-float (type {0})", PythonTypeOps.GetName(d)); } } if (cls == TypeCache.Double) { return value; } else { return cls.CreateInstance(context, value); } } [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls, IList<byte> s) { // First, check for subclasses of bytearray/bytes object value; IPythonObject po = s as IPythonObject; if (po == null || !PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__float__", out value)) { // If __float__oes not exist, just parse the string normally value = ParseFloat(s.MakeString()); } if (cls == TypeCache.Double) { return value; } else { return cls.CreateInstance(context, value); } } public static PythonTuple as_integer_ratio(double self) { if (Double.IsInfinity(self)) { throw PythonOps.OverflowError("Cannot pass infinity to float.as_integer_ratio."); } else if (Double.IsNaN(self)) { throw PythonOps.ValueError("Cannot pass nan to float.as_integer_ratio."); } BigInteger dem = 1; while ((self % 1) != 0.0) { self *= 2; dem *= 2; } return PythonTuple.MakeTuple((BigInteger)self, dem); } private static char[] _whitespace = new[] { ' ', '\t', '\n', '\f', '\v', '\r' }; [ClassMethod, StaticExtensionMethod] public static object fromhex(CodeContext/*!*/ context, PythonType/*!*/ cls, string self) { if (String.IsNullOrEmpty(self)) { throw PythonOps.ValueError("expected non empty string"); } self = self.Trim(_whitespace); // look for inf, infinity, nan, etc... double? specialRes = TryParseSpecialFloat(self); if (specialRes != null) { return specialRes.Value; } // nothing special, parse the hex... if (_fromHexRegex == null) { _fromHexRegex = new Regex("\\A\\s*(?<sign>[-+])?(?:0[xX])?(?<integer>[0-9a-fA-F]+)?(?<fraction>\\.[0-9a-fA-F]*)?(?<exponent>[pP][-+]?[0-9]+)?\\s*\\z"); } Match match = _fromHexRegex.Match(self); if (!match.Success) { throw InvalidHexString(); } var sign = match.Groups["sign"]; var integer = match.Groups["integer"]; var fraction = match.Groups["fraction"]; var exponent = match.Groups["exponent"]; bool isNegative = sign.Success && sign.Value == "-"; BigInteger intVal; if (integer.Success) { intVal = LiteralParser.ParseBigInteger(integer.Value, 16); } else { intVal = BigInteger.Zero; } // combine the integer and fractional parts into one big int BigInteger finalBits; int decimalPointBit = 0; // the number of bits of fractions that we have if (fraction.Success) { BigInteger fractionVal = 0; // add the fractional bits to the integer value for (int i = 1; i < fraction.Value.Length; i++) { char chr = fraction.Value[i]; int val; if (chr >= '0' && chr <= '9') { val = chr - '0'; } else if (chr >= 'a' && chr <= 'f') { val = 10 + chr - 'a'; } else if (chr >= 'A' && chr <= 'Z') { val = 10 + chr - 'A'; } else { // unreachable due to the regex throw new InvalidOperationException(); } fractionVal = (fractionVal << 4) | val; decimalPointBit += 4; } finalBits = (intVal << decimalPointBit) | fractionVal; } else { // we only have the integer value finalBits = intVal; } if (exponent.Success) { int exponentVal = 0; if (!Int32.TryParse(exponent.Value.Substring(1), out exponentVal)) { if (exponent.Value.ToLowerAsciiTriggered().StartsWith("p-") || finalBits == BigInteger.Zero) { double zeroRes = isNegative ? NegativeZero : PositiveZero; if (cls == TypeCache.Double) { return zeroRes; } return PythonCalls.Call(cls, zeroRes); } // integer value is too big, no way we're fitting this in. throw HexStringOverflow(); } // update the bits to truly reflect the exponent if (exponentVal > 0) { finalBits = finalBits << exponentVal; } else if (exponentVal < 0) { decimalPointBit -= exponentVal; } } if ((!exponent.Success && !fraction.Success && !integer.Success) || (!integer.Success && fraction.Length == 1)) { throw PythonOps.ValueError("invalid hexidecimal floating point string '{0}'", self); } if (finalBits == BigInteger.Zero) { if (isNegative) { return NegativeZero; } else { return PositiveZero; } } int highBit = finalBits.GetBitCount(); // minus 1 because we'll discard the high bit as it's implicit int finalExponent = highBit - decimalPointBit - 1; while (finalExponent < -1023) { // if we have a number with a very negative exponent // we'll throw away all of the insignificant bits even // if it takes the number down to zero. highBit++; finalExponent++; } if (finalExponent == -1023) { // the exponent bits will be all zero, we're going to be a denormalized number, so // we need to keep the most significant bit. highBit++; } // we have 52 bits to store the exponent. In a normalized number the mantissa has an // implied 1 bit, in denormalized mode it doesn't. int lostBits = highBit - 53; bool rounded = false; if (lostBits > 0) { // we have more bits then we can stick in the double, we need to truncate or round the value. BigInteger finalBitsAndRoundingBit = finalBits >> (lostBits - 1); // check if we need to round up (round half even aka bankers rounding) if ((finalBitsAndRoundingBit & BigInteger.One) != BigInteger.Zero) { // grab the bits we need and the least significant bit which we care about for rounding BigInteger discardedBits = finalBits & ((BigInteger.One << (lostBits - 1)) - 1); if (discardedBits != BigInteger.Zero || // not exactly .5 ((finalBits >> lostBits) & BigInteger.One) != BigInteger.Zero) { // or we're exactly .5 and odd and need to round up // round the value up by adding 1 BigInteger roundedBits = finalBitsAndRoundingBit + 1; // now remove the least significant bit we kept for rounding finalBits = (roundedBits >> 1) & 0xfffffffffffff; // check to see if we overflowed into the next bit (e.g. we had a pattern like ffffff rounding to 1000000) if (roundedBits.GetBitCount() != finalBitsAndRoundingBit.GetBitCount()) { if (finalExponent != -1023) { // we overflowed and we're a normalized number. Discard the new least significant bit so we have // the correct number of bits. We need to raise the exponent to account for this division by 2. finalBits = finalBits >> 1; finalExponent++; } else if (finalBits == BigInteger.Zero) { // we overflowed and we're a denormalized number == 0. Increase the exponent making us a normalized // number. Don't adjust the bits because we're now gaining an implicit 1 bit. finalExponent++; } } rounded = true; } } } if (!rounded) { // no rounding is necessary, just shift the bits to get the mantissa finalBits = (finalBits >> (highBit - 53)) & 0xfffffffffffff; } if (finalExponent > 1023) { throw HexStringOverflow(); } // finally assemble the bits long bits = (long)finalBits; bits |= (((long)finalExponent) + 1023) << 52; if (isNegative) { bits |= unchecked((long)0x8000000000000000); } double res = BitConverter.Int64BitsToDouble(bits); if (cls == TypeCache.Double) { return res; } return PythonCalls.Call(cls, res); } private static double? TryParseSpecialFloat(string self) { switch (self.ToLower()) { case "inf": case "+inf": case "infinity": case "+infinity": return Double.PositiveInfinity; case "-inf": case "-infinity": return Double.NegativeInfinity; case "nan": case "+nan": case "-nan": return Double.NaN; } return null; } private static Exception HexStringOverflow() { return PythonOps.OverflowError("hexadecimal value too large to represent as a float"); } private static Exception InvalidHexString() { return PythonOps.ValueError("invalid hexadecimal floating-point string"); } public static string hex(double self) { if (Double.IsPositiveInfinity(self)) { return "inf"; } else if (Double.IsNegativeInfinity(self)) { return "-inf"; } else if (Double.IsNaN(self)) { return "nan"; } ulong bits = (ulong)BitConverter.DoubleToInt64Bits(self); int exponent = (int)((bits >> 52) & 0x7ff) - 1023; long mantissa = (long)(bits & 0xfffffffffffff); StringBuilder res = new StringBuilder(); if ((bits & 0x8000000000000000) != 0) { // negative res.Append('-'); } if (exponent == -1023) { res.Append("0x0."); exponent++; } else { res.Append("0x1."); } res.Append(StringFormatSpec.FromString("013").AlignNumericText(BigIntegerOps.AbsToHex(mantissa, true), mantissa == 0, true)); res.Append("p"); if (exponent >= 0) { res.Append('+'); } res.Append(exponent.ToString()); return res.ToString(); } public static bool is_integer(double self) { return (self % 1.0) == 0.0; } private static double ParseFloat(string x) { try { double? res = TryParseSpecialFloat(x); if (res != null) { return res.Value; } return LiteralParser.ParseFloat(x); } catch (FormatException) { throw PythonOps.ValueError("invalid literal for float(): {0}", x); } } #region Binary operators [SpecialName] public static object DivMod(double x, double y) { if (y == 0) throw PythonOps.ZeroDivisionError(); // .NET does not provide Math.DivRem() for floats. Implementation along the CPython code. var mod = Math.IEEERemainder(x, y); var div = (x - mod) / y; if (mod != 0) { if ((y < 0) != (mod < 0)) { mod += y; div -= 1; } } else { mod = CopySign(0, y); } double floordiv; if (div != 0) { floordiv = Math.Floor(div); if (div - floordiv > 0.5) floordiv += 1; } else { floordiv = CopySign(0, x / y); } return PythonTuple.MakeTuple(floordiv, mod); } [SpecialName] public static double Mod(double x, double y) { if (y == 0) throw PythonOps.ZeroDivisionError(); // implemented as in CPython var mod = Math.IEEERemainder(x, y); if (mod != 0) { if ((y < 0) != (mod < 0)) { mod += y; } } else { mod = CopySign(0, y); } return mod; } [SpecialName] public static double Power(double x, double y) { if (x == 1.0 || y == 0.0) { return 1.0; } else if (double.IsNaN(x) || double.IsNaN(y)) { return double.NaN; } else if (x == 0.0) { if (y > 0.0) { // preserve sign if y is a positive, odd int if (y % 2.0 == 1.0) { return x; } return 0.0; } else if (y == 0.0) { return 1.0; } else if (double.IsNegativeInfinity(y)) { return double.PositiveInfinity; } throw PythonOps.ZeroDivisionError("0.0 cannot be raised to a negative power"); } else if (double.IsPositiveInfinity(y)) { if (x > 1.0 || x < -1.0) { return double.PositiveInfinity; } else if (x == -1.0) { return 1.0; } return 0.0; } else if (double.IsNegativeInfinity(y)) { if (x > 1.0 || x < -1.0) { return 0.0; } else if (x == -1.0) { return 1.0; } return double.PositiveInfinity; } else if (double.IsNegativeInfinity(x)) { // preserve negative sign if y is an odd int if (Math.Abs(y % 2.0) == 1.0) { return y > 0 ? double.NegativeInfinity : NegativeZero; } else { return y > 0 ? double.PositiveInfinity : 0.0; } } else if (x < 0 && (Math.Floor(y) != y)) { throw PythonOps.ValueError("negative number cannot be raised to fraction"); } return PythonOps.CheckMath(x, y, Math.Pow(x, y)); } #endregion public static PythonTuple __coerce__(CodeContext context, double x, object o) { // called via builtin.coerce() double d = (double)__new__(context, TypeCache.Double, o); if (Double.IsInfinity(d)) { throw PythonOps.OverflowError("number too big"); } return PythonTuple.MakeTuple(x, d); } #region Unary operators public static object __int__(double d) { if (Int32.MinValue <= d && d <= Int32.MaxValue) { return (int)d; } else if (double.IsInfinity(d)) { throw PythonOps.OverflowError("cannot convert float infinity to integer"); } else if (double.IsNaN(d)) { throw PythonOps.ValueError("cannot convert float NaN to integer"); } else { return (BigInteger)d; } } public static object __getnewargs__(CodeContext context, double self) { return PythonTuple.MakeTuple(DoubleOps.__new__(context, TypeCache.Double, self)); } #endregion #region ToString public static string __str__(CodeContext/*!*/ context, double x) { StringFormatter sf = new StringFormatter(context, "%.12g", x); sf._TrailingZeroAfterWholeFloat = true; return sf.Format(); } public static string __str__(double x, IFormatProvider provider) { return x.ToString(provider); } public static string __str__(double x, string format) { return x.ToString(format); } public static string __str__(double x, string format, IFormatProvider provider) { return x.ToString(format, provider); } public static int __hash__(double d) { // Python allows equality between floats, ints, and big ints. if ((d % 1) == 0) { // This double represents an integer, so it must hash like an integer. if (Int32.MinValue <= d && d <= Int32.MaxValue) { return ((int)d).GetHashCode(); } // Big integer BigInteger b = (BigInteger)d; return BigIntegerOps.__hash__(b); } // Special values if (double.IsInfinity(d)) { return d > 0 ? 314159 : -271828; } else if (double.IsNaN(d)) { return 0; } return d.GetHashCode(); } #endregion [SpecialName] public static bool LessThan(double x, double y) { return x < y && !(Double.IsInfinity(x) && Double.IsNaN(y)) && !(Double.IsNaN(x) && Double.IsInfinity(y)); } [SpecialName] public static bool LessThanOrEqual(double x, double y) { if (x == y) { return !Double.IsNaN(x); } return x < y; } [SpecialName] public static bool GreaterThan(double x, double y) { return x > y && !(Double.IsInfinity(x) && Double.IsNaN(y)) && !(Double.IsNaN(x) && Double.IsInfinity(y)); } [SpecialName] public static bool GreaterThanOrEqual(double x, double y) { if (x == y) { return !Double.IsNaN(x); } return x > y; } [SpecialName] public static bool Equals(double x, double y) { if (x == y) { return !Double.IsNaN(x); } return false; } [SpecialName] public static bool NotEquals(double x, double y) { if (x == y) { return Double.IsNaN(x); } return true; } [SpecialName] public static bool LessThan(double x, BigInteger y) { return Compare(x, y) < 0; } [SpecialName] public static bool LessThanOrEqual(double x, BigInteger y) { return Compare(x, y) <= 0; } [SpecialName] public static bool GreaterThan(double x, BigInteger y) { return Compare(x, y) > 0; } [SpecialName] public static bool GreaterThanOrEqual(double x, BigInteger y) { return Compare(x, y) >= 0; } [SpecialName] public static bool Equals(double x, BigInteger y) { return Compare(x, y) == 0; } [SpecialName] public static bool NotEquals(double x, BigInteger y) { return Compare(x, y) != 0; } internal const double PositiveZero = 0.0; internal const double NegativeZero = -0.0; internal static bool IsPositiveZero(double value) { return (value == 0.0) && double.IsPositiveInfinity(1.0 / value); } internal static bool IsNegativeZero(double value) { return (value == 0.0) && double.IsNegativeInfinity(1.0 / value); } internal static int Sign(double value) { if (value == 0.0) { return double.IsPositiveInfinity(1.0 / value) ? 1 : -1; } else { // note: NaN intentionally shows up as negative return value > 0 ? 1 : -1; } } internal static double CopySign(double value, double sign) { return Sign(sign) * Math.Abs(value); } internal static int Compare(double x, double y) { if (Double.IsInfinity(x) && Double.IsNaN(y)) { return 1; } else if (Double.IsNaN(x) && Double.IsInfinity(y)) { return -1; } return x > y ? 1 : x == y ? 0 : -1; } internal static int Compare(double x, BigInteger y) { return -Compare(y, x); } internal static int Compare(BigInteger x, double y) { if (double.IsNaN(y) || double.IsPositiveInfinity(y)) { return -1; } else if (y == Double.NegativeInfinity) { return 1; } // BigInts can hold doubles, but doubles can't hold BigInts, so // if we're comparing against a BigInt then we should convert ourself // to a long and then compare. BigInteger by = (BigInteger)y; if (by == x) { double mod = y % 1; if (mod == 0) return 0; if (mod > 0) return -1; return +1; } if (by > x) return -1; return +1; } [SpecialName] public static bool LessThan(double x, decimal y) { return Compare(x, y) < 0; } [SpecialName] public static bool LessThanOrEqual(double x, decimal y) { return Compare(x, y) <= 0; } [SpecialName] public static bool GreaterThan(double x, decimal y) { return Compare(x, y) > 0; } [SpecialName] public static bool GreaterThanOrEqual(double x, decimal y) { return Compare(x, y) >= 0; } [SpecialName] public static bool Equals(double x, decimal y) { return Compare(x, y) == 0; } [SpecialName] public static bool NotEquals(double x, decimal y) { return Compare(x, y) != 0; } internal static int Compare(double x, decimal y) { if (x > (double)decimal.MaxValue) return +1; #if ANDROID // TODO: ? const decimal minValue = -79228162514264337593543950335m; if (x < (double)minValue) return -1; #else if (x < (double)decimal.MinValue) return -1; #endif return ((decimal)x).CompareTo(y); } [SpecialName] public static bool LessThan(Double x, int y) { return x < y; } [SpecialName] public static bool LessThanOrEqual(Double x, int y) { return x <= y; } [SpecialName] public static bool GreaterThan(Double x, int y) { return x > y; } [SpecialName] public static bool GreaterThanOrEqual(Double x, int y) { return x >= y; } [SpecialName] public static bool Equals(Double x, int y) { return x == y; } [SpecialName] public static bool NotEquals(Double x, int y) { return x != y; } public static string __repr__(CodeContext/*!*/ context, double self) { if (Double.IsNaN(self)) { return "nan"; } // first format using Python's specific formatting rules... StringFormatter sf = new StringFormatter(context, "%.17g", self); sf._TrailingZeroAfterWholeFloat = true; string res = sf.Format(); if (LiteralParser.ParseFloat(res) == self) { return res; } // if it's not round trippable though use .NET's round-trip format return self.ToString("R", CultureInfo.InvariantCulture); } public static BigInteger/*!*/ __long__(double self) { if (double.IsInfinity(self)) { throw PythonOps.OverflowError("cannot convert float infinity to integer"); } else if (double.IsNaN(self)) { throw PythonOps.ValueError("cannot convert float NaN to integer"); } else { return (BigInteger)self; } } public static double __float__(double self) { return self; } public static string __getformat__(CodeContext/*!*/ context, string typestr) { FloatFormat res; switch (typestr) { case "float": res = context.LanguageContext.FloatFormat; break; case "double": res = context.LanguageContext.DoubleFormat; break; default: throw PythonOps.ValueError("__getformat__() argument 1 must be 'double' or 'float'"); } switch (res) { case FloatFormat.Unknown: return "unknown"; case FloatFormat.IEEE_BigEndian: return "IEEE, big-endian"; case FloatFormat.IEEE_LittleEndian: return "IEEE, little-endian"; default: return DefaultFloatFormat(); } } public static string __format__(CodeContext/*!*/ context, double self, [NotNull]string/*!*/ formatSpec) { if (formatSpec == string.Empty) return __str__(context, self); StringFormatSpec spec = StringFormatSpec.FromString(formatSpec); string digits; if (Double.IsPositiveInfinity(self) || Double.IsNegativeInfinity(self)) { if (spec.Type != null && char.IsUpper(spec.Type.Value)) { digits = "INF"; } else { digits = "inf"; } } else if (Double.IsNaN(self)) { if (spec.Type != null && char.IsUpper(spec.Type.Value)) { digits = "NAN"; } else { digits = "nan"; } } else { digits = DoubleToFormatString(context, self, spec); } if (spec.Sign == null) { // This is special because its not "-nan", it's nan. // Always pass isZero=false so that -0.0 shows up return spec.AlignNumericText(digits, false, Double.IsNaN(self) || Sign(self) > 0); } else { // Always pass isZero=false so that -0.0 shows up return spec.AlignNumericText(digits, false, Double.IsNaN(self) ? true : Sign(self) > 0); } } /// <summary> /// Returns the digits for the format spec, no sign is included. /// </summary> private static string DoubleToFormatString(CodeContext/*!*/ context, double self, StringFormatSpec/*!*/ spec) { self = Math.Abs(self); const int DefaultPrecision = 6; int precision = spec.Precision ?? DefaultPrecision; string digits; switch (spec.Type) { case '%': { string fmt = "0." + new string('0', precision) + "%"; if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt, CultureInfo.InvariantCulture); break; } case 'f': case 'F': { string fmt = "0." + new string('0', precision); if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt, CultureInfo.InvariantCulture); break; } case 'e': case 'E': { string fmt = "0." + new string('0', precision) + spec.Type + "+00"; if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt, CultureInfo.InvariantCulture); break; } case '\0': case null: if (spec.Precision != null) { // precision applies to the combined digits before and after the decimal point // so we first need find out how many digits we have before... int digitCnt = 1; double cur = self; while (cur >= 10) { cur /= 10; digitCnt++; } // Use exponents if we don't have enough room for all the digits before. If we // only have as single digit avoid exponents. if (digitCnt > spec.Precision.Value && digitCnt != 1) { // first round off the decimal value self = MathUtils.Round(self, 0, MidpointRounding.AwayFromZero); // then remove any insignificant digits double pow = Math.Pow(10, digitCnt - Math.Max(spec.Precision.Value, 1)); self = self - (self % pow); // finally format w/ the requested precision string fmt = "0.0" + new string('#', spec.Precision.Value); digits = self.ToString(fmt + "e+00", CultureInfo.InvariantCulture); } else { // we're including all the numbers to the right of the decimal we can, we explicitly // round to match CPython's behavior int decimalPoints = Math.Max(spec.Precision.Value - digitCnt, 0); self = MathUtils.Round(self, decimalPoints, MidpointRounding.AwayFromZero); digits = self.ToString("0.0" + new string('#', decimalPoints)); } } else { // just the default formatting if (IncludeExponent(self)) { digits = self.ToString("0.#e+00", CultureInfo.InvariantCulture); } else if (spec.ThousandsComma) { digits = self.ToString("#,0.0###", CultureInfo.InvariantCulture); } else { digits = self.ToString("0.0###", CultureInfo.InvariantCulture); } } break; case 'n': case 'g': case 'G': { // precision applies to the combined digits before and after the decimal point // so we first need find out how many digits we have before... int digitCnt = 1; double cur = self; while (cur >= 10) { cur /= 10; digitCnt++; } // Use exponents if we don't have enough room for all the digits before. If we // only have as single digit avoid exponents. if (digitCnt > precision && digitCnt != 1) { // first round off the decimal value self = MathUtils.Round(self, 0, MidpointRounding.AwayFromZero); // then remove any insignificant digits double pow = Math.Pow(10, digitCnt - Math.Max(precision, 1)); double rest = self / pow; self = self - self % pow; if ((rest % 1) >= .5) { // round up self += pow; } string fmt; if (spec.Type == 'n' && context.LanguageContext.NumericCulture != PythonContext.CCulture) { // we've already figured out, we don't have any digits for decimal points, so just format as a number + exponent fmt = "0"; } else if (spec.Precision > 1 || digitCnt > 6) { // include the requested precision to the right of the decimal fmt = "0.#" + new string('#', precision); } else { // zero precision, no decimal fmt = "0"; } if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt + (spec.Type == 'G' ? "E+00" : "e+00"), CultureInfo.InvariantCulture); } else { // we're including all the numbers to the right of the decimal we can, we explicitly // round to match CPython's behavior if (self < 1) { // no implicit 0 digitCnt--; } int decimalPoints = Math.Max(precision - digitCnt, 0); self = MathUtils.Round(self, decimalPoints, MidpointRounding.AwayFromZero); if (spec.Type == 'n' && context.LanguageContext.NumericCulture != PythonContext.CCulture) { if (digitCnt != precision && (self % 1) != 0) { digits = self.ToString("#,0.0" + new string('#', decimalPoints)); } else { // leave out the decimal if the precision == # of digits or we have a whole number digits = self.ToString("#,0"); } } else { if (digitCnt != precision && (self % 1) != 0) { digits = self.ToString("0.0" + new string('#', decimalPoints)); } else { // leave out the decimal if the precision == # of digits or we have a whole number digits = self.ToString("0"); } } } } break; default: throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'float'", spec.Type.ToString()); } return digits; } private static bool IncludeExponent(double self) { return self >= 1e12 || (self != 0 && self <= 0.00009); } private static string DefaultFloatFormat() { if (BitConverter.IsLittleEndian) { return "IEEE, little-endian"; } return "IEEE, big-endian"; } public static void __setformat__(CodeContext/*!*/ context, string typestr, string fmt) { FloatFormat format; switch (fmt) { case "unknown": format = FloatFormat.Unknown; break; case "IEEE, little-endian": if (!BitConverter.IsLittleEndian) { throw PythonOps.ValueError("can only set double format to 'unknown' or the detected platform value"); } format = FloatFormat.IEEE_LittleEndian; break; case "IEEE, big-endian": if (BitConverter.IsLittleEndian) { throw PythonOps.ValueError("can only set double format to 'unknown' or the detected platform value"); } format = FloatFormat.IEEE_BigEndian; break; default: throw PythonOps.ValueError(" __setformat__() argument 2 must be 'unknown', 'IEEE, little-endian' or 'IEEE, big-endian'"); } switch (typestr) { case "float": context.LanguageContext.FloatFormat = format; break; case "double": context.LanguageContext.DoubleFormat = format; break; default: throw PythonOps.ValueError("__setformat__() argument 1 must be 'double' or 'float'"); } } } internal enum FloatFormat { None, Unknown, IEEE_LittleEndian, IEEE_BigEndian } public partial class SingleOps { [SpecialName] public static bool LessThan(float x, float y) { return x < y; } [SpecialName] public static bool LessThanOrEqual(float x, float y) { if (x == y) { return !Single.IsNaN(x); } return x < y; } [SpecialName] public static bool GreaterThan(float x, float y) { return x > y; } [SpecialName] public static bool GreaterThanOrEqual(float x, float y) { if (x == y) { return !Single.IsNaN(x); } return x > y; } [SpecialName] public static bool Equals(float x, float y) { if (x == y) { return !Single.IsNaN(x); } return x == y; } [SpecialName] public static bool NotEquals(float x, float y) { return !Equals(x, y); } [SpecialName] public static float Mod(float x, float y) { return (float)DoubleOps.Mod(x, y); } [SpecialName] public static float Power(float x, float y) { return (float)DoubleOps.Power(x, y); } [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls) { if (cls == TypeCache.Single) return (float)0.0; return cls.CreateInstance(context); } [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls, object x) { if (cls != TypeCache.Single) { return cls.CreateInstance(context, x); } if (x is string) { return ParseFloat((string)x); } else if (x is Extensible<string>) { return ParseFloat(((Extensible<string>)x).Value); } else if (x is char) { return ParseFloat(ScriptingRuntimeHelpers.CharToString((char)x)); } double doubleVal; if (Converter.TryConvertToDouble(x, out doubleVal)) return (float)doubleVal; if (x is Complex) throw PythonOps.TypeError("can't convert complex to Single; use abs(z)"); object d = PythonOps.CallWithContext(context, PythonOps.GetBoundAttr(context, x, "__float__")); if (d is double) return (float)(double)d; throw PythonOps.TypeError("__float__ returned non-float (type %s)", DynamicHelpers.GetPythonType(d)); } [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls, IList<byte> s) { // First, check for subclasses of bytearray/bytes object value; IPythonObject po = s as IPythonObject; if (po == null || !PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__float__", out value)) { // If __float__ does not exist, just parse the string normally value = ParseFloat(s.MakeString()); } if (!(value is double)) { // The check for double is correct, because that's all Python types should be using throw PythonOps.TypeError("__float__ returned non-float (type %s)", DynamicHelpers.GetPythonType(value)); } if (cls == TypeCache.Single) { return (float)value; } else { return cls.CreateInstance(context, (float)value); } } private static object ParseFloat(string x) { try { return (float)LiteralParser.ParseFloat(x); } catch (FormatException) { throw PythonOps.ValueError("invalid literal for Single(): {0}", x); } } public static string __str__(CodeContext/*!*/ context, float x) { // Python does not natively support System.Single. However, we try to provide // formatting consistent with System.Double. StringFormatter sf = new StringFormatter(context, "%.6g", x); sf._TrailingZeroAfterWholeFloat = true; return sf.Format(); } public static string __repr__(CodeContext/*!*/ context, float self) { return __str__(context, self); } public static string __format__(CodeContext/*!*/ context, float self, [NotNull]string/*!*/ formatSpec) { return DoubleOps.__format__(context, self, formatSpec); } public static int __hash__(float x) { return DoubleOps.__hash__(((double)x)); } public static double __float__(float x) { return x; } } }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract class AbstractUserDiagnosticTest { protected abstract string GetLanguage(); protected abstract ParseOptions GetScriptOptions(); protected abstract TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions); internal abstract IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(TestWorkspace workspace, string fixAllActionEquivalenceKey); internal abstract IEnumerable<Diagnostic> GetDiagnostics(TestWorkspace workspace); protected virtual void TestMissing(string initial, IDictionary<OptionKey, object> options = null, string fixAllActionEquivalenceKey = null) { TestMissing(initial, null, options, fixAllActionEquivalenceKey); TestMissing(initial, GetScriptOptions(), options, fixAllActionEquivalenceKey); } protected virtual void TestMissing(string initial, ParseOptions parseOptions, IDictionary<OptionKey, object> options = null, string fixAllActionEquivalenceKey = null) { TestMissing(initial, parseOptions, null, options, fixAllActionEquivalenceKey); } protected void TestMissing(string initialMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions, IDictionary<OptionKey, object> options = null, string fixAllActionEquivalenceKey = null) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { if (options != null) { ApplyOptionsToWorkspace(options, workspace); } var diagnostics = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey); Assert.False(diagnostics?.Item2?.Fixes.IsEmpty == true); } } protected void Test( string initial, string expected, int index = 0, bool compareTokens = true, bool isLine = true, IDictionary<OptionKey, object> options = null, bool isAddedDocument = false, string fixAllActionEquivalenceKey = null) { Test(initial, expected, null, index, compareTokens, isLine, options, isAddedDocument, fixAllActionEquivalenceKey); Test(initial, expected, GetScriptOptions(), index, compareTokens, isLine, options, isAddedDocument, fixAllActionEquivalenceKey); } protected void Test( string initial, string expected, ParseOptions parseOptions, int index = 0, bool compareTokens = true, bool isLine = true, IDictionary<OptionKey, object> options = null, bool isAddedDocument = false, string fixAllActionEquivalenceKey = null) { Test(initial, expected, parseOptions, null, index, compareTokens, isLine, options, isAddedDocument, fixAllActionEquivalenceKey); } protected void Test( string initialMarkup, string expectedMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions, int index = 0, bool compareTokens = true, bool isLine = true, IDictionary<OptionKey, object> options = null, bool isAddedDocument = false, string fixAllActionEquivalenceKey = null) { string expected; IDictionary<string, IList<TextSpan>> spanMap; MarkupTestFile.GetSpans(expectedMarkup.NormalizeLineEndings(), out expected, out spanMap); var conflictSpans = spanMap.GetOrAdd("Conflict", _ => new List<TextSpan>()); var renameSpans = spanMap.GetOrAdd("Rename", _ => new List<TextSpan>()); var warningSpans = spanMap.GetOrAdd("Warning", _ => new List<TextSpan>()); using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup)) { if (options != null) { ApplyOptionsToWorkspace(options, workspace); } var diagnosticAndFixes = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey); Assert.NotNull(diagnosticAndFixes); TestActions( workspace, expected, index, diagnosticAndFixes.Item2.Fixes.Select(f => f.Action).ToList(), conflictSpans, renameSpans, warningSpans, compareTokens: compareTokens, isAddedDocument: isAddedDocument); } } private static void ApplyOptionsToWorkspace(IDictionary<OptionKey, object> options, TestWorkspace workspace) { var optionService = workspace.Services.GetService<IOptionService>(); var optionSet = optionService.GetOptions(); foreach (var option in options) { optionSet = optionSet.WithChangedOption(option.Key, option.Value); } optionService.SetOptions(optionSet); } internal Tuple<Diagnostic, CodeFixCollection> GetDiagnosticAndFix(TestWorkspace workspace, string fixAllActionEquivalenceKey = null) { return GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceKey).FirstOrDefault(); } protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any()); span = hostDocument.SelectedSpans.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span) { var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any()); if (hostDocument == null) { document = null; span = default(TextSpan); return false; } span = hostDocument.SelectedSpans.Single(); document = workspace.CurrentSolution.GetDocument(hostDocument.Id); return true; } protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any()); var annotatedSpan = hostDocument.AnnotatedSpans.Single(); annotation = annotatedSpan.Key; span = annotatedSpan.Value.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected FixAllScope GetFixAllScope(string annotation) { switch (annotation) { case "FixAllInDocument": return FixAllScope.Document; case "FixAllInProject": return FixAllScope.Project; case "FixAllInSolution": return FixAllScope.Solution; } throw new InvalidProgramException("Incorrect FixAll annotation in test"); } protected void TestSmartTagText( string initialMarkup, string displayText, int index = 0, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = GetDiagnosticAndFix(workspace); Assert.Equal(displayText, diagnosticAndFix.Item2.Fixes.ElementAt(index).Action.Title); } } protected void TestExactActionSetOffered( string initialMarkup, IEnumerable<string> expectedActionSet, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = GetDiagnosticAndFix(workspace); var actualActionSet = diagnosticAndFix.Item2.Fixes.Select(f => f.Action.Title); Assert.True(actualActionSet.SequenceEqual(expectedActionSet), "Expected: " + string.Join(", ", expectedActionSet) + "\nActual: " + string.Join(", ", actualActionSet)); } } protected void TestActionCount( string initialMarkup, int count, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = GetDiagnosticAndFix(workspace); Assert.Equal(count, diagnosticAndFix.Item2.Fixes.Count()); } } protected void TestActionCountInAllFixes( string initialMarkup, int count, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = GetDiagnosticAndFixes(workspace, null); var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum(); Assert.Equal(count, diagnosticCount); } } protected Tuple<Solution, Solution> ApplyOperationsAndGetSolution( TestWorkspace workspace, IEnumerable<CodeActionOperation> operations) { var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); var oldSolution = workspace.CurrentSolution; var newSolution = applyChangesOperation.ChangedSolution; return Tuple.Create(oldSolution, newSolution); } protected Tuple<Solution, Solution> TestActions( TestWorkspace workspace, string expectedText, IEnumerable<CodeActionOperation> operations, DocumentId expectedChangedDocumentId = null, IList<TextSpan> expectedConflictSpans = null, IList<TextSpan> expectedRenameSpans = null, IList<TextSpan> expectedWarningSpans = null, bool compareTokens = true, bool isAddedDocument = false) { var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; Document document = null; if (expectedText.TrimStart('\r', '\n', ' ').StartsWith("<Workspace>", StringComparison.Ordinal)) { using (var expectedWorkspace = TestWorkspaceFactory.CreateWorkspace(expectedText)) { var expectedSolution = expectedWorkspace.CurrentSolution; Assert.Equal(expectedSolution.Projects.Count(), newSolution.Projects.Count()); foreach (var project in newSolution.Projects) { var expectedProject = expectedSolution.GetProjectsByName(project.Name).Single(); Assert.Equal(expectedProject.Documents.Count(), project.Documents.Count()); foreach (var doc in project.Documents) { var root = doc.GetSyntaxRootAsync().Result; var expectedDocument = expectedProject.Documents.Single(d => d.Name == doc.Name); var expectedRoot = expectedDocument.GetSyntaxRootAsync().Result; Assert.Equal(expectedRoot.ToFullString(), root.ToFullString()); } } } } else { // If the expectedChangedDocumentId is not mentioned then we expect only single document to be changed if (expectedChangedDocumentId == null) { if (!isAddedDocument) { // This method assumes that only one document changed and rest(Project state) remains unchanged document = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolution); } else { // This method assumes that only one document added and rest(Project state) remains unchanged document = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution); Assert.Empty(SolutionUtilities.GetChangedDocuments(oldSolution, newSolution)); } } else { // This method obtains only the document changed and does not check the project state. document = newSolution.GetDocument(expectedChangedDocumentId); } var fixedRoot = document.GetSyntaxRootAsync().Result; var actualText = compareTokens ? fixedRoot.ToString() : fixedRoot.ToFullString(); if (compareTokens) { TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage()); } else { Assert.Equal(expectedText, actualText); } TestAnnotations(expectedText, expectedConflictSpans, fixedRoot, ConflictAnnotation.Kind, compareTokens); TestAnnotations(expectedText, expectedRenameSpans, fixedRoot, RenameAnnotation.Kind, compareTokens); TestAnnotations(expectedText, expectedWarningSpans, fixedRoot, WarningAnnotation.Kind, compareTokens); } return Tuple.Create(oldSolution, newSolution); } protected void TestActions( TestWorkspace workspace, string expectedText, int index, IList<CodeAction> actions, IList<TextSpan> expectedConflictSpans = null, IList<TextSpan> expectedRenameSpans = null, IList<TextSpan> expectedWarningSpans = null, bool compareTokens = true, bool isAddedDocument = false) { Assert.NotNull(actions); if (actions.Count == 1) { var suppressionAction = actions.Single() as SuppressionCodeAction; if (suppressionAction != null) { actions = suppressionAction.NestedActions.ToList(); } } Assert.InRange(index, 0, actions.Count - 1); var operations = actions[index].GetOperationsAsync(CancellationToken.None).Result; TestActions( workspace, expectedText, operations, expectedConflictSpans: expectedConflictSpans, expectedRenameSpans: expectedRenameSpans, expectedWarningSpans: expectedWarningSpans, compareTokens: compareTokens, isAddedDocument: isAddedDocument); } private void TestAnnotations( string expectedText, IList<TextSpan> expectedSpans, SyntaxNode fixedRoot, string annotationKind, bool compareTokens) { expectedSpans = expectedSpans ?? new List<TextSpan>(); var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList(); Assert.Equal(expectedSpans.Count, annotatedTokens.Count); if (expectedSpans.Count > 0) { var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage())); var actualTokens = TokenUtilities.GetTokens(fixedRoot); for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++) { var expectedToken = expectedTokens[i]; var actualToken = actualTokens[i]; var actualIsConflict = annotatedTokens.Contains(actualToken); var expectedIsConflict = expectedSpans.Contains(expectedToken.Span); Assert.Equal(expectedIsConflict, actualIsConflict); } } } protected void TestSpans( string initialMarkup, string expectedMarkup, int index = 0, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, string diagnosticId = null, string fixAllActionEquivalenceId = null) { IList<TextSpan> spansList; string unused; MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList); var expectedTextSpans = spansList.ToSet(); using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { ISet<TextSpan> actualTextSpans; if (diagnosticId == null) { var diagnosticsAndFixes = GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceId); var diagnostics = diagnosticsAndFixes.Select(t => t.Item1); actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet(); } else { var diagnostics = GetDiagnostics(workspace); actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet(); } Assert.True(expectedTextSpans.SetEquals(actualTextSpans)); } } protected void TestAddDocument( string initial, string expected, IList<string> expectedContainers, string expectedDocumentName, int index = 0, bool compareTokens = true, bool isLine = true) { TestAddDocument(initial, expected, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine); TestAddDocument(initial, expected, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine); } private void TestAddDocument( string initialMarkup, string expected, int index, IList<string> expectedContainers, string expectedDocumentName, ParseOptions parseOptions, CompilationOptions compilationOptions, bool compareTokens, bool isLine) { using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup)) { var diagnosticAndFix = GetDiagnosticAndFix(workspace); TestAddDocument(workspace, expected, index, expectedContainers, expectedDocumentName, diagnosticAndFix.Item2.Fixes.Select(f => f.Action).ToList(), compareTokens); } } private void TestAddDocument( TestWorkspace workspace, string expected, int index, IList<string> expectedFolders, string expectedDocumentName, IList<CodeAction> fixes, bool compareTokens) { Assert.NotNull(fixes); Assert.InRange(index, 0, fixes.Count - 1); var operations = fixes[index].GetOperationsAsync(CancellationToken.None).Result; TestAddDocument( workspace, expected, operations, hasProjectChange: false, modifiedProjectId: null, expectedFolders: expectedFolders, expectedDocumentName: expectedDocumentName, compareTokens: compareTokens); } private Tuple<Solution, Solution> TestAddDocument( TestWorkspace workspace, string expected, IEnumerable<CodeActionOperation> operations, bool hasProjectChange, ProjectId modifiedProjectId, IList<string> expectedFolders, string expectedDocumentName, bool compareTokens) { var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; Document addedDocument = null; if (!hasProjectChange) { addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution); } else { Assert.NotNull(modifiedProjectId); addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName); } Assert.NotNull(addedDocument); AssertEx.Equal(expectedFolders, addedDocument.Folders); Assert.Equal(expectedDocumentName, addedDocument.Name); if (compareTokens) { TokenUtilities.AssertTokensEqual( expected, addedDocument.GetTextAsync().Result.ToString(), GetLanguage()); } else { Assert.Equal(expected, addedDocument.GetTextAsync().Result.ToString()); } var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); if (!hasProjectChange) { // If there is just one document change then we expect the preview to be a WpfTextView var content = editHandler.GetPreview(workspace, operations, CancellationToken.None); var diffView = content as IWpfDifferenceViewer; Assert.NotNull(diffView); diffView.Close(); } else { // If there are more changes than just the document we need to browse all the changes and get the document change var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None); bool hasPreview = false; object preview; while ((preview = contents.TakeNextPreview()) != null) { var diffView = preview as IWpfDifferenceViewer; if (diffView != null) { hasPreview = true; diffView.Close(); break; } } Assert.True(hasPreview); } return Tuple.Create(oldSolution, newSolution); } internal void TestWithMockedGenerateTypeDialog( string initial, string languageName, string typeName, string expected = null, bool isLine = true, bool isMissing = false, Accessibility accessibility = Accessibility.NotApplicable, TypeKind typeKind = TypeKind.Class, string projectName = null, bool isNewFile = false, string existingFilename = null, IList<string> newFileFolderContainers = null, string fullFilePath = null, string newFileName = null, string assertClassName = null, bool checkIfUsingsIncluded = false, bool checkIfUsingsNotIncluded = false, string expectedTextWithUsings = null, string defaultNamespace = "", bool areFoldersValidIdentifiers = true, GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null, IList<TypeKindOptions> assertTypeKindPresent = null, IList<TypeKindOptions> assertTypeKindAbsent = null, bool isCancelled = false) { using (var testState = new GenerateTypeTestState(initial, isLine, projectName, typeName, existingFilename, languageName)) { // Initialize the viewModel values testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions( accessibility: accessibility, typeKind: typeKind, typeName: testState.TypeName, project: testState.ProjectToBeModified, isNewFile: isNewFile, newFileName: newFileName, folders: newFileFolderContainers, fullFilePath: fullFilePath, existingDocument: testState.ExistingDocument, areFoldersValidIdentifiers: areFoldersValidIdentifiers, isCancelled: isCancelled); testState.TestProjectManagementService.SetDefaultNamespace( defaultNamespace: defaultNamespace); var diagnosticsAndFixes = GetDiagnosticAndFixes(testState.Workspace, null); var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id)); if (isMissing) { Assert.Null(generateTypeDiagFixes); return; } var fixes = generateTypeDiagFixes.Item2.Fixes; Assert.NotNull(fixes); var fixActions = fixes.Select(f => f.Action); Assert.NotNull(fixActions); // Since the dialog option is always fed as the last CodeAction var index = fixActions.Count() - 1; var action = fixActions.ElementAt(index); Assert.Equal(action.Title, FeaturesResources.GenerateNewType); var options = ((CodeActionWithOptions)action).GetOptions(CancellationToken.None); var operations = ((CodeActionWithOptions)action).GetOperationsAsync(options, CancellationToken.None).Result; Tuple<Solution, Solution> oldSolutionAndNewSolution = null; if (!isNewFile) { oldSolutionAndNewSolution = TestActions(testState.Workspace, expected, operations, testState.ExistingDocument.Id, compareTokens: false); } else { oldSolutionAndNewSolution = TestAddDocument( testState.Workspace, expected, operations, projectName != null, testState.ProjectToBeModified.Id, newFileFolderContainers, newFileName, compareTokens: false); } if (checkIfUsingsIncluded) { Assert.NotNull(expectedTextWithUsings); TestActions(testState.Workspace, expectedTextWithUsings, operations, testState.InvocationDocument.Id, compareTokens: false); } if (checkIfUsingsNotIncluded) { var oldSolution = oldSolutionAndNewSolution.Item1; var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id)); } // Added into a different project than the triggering project if (projectName != null) { var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations); var newSolution = appliedChanges.Item2; var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id); // Make sure the Project reference is present Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id)); } // Assert Option Calculation if (assertClassName != null) { Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName); } if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null) { var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions; if (assertGenerateTypeDialogOptions != null) { Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility); Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions); Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute); } if (assertTypeKindPresent != null) { foreach (var typeKindPresentEach in assertTypeKindPresent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0); } } if (assertTypeKindAbsent != null) { foreach (var typeKindPresentEach in assertTypeKindAbsent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0); } } } } } } }
//--------------------------------------------------------------------------- // // <copyright file="ScaleTransform.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class ScaleTransform : Transform { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new ScaleTransform Clone() { return (ScaleTransform)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new ScaleTransform CloneCurrentValue() { return (ScaleTransform)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void ScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform target = ((ScaleTransform) d); target.PropertyChanged(ScaleXProperty); } private static void ScaleYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform target = ((ScaleTransform) d); target.PropertyChanged(ScaleYProperty); } private static void CenterXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform target = ((ScaleTransform) d); target.PropertyChanged(CenterXProperty); } private static void CenterYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform target = ((ScaleTransform) d); target.PropertyChanged(CenterYProperty); } #region Public Properties /// <summary> /// ScaleX - double. Default value is 1.0. /// </summary> public double ScaleX { get { return (double) GetValue(ScaleXProperty); } set { SetValueInternal(ScaleXProperty, value); } } /// <summary> /// ScaleY - double. Default value is 1.0. /// </summary> public double ScaleY { get { return (double) GetValue(ScaleYProperty); } set { SetValueInternal(ScaleYProperty, value); } } /// <summary> /// CenterX - double. Default value is 0.0. /// </summary> public double CenterX { get { return (double) GetValue(CenterXProperty); } set { SetValueInternal(CenterXProperty, value); } } /// <summary> /// CenterY - double. Default value is 0.0. /// </summary> public double CenterY { get { return (double) GetValue(CenterYProperty); } set { SetValueInternal(CenterYProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new ScaleTransform(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Obtain handles for animated properties DUCE.ResourceHandle hScaleXAnimations = GetAnimationResourceHandle(ScaleXProperty, channel); DUCE.ResourceHandle hScaleYAnimations = GetAnimationResourceHandle(ScaleYProperty, channel); DUCE.ResourceHandle hCenterXAnimations = GetAnimationResourceHandle(CenterXProperty, channel); DUCE.ResourceHandle hCenterYAnimations = GetAnimationResourceHandle(CenterYProperty, channel); // Pack & send command packet DUCE.MILCMD_SCALETRANSFORM data; unsafe { data.Type = MILCMD.MilCmdScaleTransform; data.Handle = _duceResource.GetHandle(channel); if (hScaleXAnimations.IsNull) { data.ScaleX = ScaleX; } data.hScaleXAnimations = hScaleXAnimations; if (hScaleYAnimations.IsNull) { data.ScaleY = ScaleY; } data.hScaleYAnimations = hScaleYAnimations; if (hCenterXAnimations.IsNull) { data.CenterX = CenterX; } data.hCenterXAnimations = hCenterXAnimations; if (hCenterYAnimations.IsNull) { data.CenterY = CenterY; } data.hCenterYAnimations = hCenterYAnimations; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_SCALETRANSFORM)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_SCALETRANSFORM)) { AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the ScaleTransform.ScaleX property. /// </summary> public static readonly DependencyProperty ScaleXProperty; /// <summary> /// The DependencyProperty for the ScaleTransform.ScaleY property. /// </summary> public static readonly DependencyProperty ScaleYProperty; /// <summary> /// The DependencyProperty for the ScaleTransform.CenterX property. /// </summary> public static readonly DependencyProperty CenterXProperty; /// <summary> /// The DependencyProperty for the ScaleTransform.CenterY property. /// </summary> public static readonly DependencyProperty CenterYProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal const double c_ScaleX = 1.0; internal const double c_ScaleY = 1.0; internal const double c_CenterX = 0.0; internal const double c_CenterY = 0.0; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static ScaleTransform() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(ScaleTransform); ScaleXProperty = RegisterProperty("ScaleX", typeof(double), typeofThis, 1.0, new PropertyChangedCallback(ScaleXPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); ScaleYProperty = RegisterProperty("ScaleY", typeof(double), typeofThis, 1.0, new PropertyChangedCallback(ScaleYPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterXProperty = RegisterProperty("CenterX", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterXPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterYProperty = RegisterProperty("CenterY", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterYPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using MiniJSON; /* * Session M service implementation. Implements and provides access (via SessionM.GetInstance()) to the SessionM service. */ public class SessionM : MonoBehaviour { private ISessionMCallback callback; public string iosAppId; public string androidAppId; public LogLevel logLevel; //The SessionM Class is a monobehaviour Singleton. Drop the Gameobject in your scene and set it up instead of trying to instantiate it via code. //Put the SessionM object as early in your project as possible. The object will survive loads, so there's never a reason to put it in more than one place in your scenes. private static SessionM instance; public static SessionM GetInstance() { if(instance == null) { SessionM existingSessionM = GameObject.FindObjectOfType<SessionM>(); if(existingSessionM == null) { Debug.LogError("There is no SessionM GameObject set up in the scene. Please add one and set it up as per the SessionM Plug-In Documentation."); return null; } existingSessionM.SetSessionMNative(); instance = existingSessionM; } return instance; } public static ServiceRegion serviceRegion = ServiceRegion.USA; //Call this method before starting the session to set the service region. public static void SetServiceRegion(ServiceRegion region) { serviceRegion = region; } //Here, SessionM instantiates the appropiate Native interface to be used on each platform. //iOS: iSessionM_IOS //Android: iSessionM_Android //All others: iSessionM_Dummy (The Dummy simply catches all calls coming into SessionM un unsupported platforms.) //If you need to modify how SessionM is interacting with either iOS or Android natively, please look in the respective Interface Class. private ISessionM sessionMNative; public ISessionM SessionMNative { get { return sessionMNative; } } //The following methods can be called at anytime via the SessionM Singleton. //For instance, you can call GetSessionState from anywhere in Unity program by aclling SessionM.GetInstance().GetSessionState() //Returns SessionM's current SessionState //Can be: Stopped, Started Online, Started Offline //Use this method to determine if your user is in a valid region for SessionM. If SessionM is in a Stopped State, you should //suppress SessionM elements. public SessionState GetSessionState() { return sessionMNative.GetSessionState(); } //Use this method for displaying a badge or other SessionM tools. Remember, your Acheivement count can accumulate over days, so be sure to support at least //triple digit numbers. public int GetUnclaimedAchievementCount() { return sessionMNative.GetUnclaimedAchievementCount(); } //Use this method to get current user data. public UserData GetUserData() { UserData userData = null; string userDataJSON = null; userDataJSON = sessionMNative.GetUser(); if(userDataJSON == null) { return null; } userData = GetUserData(userDataJSON); return userData; } //Use this method to set user opt-out status public void SetUserOptOutStatus(bool status){ sessionMNative.SetUserOptOutStatus(status); } //Use this method to set the value of shouldAutoUpdateAchievementsList public void SetShouldAutoUpdateAchievementsList(bool shouldAutoUpdate) { sessionMNative.SetShouldAutoUpdateAchievementsList(shouldAutoUpdate); } //Use this method to manually update the user's achievementsList field. Has no effect if shouldAutoUpdateAchievementsList is set to true. public void UpdateAchievementsList() { sessionMNative.UpdateAchievementsList(); } //This method is required for displaying Native Acheivements. Fore more information, please see the Unity plugin documetnation. public AchievementData GetUnclaimedAchievementData() { IAchievementData achievementData = null; string achievementJSON = null; achievementJSON = sessionMNative.GetUnclaimedAchievementData(); if(achievementJSON == null) { return null; } achievementData = GetAchievementData(achievementJSON); return achievementData as AchievementData; } //This method is vital to using SessionM, whenever your user completes an action that contributes towards a SessionM Acheivement //report it to SessionM using this method. public void LogAction(string action) { sessionMNative.LogAction(action); } //You can use this method if multiple actions were achieved simultaneously. public void LogAction(string action, int count) { sessionMNative.LogAction(action, count); } //Use this method to display an Acheivement if there is an unclaimed Achievement ready. SessionM will automatically display an overlay //Acheivement display for you. You can see if there is an achievement ready by running the IsActivityAvailable method below. public bool PresentActivity(ActivityType type) { return sessionMNative.PresentActivity(type); } public bool IsActivityAvailable(ActivityType type) { return sessionMNative.IsActivityAvailable(type); } //Use this to display the SessionM Portal. You can use this after users have clicked on a Native Acheivement, or when they click on a SessionM //button in your app. public bool ShowPortal() { return PresentActivity(ActivityType.Portal); } //The following methods are generally used for debugging and won't be utilized by most SessionM Developers. public string GetSDKVersion() { return sessionMNative.GetSDKVersion(); } public string[] GetRewards() { return UnpackJSONArray(sessionMNative.GetRewards()); } public LogLevel GetLogLevel() { return sessionMNative.GetLogLevel(); } public void SetLogLevel(LogLevel level) { //Note Log Level only works on iOS. For Android, use logcat. //LogLevel can also be set on the SessionM Object. sessionMNative.SetLogLevel(level); } public bool IsActivityPresented() { return sessionMNative.IsActivityPresented(); } public void SetMetaData(string data, string key) { sessionMNative.SetMetaData(data, key); } public void NotifyPresented() { sessionMNative.NotifyPresented(); } public void NotifyDismissed() { sessionMNative.NotifyDismissed(); } public void NotifyClaimed() { sessionMNative.NotifyClaimed(); } public void DismissActivity() { sessionMNative.DismissActivity(); } public void SetCallback(ISessionMCallback callback) { sessionMNative.SetCallback(callback); } public ISessionMCallback GetCallback() { return sessionMNative.GetCallback(); } // Unity Lifecycle private void Awake() { if (instance != null) { GameObject.Destroy(this); GameObject.Destroy(this.gameObject); return; } SetSessionMNative(); GameObject.DontDestroyOnLoad(this.gameObject); SetLogLevel (logLevel); instance = this; } private void SetSessionMNative() { if(sessionMNative != null) return; //Assign the appropiate Native Class to handle method calls here. #if UNITY_EDITOR sessionMNative = new ISessionM_Dummy(); #elif UNITY_IOS sessionMNative = new ISessionM_iOS(this); #elif UNITY_ANDROID sessionMNative = new ISessionM_Android(this); #else sessionMNative = new ISessionM_Dummy(); #endif } //This is a useful method you can call whenever you need to parse a JSON string into a the IAchievementData custom class. public static IAchievementData GetAchievementData(string jsonString) { Dictionary<string, object> achievementDict = Json.Deserialize(jsonString) as Dictionary<string,object>; long mpointValue = (Int64)achievementDict["mpointValue"]; long timesEarned = (Int64)achievementDict["timesEarned"]; long unclaimedCount = (Int64)achievementDict["unclaimedCount"]; long distance = (Int64)achievementDict["distance"]; bool isCustom = (bool)achievementDict["isCustom"]; string identifier = (string)achievementDict["identifier"]; string importID = (string)achievementDict["importID"]; string instructions = (string)achievementDict["instructions"]; string achievementIconURL = (string)achievementDict["achievementIconURL"]; string action = (string)achievementDict["action"]; string name = (string)achievementDict["name"]; string message = (string)achievementDict["message"]; string limitText = (string)achievementDict["limitText"]; DateTime lastEarnedDate = new DateTime((Int64)achievementDict["lastEarnedDate"], DateTimeKind.Utc); IAchievementData achievementData = new AchievementData(identifier, importID, instructions, achievementIconURL, action, name, message, limitText, (int)mpointValue, isCustom, lastEarnedDate, (int)timesEarned, (int)unclaimedCount, (int)distance); return achievementData; } //This is a useful method you can call whenever you need to parse a JSON string into a the UserData custom class. public static UserData GetUserData(string jsonString) { Dictionary<string, object> userDict = Json.Deserialize(jsonString) as Dictionary<string, object>; bool isOptedOut = (bool)userDict["isOptedOut"]; bool isRegistered = (bool)userDict["isRegistered"]; bool isLoggedIn = (bool)userDict["isLoggedIn"]; long userPointBalance = (Int64)userDict["getPointBalance"]; long unclaimedAchievementCount = (Int64)userDict["getUnclaimedAchievementCount"]; long unclaimedAchievementValue = (Int64)userDict["getUnclaimedAchievementValue"]; string achievementsJSON = (string)userDict["getAchievementsJSON"]; string[] achievementsJSONArray = UnpackJSONArray(achievementsJSON); AchievementData[] achievementsArray = new AchievementData[achievementsJSONArray.Length]; for(int i = 0; i < achievementsJSONArray.Length; i++) { string achievement = achievementsJSONArray[i]; if(achievement == "") { break; } achievementsArray[i] = GetAchievementData(achievement) as AchievementData; } List<AchievementData> achievements = new List<AchievementData>(achievementsArray); string achievementsListJSON = (string)userDict["getAchievementsListJSON"]; string[] achievementsListJSONArray = UnpackJSONArray(achievementsListJSON); AchievementData[] achievementsListArray = new AchievementData[achievementsListJSONArray.Length]; for(int i = 0; i < achievementsListJSONArray.Length; i++) { string achievement = achievementsListJSONArray[i]; if(achievement == "") { break; } achievementsListArray[i] = GetAchievementData(achievement) as AchievementData; } List<AchievementData> achievementsList = new List<AchievementData>(achievementsListArray); UserData userData = new UserData(isOptedOut, isRegistered, isLoggedIn, (int)userPointBalance, (int)unclaimedAchievementCount, (int)unclaimedAchievementValue, achievements, achievementsList); return userData; } private static string[] UnpackJSONArray(string json) { string[] separatorArray = new string[] {"__"}; string[] JSONArray = json.Split(separatorArray, StringSplitOptions.None); return JSONArray; } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.CompilerServices; using NodaTime.TimeZones; namespace NodaTime.Testing.TimeZones { /// <summary> /// Time zone with multiple transitions, created via a builder. /// </summary> public sealed class MultiTransitionDateTimeZone : DateTimeZone { /// <summary> /// Gets the zone intervals within this time zone, in chronological order, spanning the whole time line. /// </summary> /// <value>The zone intervals within this time zone, in chronological order, spanning the whole time line.</value> public ReadOnlyCollection<ZoneInterval> Intervals { get; } /// <summary> /// Gets the transition points between intervals. /// </summary> /// <value>The transition points between intervals.</value> public ReadOnlyCollection<Instant> Transitions { get; } private MultiTransitionDateTimeZone(string id, IList<ZoneInterval> intervals) : base(id, intervals.Count == 1, intervals.Min(x => x.WallOffset), intervals.Max(x => x.WallOffset)) { Intervals = new ReadOnlyCollection<ZoneInterval>(intervals.ToList()); Transitions = new ReadOnlyCollection<Instant>(intervals.Skip(1).Select(x => x.Start).ToList()); } /// <inheritdoc /> public override ZoneInterval GetZoneInterval(Instant instant) { int lower = 0; // Inclusive int upper = Intervals.Count; // Exclusive while (lower < upper) { int current = (lower + upper) / 2; var candidate = Intervals[current]; if (candidate.HasStart && candidate.Start > instant) { upper = current; } else if (candidate.HasEnd && candidate.End <= instant) { lower = current + 1; } else { return candidate; } } // Note: this would indicate a bug. The time zone is meant to cover the whole of time. throw new InvalidOperationException(string.Format("Instant {0} did not exist in time zone {1}", instant, Id)); } /// <inheritdoc /> protected override bool EqualsImpl(DateTimeZone zone) { // Just use reference equality... return ReferenceEquals(this, zone); } /// <inheritdoc /> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } /// <summary> /// Builder to create instances of <see cref="MultiTransitionDateTimeZone"/>. Each builder /// can only be built once. /// </summary> public sealed class Builder : IEnumerable { private readonly List<ZoneInterval> intervals = new List<ZoneInterval>(); private Offset currentStandardOffset; private Offset currentSavings; private string currentName; private bool built = false; /// <summary> /// Gets the ID of the time zone which will be built. /// </summary> /// <value>The ID of the time zone which will be built.</value> public string Id { get; set; } /// <summary> /// Constructs a builder using an ID of "MultiZone", an initial offset of zero (standard and savings), /// and an initial name of "First". /// </summary> public Builder() : this(0, 0) { } /// <summary> /// Constructs a builder using the given first name, standard offset, and a daylight saving /// offset of 0. The ID is initially "MultiZone". /// </summary> /// <param name="firstName">Name of the first zone interval.</param> /// <param name="firstOffsetHours">Standard offset in hours in the first zone interval.</param> public Builder(int firstOffsetHours, string firstName) : this(firstOffsetHours, 0, firstName) { } /// <summary> /// Constructs a builder using the given standard offset and saving offset. The ID is initially "MultiZone". /// </summary> /// <param name="firstStandardOffsetHours">Standard offset in hours in the first zone interval.</param> /// <param name="firstSavingOffsetHours">Standard offset in hours in the first zone interval.</param> public Builder(int firstStandardOffsetHours, int firstSavingOffsetHours) : this(firstStandardOffsetHours, firstSavingOffsetHours, "First") { } /// <summary> /// Constructs a builder using the given first name, standard offset, and daylight saving offset. /// The ID is initially "MultiZone". /// </summary> /// <param name="firstStandardOffsetHours">Standard offset in hours in the first zone interval.</param> /// <param name="firstSavingOffsetHours">Daylight saving offset in hours in the first zone interval.</param> /// <param name="firstName">Name of the first zone interval.</param> public Builder(int firstStandardOffsetHours, int firstSavingOffsetHours, string firstName) { Id = "MultiZone"; currentName = firstName; currentStandardOffset = Offset.FromHours(firstStandardOffsetHours); currentSavings = Offset.FromHours(firstSavingOffsetHours); } /// <summary> /// Adds a transition at the given instant, to the specified new standard offset, /// with no daylight saving. The name is generated from the transition. /// </summary> /// <param name="transition">Instant at which the zone changes.</param> /// <param name="newStandardOffsetHours">The new standard offset, in hours.</param> public void Add(Instant transition, int newStandardOffsetHours) { Add(transition, newStandardOffsetHours, 0); } /// <summary> /// Adds a transition at the given instant, to the specified new standard offset, /// with the new specified daylight saving. The name is generated from the transition. /// </summary> /// <param name="transition">Instant at which the zone changes.</param> /// <param name="newStandardOffsetHours">The new standard offset, in hours.</param> /// <param name="newSavingOffsetHours">The new daylight saving offset, in hours.</param> public void Add(Instant transition, int newStandardOffsetHours, int newSavingOffsetHours) { Add(transition, newStandardOffsetHours, newSavingOffsetHours, "Interval from " + transition); } /// <summary> /// Adds a transition at the given instant, to the specified new standard offset, /// with the new specified daylight saving. The name is generated from the transition. /// </summary> /// <param name="transition">Instant at which the zone changes.</param> /// <param name="newStandardOffsetHours">The new standard offset, in hours.</param> /// <param name="newSavingOffsetHours">The new daylight saving offset, in hours.</param> /// <param name="newName">The new zone interval name.</param> public void Add(Instant transition, int newStandardOffsetHours, int newSavingOffsetHours, string newName) { EnsureNotBuilt(); Instant? previousStart = intervals.Count == 0 ? (Instant?) null : intervals.Last().End; // The ZoneInterval constructor will perform validation. intervals.Add(new ZoneInterval(currentName, previousStart, transition, currentStandardOffset + currentSavings, currentSavings)); currentName = newName; currentStandardOffset = Offset.FromHours(newStandardOffsetHours); currentSavings = Offset.FromHours(newSavingOffsetHours); } /// <summary> /// Builds a <see cref="MultiTransitionDateTimeZone"/> from this builder, invalidating it in the process. /// </summary> /// <returns>The newly-built zone.</returns> public MultiTransitionDateTimeZone Build() { EnsureNotBuilt(); built = true; Instant? previousStart = intervals.Count == 0 ? (Instant?) null : intervals.Last().End; intervals.Add(new ZoneInterval(currentName, previousStart, null, currentStandardOffset + currentSavings, currentSavings)); return new MultiTransitionDateTimeZone(Id, intervals); } private void EnsureNotBuilt() { if (built) { throw new InvalidOperationException("Cannot use a builder after building"); } } /// <summary> /// We don't *really* want to implement this, but we want the collection initializer... /// </summary> IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } } }
// Copyright (c) 2009-2012 David Koontz // Please direct any bugs/comments/suggestions to david@koontzfamily.org // // Thanks to Gabriel Gheorghiu (gabison@gmail.com) for his code submission // that lead to the integration with the iTween visual path editor. // // 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 UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Linq; [CustomEditor(typeof(iTweenEvent))] public class iTweenEventDataEditor : Editor { List<string> trueFalseOptions = new List<string>() {"True", "False"}; Dictionary<string, object> values; Dictionary<string, bool> propertiesEnabled = new Dictionary<string, bool>(); iTweenEvent.TweenType previousType; [MenuItem("Component/iTween/iTweenEvent")] static void AddiTweenEvent () { if(Selection.activeGameObject != null) { Selection.activeGameObject.AddComponent(typeof(iTweenEvent)); } } [MenuItem("Component/iTween/Prepare Visual Editor for Javascript Usage")] static void CopyFilesForJavascriptUsage() { if(Directory.Exists(Application.dataPath + "/iTweenEditor/Helper Classes")) { if(!Directory.Exists(Application.dataPath + "/Plugins")) { Directory.CreateDirectory(Application.dataPath + "/Plugins"); } if(!Directory.Exists(Application.dataPath + "/Plugins/iTweenEditor")) { Directory.CreateDirectory(Application.dataPath + "/Plugins/iTweenEditor"); } FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/Helper Classes", Application.dataPath + "/Plugins/iTweenEditor/Helper Classes"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTweenEvent.cs", Application.dataPath + "/Plugins/iTweenEvent.cs"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTween.cs", Application.dataPath + "/Plugins/iTween.cs"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTweenPath.cs", Application.dataPath + "/Plugins/iTweenPath.cs"); AssetDatabase.Refresh(); } else { EditorUtility.DisplayDialog("Can't move files", "Your files have already been moved", "Ok"); } } [MenuItem("Component/iTween/Donate to support the Visual Editor")] static void Donate() { Application.OpenURL("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WD3GQ6HHD257C"); } public void OnEnable() { var evt = (iTweenEvent)target; foreach(var key in EventParamMappings.mappings[evt.type].Keys) { propertiesEnabled[key] = false; } previousType = evt.type; if(!Directory.Exists(Application.dataPath + "/Gizmos")) { Directory.CreateDirectory(Application.dataPath + "/Gizmos"); } /*if(!File.Exists(Application.dataPath + "/Gizmos/iTweenIcon.tif")) { FileUtil.CopyFileOrDirectory(Application.dataPath + "/iTweenEditor/Gizmos/iTweenIcon.tif", Application.dataPath + "/Gizmos/iTweenIcon.tif"); }*/ } public override void OnInspectorGUI() { var evt = (iTweenEvent)target; values = evt.Values; var keys = values.Keys.ToArray(); foreach(var key in keys) { propertiesEnabled[key] = true; if(typeof(Vector3OrTransform) == EventParamMappings.mappings[evt.type][key]) { var val = new Vector3OrTransform(); if(null == values[key] || typeof(Transform) == values[key].GetType()) { if(null == values[key]) { val.transform = null; } else { val.transform = (Transform)values[key]; } val.selected = Vector3OrTransform.transformSelected; } else if(typeof(Vector3) == values[key].GetType()) { val.vector = (Vector3)values[key]; val.selected = Vector3OrTransform.vector3Selected; } values[key] = val; } if(typeof(Vector3OrTransformArray) == EventParamMappings.mappings[evt.type][key]) { var val = new Vector3OrTransformArray(); if(null == values[key] || typeof(Transform[]) == values[key].GetType()) { if(null == values[key]) { val.transformArray = null; } else { val.transformArray = (Transform[])values[key]; } val.selected = Vector3OrTransformArray.transformSelected; } else if(typeof(Vector3[]) == values[key].GetType()) { val.vectorArray = (Vector3[])values[key]; val.selected = Vector3OrTransformArray.vector3Selected; } else if(typeof(string) == values[key].GetType()) { val.pathName = (string)values[key]; val.selected = Vector3OrTransformArray.iTweenPathSelected; } values[key] = val; } } GUILayout.Label(string.Format("iTween Event Editor v{0}", iTweenEvent.VERSION)); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("Name"); evt.tweenName = EditorGUILayout.TextField(evt.tweenName); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); evt.showIconInInspector = GUILayout.Toggle(evt.showIconInInspector, " Show Icon In Scene"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); evt.playAutomatically = GUILayout.Toggle(evt.playAutomatically, " Play Automatically"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Initial Start Delay (delay begins once the iTweenEvent is played)"); evt.delay = EditorGUILayout.FloatField(evt.delay); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("Event Type"); evt.type = (iTweenEvent.TweenType)EditorGUILayout.EnumPopup(evt.type); GUILayout.EndHorizontal(); if(evt.type != previousType) { foreach(var key in EventParamMappings.mappings[evt.type].Keys) { propertiesEnabled[key] = false; } evt.Values = new Dictionary<string, object>(); previousType = evt.type; return; } var properties = EventParamMappings.mappings[evt.type]; foreach(var pair in properties) { var key = pair.Key; GUILayout.BeginHorizontal(); if(EditorGUILayout.BeginToggleGroup(key, propertiesEnabled[key])) { propertiesEnabled[key] = true; GUILayout.BeginVertical(); if(typeof(string) == pair.Value) { values[key] = EditorGUILayout.TextField(values.ContainsKey(key) ? (string)values[key] : ""); } else if(typeof(float) == pair.Value) { values[key] = EditorGUILayout.FloatField(values.ContainsKey(key) ? (float)values[key] : 0); } else if(typeof(int) == pair.Value) { values[key] = EditorGUILayout.IntField(values.ContainsKey(key) ? (int)values[key] : 0); } else if(typeof(bool) == pair.Value) { GUILayout.BeginHorizontal(); var currentValueString = (values.ContainsKey(key) ? (bool)values[key] : false).ToString(); currentValueString = currentValueString.Substring(0, 1).ToUpper() + currentValueString.Substring(1); var index = EditorGUILayout.Popup(trueFalseOptions.IndexOf(currentValueString), trueFalseOptions.ToArray()); GUILayout.EndHorizontal(); values[key] = bool.Parse(trueFalseOptions[index]); } else if(typeof(GameObject) == pair.Value) { values[key] = EditorGUILayout.ObjectField(values.ContainsKey(key) ? (GameObject)values[key] : null, typeof(GameObject), true); } else if(typeof(Vector3) == pair.Value) { values[key] = EditorGUILayout.Vector3Field("", values.ContainsKey(key) ? (Vector3)values[key] : Vector3.zero); } else if(typeof(Vector3OrTransform) == pair.Value) { if(!values.ContainsKey(key)) { values[key] = new Vector3OrTransform(); } var val = (Vector3OrTransform)values[key]; val.selected = GUILayout.SelectionGrid(val.selected, Vector3OrTransform.choices, 2); if(Vector3OrTransform.vector3Selected == val.selected) { val.vector = EditorGUILayout.Vector3Field("", val.vector); // GUILayout.Label("Number of points"); // GUILayout.Label("Number of points"); // GUILayout.Label("Number of points"); // GUILayout.Label("Number of points"); // GUILayout.Label("Number of points"); // GUILayout.Label("Number of points"); } else { val.transform = (Transform)EditorGUILayout.ObjectField(val.transform, typeof(Transform), true); } values[key] = val; } else if(typeof(Vector3OrTransformArray) == pair.Value) { if(!values.ContainsKey(key)) { values[key] = new Vector3OrTransformArray(); } var val = (Vector3OrTransformArray)values[key]; val.selected = GUILayout.SelectionGrid(val.selected, Vector3OrTransformArray.choices, Vector3OrTransformArray.choices.Length); if(Vector3OrTransformArray.vector3Selected == val.selected) { if(null == val.vectorArray) { val.vectorArray = new Vector3[0]; } var elements = val.vectorArray.Length; GUILayout.BeginHorizontal(); GUILayout.Label("Number of points"); elements = EditorGUILayout.IntField(elements); GUILayout.EndHorizontal(); if(elements != val.vectorArray.Length) { var resizedArray = new Vector3[elements]; val.vectorArray.CopyTo(resizedArray, 0); val.vectorArray = resizedArray; } for(var i = 0; i < val.vectorArray.Length; ++i) { val.vectorArray[i] = EditorGUILayout.Vector3Field("", val.vectorArray[i]); } } else if(Vector3OrTransformArray.transformSelected == val.selected) { if(null == val.transformArray) { val.transformArray = new Transform[0]; } var elements = val.transformArray.Length; GUILayout.BeginHorizontal(); GUILayout.Label("Number of points"); elements = EditorGUILayout.IntField(elements); GUILayout.EndHorizontal(); if(elements != val.transformArray.Length) { var resizedArray = new Transform[elements]; val.transformArray.CopyTo(resizedArray, 0); val.transformArray = resizedArray; } for(var i = 0; i < val.transformArray.Length; ++i) { val.transformArray[i] = (Transform)EditorGUILayout.ObjectField(val.transformArray[i], typeof(Transform), true); } } else if(Vector3OrTransformArray.iTweenPathSelected == val.selected) { var index = 0; var paths = (GameObject.FindObjectsOfType(typeof(iTweenPath)) as iTweenPath[]); if(0 == paths.Length) { val.pathName = ""; GUILayout.Label("No paths are defined"); } else { for(var i = 0; i < paths.Length; ++i) { if(paths[i].pathName == val.pathName) { index = i; } } index = EditorGUILayout.Popup(index, (GameObject.FindObjectsOfType(typeof(iTweenPath)) as iTweenPath[]).Select(path => path.pathName).ToArray()); val.pathName = paths[index].pathName; } } values[key] = val; } else if(typeof(iTween.LoopType) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (iTween.LoopType)values[key] : iTween.LoopType.none); } else if(typeof(iTween.EaseType) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (iTween.EaseType)values[key] : iTween.EaseType.linear); } else if(typeof(AudioSource) == pair.Value) { values[key] = (AudioSource)EditorGUILayout.ObjectField(values.ContainsKey(key) ? (AudioSource)values[key] : null, typeof(AudioSource), true); } else if(typeof(AudioClip) == pair.Value) { values[key] = (AudioClip)EditorGUILayout.ObjectField(values.ContainsKey(key) ? (AudioClip)values[key] : null, typeof(AudioClip), true); } else if(typeof(Color) == pair.Value) { values[key] = EditorGUILayout.ColorField(values.ContainsKey(key) ? (Color)values[key] : Color.white); } else if(typeof(Space) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (Space)values[key] : Space.Self); } GUILayout.EndVertical(); } else { propertiesEnabled[key] = false; values.Remove(key); } EditorGUILayout.EndToggleGroup(); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); } keys = values.Keys.ToArray(); foreach(var key in keys) { if(values[key] != null && values[key].GetType() == typeof(Vector3OrTransform)) { var val = (Vector3OrTransform)values[key]; if(Vector3OrTransform.vector3Selected == val.selected) { values[key] = val.vector; } else { values[key] = val.transform; } } else if(values[key] != null && values[key].GetType() == typeof(Vector3OrTransformArray)) { var val = (Vector3OrTransformArray)values[key]; if(Vector3OrTransformArray.vector3Selected == val.selected) { values[key] = val.vectorArray; } else if(Vector3OrTransformArray.transformSelected == val.selected) { values[key] = val.transformArray; } else if(Vector3OrTransformArray.iTweenPathSelected == val.selected) { values[key] = val.pathName; } } } evt.Values = values; previousType = evt.type; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Orleans.AzureUtils; using Orleans.Providers; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; namespace Orleans.Storage { /// <summary> /// Simple storage provider for writing grain state data to Azure table storage. /// </summary> /// <remarks> /// <para> /// Required configuration params: <c>DataConnectionString</c> /// </para> /// <para> /// Optional configuration params: /// <c>TableName</c> -- defaults to <c>OrleansGrainState</c> /// <c>DeleteStateOnClear</c> -- defaults to <c>false</c> /// </para> /// </remarks> /// <example> /// Example configuration for this storage provider in OrleansConfiguration.xml file: /// <code> /// &lt;OrleansConfiguration xmlns="urn:orleans"> /// &lt;Globals> /// &lt;StorageProviders> /// &lt;Provider Type="Orleans.Storage.AzureTableStorage" Name="AzureStore" /// DataConnectionString="UseDevelopmentStorage=true" /// DeleteStateOnClear="true" /// /> /// &lt;/StorageProviders> /// </code> /// </example> public class AzureTableStorage : IStorageProvider, IRestExceptionDecoder { internal const string DataConnectionStringPropertyName = "DataConnectionString"; internal const string TableNamePropertyName = "TableName"; internal const string DeleteOnClearPropertyName = "DeleteStateOnClear"; internal const string UseJsonFormatPropertyName = "UseJsonFormat"; internal const string TableNameDefaultValue = "OrleansGrainState"; private string dataConnectionString; private string tableName; private string serviceId; private GrainStateTableDataManager tableDataManager; private bool isDeleteStateOnClear; private static int counter; private readonly int id; // each property can hold 64KB of data and each entity can take 1MB in total, so 15 full properties take // 15 * 64 = 960 KB leaving room for the primary key, timestamp etc private const int MAX_DATA_CHUNK_SIZE = 64 * 1024; private const int MAX_STRING_PROPERTY_LENGTH = 32 * 1024; private const int MAX_DATA_CHUNKS_COUNT = 15; private const string BINARY_DATA_PROPERTY_NAME = "Data"; private const string STRING_DATA_PROPERTY_NAME = "StringData"; private bool useJsonFormat; private Newtonsoft.Json.JsonSerializerSettings jsonSettings; /// <summary> Name of this storage provider instance. </summary> /// <see cref="IProvider.Name"/> public string Name { get; private set; } /// <summary> Logger used by this storage provider instance. </summary> /// <see cref="IStorageProvider.Log"/> public Logger Log { get; private set; } /// <summary> Default constructor </summary> public AzureTableStorage() { tableName = TableNameDefaultValue; id = Interlocked.Increment(ref counter); } /// <summary> Initialization function for this storage provider. </summary> /// <see cref="IProvider.Init"/> public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { Name = name; serviceId = providerRuntime.ServiceId.ToString(); if (!config.Properties.ContainsKey(DataConnectionStringPropertyName) || string.IsNullOrWhiteSpace(config.Properties[DataConnectionStringPropertyName])) throw new ArgumentException("DataConnectionString property not set"); dataConnectionString = config.Properties["DataConnectionString"]; if (config.Properties.ContainsKey(TableNamePropertyName)) tableName = config.Properties[TableNamePropertyName]; isDeleteStateOnClear = config.Properties.ContainsKey(DeleteOnClearPropertyName) && "true".Equals(config.Properties[DeleteOnClearPropertyName], StringComparison.OrdinalIgnoreCase); Log = providerRuntime.GetLogger("Storage.AzureTableStorage." + id); var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}", Name, serviceId, tableName, isDeleteStateOnClear); if (config.Properties.ContainsKey(UseJsonFormatPropertyName)) useJsonFormat = "true".Equals(config.Properties[UseJsonFormatPropertyName], StringComparison.OrdinalIgnoreCase); this.jsonSettings = SerializationManager.UpdateSerializerSettings(SerializationManager.GetDefaultJsonSerializerSettings(), config); initMsg = String.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat); Log.Info((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, initMsg); Log.Info((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(dataConnectionString)); tableDataManager = new GrainStateTableDataManager(tableName, dataConnectionString, Log); return tableDataManager.InitTableAsync(); } // Internal method to initialize for testing internal void InitLogger(Logger logger) { Log = logger; } /// <summary> Shutdown this storage provider. </summary> /// <see cref="IProvider.Close"/> public Task Close() { tableDataManager = null; return TaskDone.Done; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IStorageProvider.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_ReadingData, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, pk, grainReference, tableName); string partitionKey = pk; string rowKey = grainType; GrainStateRecord record = await tableDataManager.Read(partitionKey, rowKey).ConfigureAwait(false); if (record != null) { var entity = record.Entity; if (entity != null) { var loadedState = ConvertFromStorageFormat(entity); grainState.State = loadedState ?? Activator.CreateInstance(grainState.State.GetType()); grainState.ETag = record.ETag; } } // Else leave grainState in previous default condition } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IStorageProvider.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Writing: GrainType={0} Pk={1} Grainid={2} ETag={3} to Table={4}", grainType, pk, grainReference, grainState.ETag, tableName); var entity = new DynamicTableEntity(pk, grainType); ConvertToStorageFormat(grainState.State, entity); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; try { await tableDataManager.Write(record); grainState.ETag = record.ETag; } catch (Exception exc) { Log.Error((int)AzureProviderErrorCode.AzureTableProvider_WriteError, string.Format("Error Writing: GrainType={0} Grainid={1} ETag={2} to Table={3} Exception={4}", grainType, grainReference, grainState.ETag, tableName, exc.Message), exc); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IStorageProvider.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, pk, grainReference, grainState.ETag, isDeleteStateOnClear, tableName); var entity = new DynamicTableEntity(pk, grainType); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; string operation = "Clearing"; try { if (isDeleteStateOnClear) { operation = "Deleting"; await tableDataManager.Delete(record).ConfigureAwait(false); } else { await tableDataManager.Write(record).ConfigureAwait(false); } grainState.ETag = record.ETag; // Update in-memory data to the new ETag } catch (Exception exc) { Log.Error((int)AzureProviderErrorCode.AzureTableProvider_DeleteError, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}", operation, grainType, grainReference, grainState.ETag, tableName, exc.Message), exc); throw; } } /// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat(object grainState, DynamicTableEntity entity) { int dataSize; IEnumerable<EntityProperty> properties; string basePropertyName; if (useJsonFormat) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm string data = Newtonsoft.Json.JsonConvert.SerializeObject(grainState, jsonSettings); if (Log.IsVerbose3) Log.Verbose3("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); // each Unicode character takes 2 bytes dataSize = data.Length * 2; properties = SplitStringData(data).Select(t => new EntityProperty(t)); basePropertyName = STRING_DATA_PROPERTY_NAME; } else { // Convert to binary format byte[] data = SerializationManager.SerializeToByteArray(grainState); if (Log.IsVerbose3) Log.Verbose3("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); dataSize = data.Length; properties = SplitBinaryData(data).Select(t => new EntityProperty(t)); basePropertyName = BINARY_DATA_PROPERTY_NAME; } CheckMaxDataSize(dataSize, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT); foreach (var keyValuePair in properties.Zip(GetPropertyNames(basePropertyName), (property, name) => new KeyValuePair<string, EntityProperty>(name, property))) { entity.Properties.Add(keyValuePair); } } private void CheckMaxDataSize(int dataSize, int maxDataSize) { if (dataSize > maxDataSize) { var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, maxDataSize); Log.Error(0, msg); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } private static IEnumerable<string> SplitStringData(string stringData) { var startIndex = 0; while (startIndex < stringData.Length) { var chunkSize = Math.Min(MAX_STRING_PROPERTY_LENGTH, stringData.Length - startIndex); yield return stringData.Substring(startIndex, chunkSize); startIndex += chunkSize; } } private static IEnumerable<byte[]> SplitBinaryData(byte[] binaryData) { var startIndex = 0; while (startIndex < binaryData.Length) { var chunkSize = Math.Min(MAX_DATA_CHUNK_SIZE, binaryData.Length - startIndex); var chunk = new byte[chunkSize]; Array.Copy(binaryData, startIndex, chunk, 0, chunkSize); yield return chunk; startIndex += chunkSize; } } private static IEnumerable<string> GetPropertyNames(string basePropertyName) { yield return basePropertyName; for (var i = 1; i < MAX_DATA_CHUNKS_COUNT; ++i) { yield return basePropertyName + i; } } private static IEnumerable<byte[]> ReadBinaryDataChunks(DynamicTableEntity entity) { foreach (var binaryDataPropertyName in GetPropertyNames(BINARY_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(binaryDataPropertyName, out dataProperty)) { switch (dataProperty.PropertyType) { // if TablePayloadFormat.JsonNoMetadata is used case EdmType.String: var stringValue = dataProperty.StringValue; if (!string.IsNullOrEmpty(stringValue)) { yield return Convert.FromBase64String(stringValue); } break; // if any payload type providing metadata is used case EdmType.Binary: var binaryValue = dataProperty.BinaryValue; if (binaryValue != null && binaryValue.Length > 0) { yield return binaryValue; } break; } } } } private static byte[] ReadBinaryData(DynamicTableEntity entity) { var dataChunks = ReadBinaryDataChunks(entity).ToArray(); var dataSize = dataChunks.Select(d => d.Length).Sum(); var result = new byte[dataSize]; var startIndex = 0; foreach (var dataChunk in dataChunks) { Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length); startIndex += dataChunk.Length; } return result; } private static IEnumerable<string> ReadStringDataChunks(DynamicTableEntity entity) { foreach (var stringDataPropertyName in GetPropertyNames(STRING_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(stringDataPropertyName, out dataProperty)) { var data = dataProperty.StringValue; if (!string.IsNullOrEmpty(data)) { yield return data; } } } } private static string ReadStringData(DynamicTableEntity entity) { return string.Join(string.Empty, ReadStringDataChunks(entity)); } /// <summary> /// Deserialize from Azure storage format /// </summary> /// <param name="entity">The Azure table entity the stored data</param> internal object ConvertFromStorageFormat(DynamicTableEntity entity) { var binaryData = ReadBinaryData(entity); var stringData = ReadStringData(entity); object dataValue = null; try { if (binaryData.Length > 0) { // Rehydrate dataValue = SerializationManager.DeserializeFromByteArray<object>(binaryData); } else if (!string.IsNullOrEmpty(stringData)) { dataValue = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(stringData, jsonSettings); } // Else, no data found } catch (Exception exc) { var sb = new StringBuilder(); if (binaryData.Length > 0) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData); } else if (!string.IsNullOrEmpty(stringData)) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData); } if (dataValue != null) { sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType()); } Log.Error(0, sb.ToString(), exc); throw new AggregateException(sb.ToString(), exc); } return dataValue; } private string GetKeyString(GrainReference grainReference) { var key = String.Format("{0}_{1}", serviceId, grainReference.ToKeyString()); return AzureStorageUtils.SanitizeTableProperty(key); } internal class GrainStateRecord { public string ETag { get; set; } public DynamicTableEntity Entity { get; set; } } private class GrainStateTableDataManager { public string TableName { get; private set; } private readonly AzureTableDataManager<DynamicTableEntity> tableManager; private readonly Logger logger; public GrainStateTableDataManager(string tableName, string storageConnectionString, Logger logger) { this.logger = logger; TableName = tableName; tableManager = new AzureTableDataManager<DynamicTableEntity>(tableName, storageConnectionString); } public Task InitTableAsync() { return tableManager.InitTableAsync(); } public async Task<GrainStateRecord> Read(string partitionKey, string rowKey) { if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); try { Tuple<DynamicTableEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false); if (data == null || data.Item1 == null) { if (logger.IsVerbose2) logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); return null; } DynamicTableEntity stateEntity = data.Item1; var record = new GrainStateRecord { Entity = stateEntity, ETag = data.Item2 }; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag); return record; } catch (Exception exc) { if (AzureStorageUtils.TableStorageDataNotFound(exc)) { if (logger.IsVerbose2) logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, LogFormatter.PrintException(exc)); return null; // No data } throw; } } public async Task Write(GrainStateRecord record) { var entity = record.Entity; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Writing: PartitionKey={0} RowKey={1} to Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); string eTag = String.IsNullOrEmpty(record.ETag) ? await tableManager.CreateTableEntryAsync(entity).ConfigureAwait(false) : await tableManager.UpdateTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = eTag; } public async Task Delete(GrainStateRecord record) { var entity = record.Entity; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Deleting: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); await tableManager.DeleteTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = null; } } /// <summary> Decodes Storage exceptions.</summary> public bool DecodeException(Exception e, out HttpStatusCode httpStatusCode, out string restStatus, bool getRESTErrors = false) { return AzureStorageUtils.EvaluateException(e, out httpStatusCode, out restStatus, getRESTErrors); } } }